浏览代码

Merge pull request #479 from michaelenger/wildcard-end-route

Added support for using ** as a catch-all at the end of a route
Victor Sigler 4 年之前
父节点
当前提交
d8dc616687
共有 3 个文件被更改,包括 19 次插入1 次删除
  1. 1 1
      CHANGELOG.md
  2. 6 0
      Xcode/Sources/HttpRouter.swift
  3. 12 0
      Xcode/Tests/SwifterTestsHttpRouter.swift

+ 1 - 1
CHANGELOG.md

@@ -19,7 +19,7 @@ All notable changes to this project will be documented in this file. Changes not
 # [Unreleased]
 
 ## Added
-
+- Add support for using `**` as a catch-all at the end of a route. ([#479](https://github.com/httpswift/swifter/pull/479)) by [@michaelenger](https://github.com/michaelenger)
 - Set `Content-Type` to HttpBody and Text HttpResponse. ([#474](https://github.com/httpswift/swifter/pull/474)) by [@mtgto](https://github.com/mtgto)
 
 ## Fixed

+ 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