Swifter.swift 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. //
  2. // HttpServer.swift
  3. // Swifter
  4. //
  5. // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
  6. //
  7. import Foundation
  8. public class Swifter {
  9. public static let version = "2.0.0a"
  10. private let router: Router<(([String: String], Request, @escaping ((Response) -> Void)) -> Void)>
  11. private let server: Server
  12. public var notFoundHandler: ((Request) -> Response)?
  13. public var middleware = Array<((Request) -> Response?)>()
  14. public init(_ port: in_port_t = 8080) throws {
  15. self.router = Router()
  16. self.server = try Server(port)
  17. }
  18. public func get(_ path: String, _ closure: @escaping (([String: String], Request, @escaping ((Response) -> Void)) -> Void)) {
  19. router.attach("GET", path: path, handler: closure)
  20. }
  21. public func post(_ path: String, _ closure: @escaping (([String: String], Request, @escaping ((Response) -> Void)) -> Void)) {
  22. router.attach("POST", path: path, handler: closure)
  23. }
  24. public func put(_ path: String, _ closure: @escaping (([String: String], Request, @escaping ((Response) -> Void)) -> Void)) {
  25. router.attach("PUT", path: path, handler: closure)
  26. }
  27. public func delete(_ path: String, _ closure: @escaping (([String: String], Request, @escaping ((Response) -> Void)) -> Void)) {
  28. router.attach("DELETE", path: path, handler: closure)
  29. }
  30. public func options(_ path: String, _ closure: @escaping (([String: String], Request, @escaping ((Response) -> Void)) -> Void)) {
  31. router.attach("OPTIONS", path: path, handler: closure)
  32. }
  33. public subscript(path: String) -> (([String: String], Request, @escaping ((Response) -> Void)) -> Void)? {
  34. set {
  35. router.attach(nil, path: path, handler: newValue)
  36. }
  37. get { return nil }
  38. }
  39. public var routes: [String] {
  40. return router.routes();
  41. }
  42. public func loop() throws {
  43. try self.server.serve { request, responder in
  44. var middlewareResponse: Response? = nil
  45. for layer in self.middleware {
  46. if let responseFound = layer(request) {
  47. middlewareResponse = responseFound
  48. break
  49. }
  50. }
  51. if let middlewareResponseFound = middlewareResponse {
  52. responder(middlewareResponseFound)
  53. } else {
  54. if let (params, response) = self.router.route(request.method, path: request.path) {
  55. response(params, request, responder)
  56. } else {
  57. if let notFoundHandler = self.notFoundHandler {
  58. responder(notFoundHandler(request))
  59. } else {
  60. responder(Response(404))
  61. }
  62. }
  63. }
  64. }
  65. }
  66. }