HttpServer.swift 2.8 KB

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