HttpServer.swift 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //
  2. // HttpServer2.swift
  3. // Swifter
  4. //
  5. // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
  6. //
  7. import Foundation
  8. public class HttpServer: HttpServerIO {
  9. public static let VERSION = "1.1.3"
  10. private let router = HttpRouter()
  11. public override init() {
  12. self.DELETE = MethodRoute(method: "DELETE", router: router)
  13. self.UPDATE = MethodRoute(method: "UPDATE", router: router)
  14. self.HEAD = MethodRoute(method: "HEAD", router: router)
  15. self.POST = MethodRoute(method: "POST", router: router)
  16. self.GET = MethodRoute(method: "GET", router: router)
  17. self.PUT = MethodRoute(method: "PUT", router: router)
  18. }
  19. public var DELETE, UPDATE, HEAD, POST, GET, PUT : MethodRoute
  20. public func get(_ path: String, _ handler: ((HttpRequest) -> HttpResponse)) {
  21. router.register("GET", path: path, handler: handler)
  22. }
  23. public func post(_ path: String, _ handler: ((HttpRequest) -> HttpResponse)) {
  24. router.register("POST", path: path, handler: handler)
  25. }
  26. public func put(_ path: String, _ handler: ((HttpRequest) -> HttpResponse)) {
  27. router.register("PUT", path: path, handler: handler)
  28. }
  29. public func head(_ path: String, _ handler: ((HttpRequest) -> HttpResponse)) {
  30. router.register("HEAD", path: path, handler: handler)
  31. }
  32. public func delete(_ path: String, _ handler: ((HttpRequest) -> HttpResponse)) {
  33. router.register("DELETE", path: path, handler: handler)
  34. }
  35. public func update(_ path: String, _ handler: ((HttpRequest) -> HttpResponse)) {
  36. router.register("UPDATE", path: path, handler: handler)
  37. }
  38. public subscript(path: String) -> ((HttpRequest) -> HttpResponse)? {
  39. set {
  40. router.register(nil, path: path, handler: newValue)
  41. }
  42. get { return nil }
  43. }
  44. public var routes: [String] {
  45. return router.routes();
  46. }
  47. public var notFoundHandler: ((HttpRequest) -> HttpResponse)?
  48. override public func dispatch(_ method: String, path: String) -> ([String:String], (HttpRequest) -> HttpResponse) {
  49. if let result = router.route(method, path: path) {
  50. return result
  51. }
  52. if let notFoundHandler = self.notFoundHandler {
  53. return ([:], notFoundHandler)
  54. }
  55. return super.dispatch(method, path: path)
  56. }
  57. public struct MethodRoute {
  58. public let method: String
  59. public let router: HttpRouter
  60. public subscript(path: String) -> ((HttpRequest) -> HttpResponse)? {
  61. set {
  62. router.register(method, path: path, handler: newValue)
  63. }
  64. get { return nil }
  65. }
  66. }
  67. }