Selaa lähdekoodia

Added support for using ** as a catch-all at the end of a route

Michael Enger 5 vuotta sitten
vanhempi
sitoutus
ee567a23de
2 muutettua tiedostoa jossa 18 lisäystä ja 0 poistoa
  1. 6 0
      XCode/Sources/HttpRouter.swift
  2. 12 0
      XCode/Tests/SwifterTestsHttpRouter.swift

+ 6 - 0
XCode/Sources/HttpRouter.swift

@@ -151,6 +151,12 @@ open class HttpRouter {
             }
 
             if let startStarNode = node.nodes["**"] {
+                if startStarNode.isEndOfRoute {
+                    // ** at the end of a route works as a catch-all
+                    matchedNodes.append(startStarNode)
+                    return
+                }
+
                 let startStarNodeKeys = startStarNode.nodes.keys
                 currentIndex += 1
                 while currentIndex < count, let pathToken = pattern[currentIndex].removingPercentEncoding {

+ 12 - 0
XCode/Tests/SwifterTestsHttpRouter.swift

@@ -85,6 +85,18 @@ class SwifterTestsHttpRouter: XCTestCase {
         XCTAssertNil(router.route(nil, path: "/a/e/f/g"))
     }
 
+    func testHttpRouterMultiplePathSegmentWildcardTail() {
+
+        router.register(nil, path: "/a/b/**", handler: { _ in
+            return .ok(.htmlBody("OK"))
+        })
+
+        XCTAssertNil(router.route(nil, path: "/"))
+        XCTAssertNil(router.route(nil, path: "/a"))
+        XCTAssertNotNil(router.route(nil, path: "/a/b/c/d/e/f/g"))
+        XCTAssertNil(router.route(nil, path: "/a/e/f/g"))
+    }
+
     func testHttpRouterEmptyTail() {
 
         router.register(nil, path: "/a/b/", handler: { _ in