Kaynağa Gözat

Added middleware to the stable build (2.2.x).

Damian Kołakowski 10 yıl önce
ebeveyn
işleme
ef0f703323

+ 5 - 0
Sources/DemoServer.swift

@@ -125,5 +125,10 @@ public func demoServer(publicDir: String) -> HttpServer {
         return .MovedPermanently("https://github.com/404")
     }
     
+    server.middleware.append { r in
+        print("Middleware:\(r.method) \(r.path)")
+        return nil
+    }
+    
     return server
 }

+ 11 - 4
Sources/HttpServer.swift

@@ -35,7 +35,7 @@ public class HttpServer: HttpServerIO {
     
     public var DELETE, UPDATE, HEAD, POST, GET, PUT : MethodRoute
     public var delete, update, head, post, get, put : MethodRoute
-
+    
     public subscript(path: String) -> (HttpRequest -> HttpResponse)? {
         set {
             router.register(nil, path: path, handler: newValue)
@@ -48,15 +48,22 @@ public class HttpServer: HttpServerIO {
     }
     
     public var notFoundHandler: (HttpRequest -> HttpResponse)?
+    
+    public var middleware = Array<(HttpRequest) -> HttpResponse?>()
 
-    override public func dispatch(method: String, path: String) -> ([String:String], HttpRequest -> HttpResponse) {
-        if let result = router.route(method, path: path) {
+    override public func dispatch(request: HttpRequest) -> ([String:String], HttpRequest -> HttpResponse) {
+        for layer in middleware {
+            if let response = layer(request) {
+                return ([:], { _ in response })
+            }
+        }
+        if let result = router.route(request.method, path: request.path) {
             return result
         }
         if let notFoundHandler = self.notFoundHandler {
             return ([:], notFoundHandler)
         }
-        return super.dispatch(method, path: path)
+        return super.dispatch(request)
     }
     
     public struct MethodRoute {

+ 2 - 2
Sources/HttpServerIO.swift

@@ -46,7 +46,7 @@ public class HttpServerIO {
         }
     }
     
-    public func dispatch(method: String, path: String) -> ([String: String], HttpRequest -> HttpResponse) {
+    public func dispatch(request: HttpRequest) -> ([String: String], HttpRequest -> HttpResponse) {
         return ([:], { _ in HttpResponse.NotFound })
     }
     
@@ -55,7 +55,7 @@ public class HttpServerIO {
         let parser = HttpParser()
         while let request = try? parser.readHttpRequest(socket) {
             let request = request
-            let (params, handler) = self.dispatch(request.method, path: request.path)
+            let (params, handler) = self.dispatch(request)
             request.address = address
             request.params = params;
             let response = handler(request)