Skip to content

Commit

Permalink
Ensure endpoint path starts with a "/" (hummingbird-project#164)
Browse files Browse the repository at this point in the history
* Ensure endpoint path starts with a "/"

* comment
  • Loading branch information
adam-fowler committed Jan 25, 2023
1 parent 890934a commit 91b85f8
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
2 changes: 2 additions & 0 deletions Sources/Hummingbird/Router/RouterBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ public final class HBRouterBuilder: HBRouterMethods {
/// - method: http method
/// - responder: handler to call
public func add(_ path: String, method: HTTPMethod, responder: HBResponder) {
// ensure path starts with a "/"
let path = path.starts(with: "/") ? path : "/\(path)"
self.trie.addEntry(.init(path), value: HBEndpointResponders(path: path)) { node in
node.value!.addResponder(for: method, responder: middlewares.constructResponder(finalResponder: responder))
}
Expand Down
32 changes: 32 additions & 0 deletions Tests/HummingbirdTests/RouterTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,38 @@ final class RouterTests: XCTestCase {
}
}

/// Test endpointPath is prefixed with a "/"
func testEndpointPathPrefix() throws {
struct TestEndpointMiddleware: HBMiddleware {
func apply(to request: HBRequest, next: HBResponder) -> EventLoopFuture<HBResponse> {
guard let endpointPath = request.endpointPath else { return next.respond(to: request) }
return request.success(.init(status: .ok, body: .byteBuffer(ByteBuffer(string: endpointPath))))
}
}

let app = HBApplication(testing: .embedded)
app.middleware.add(TestEndpointMiddleware())
app.router.get("test") {
$0.endpointPath
}
app.router.post("/test2") {
$0.endpointPath
}

try app.XCTStart()
defer { app.XCTStop() }

try app.XCTExecute(uri: "/test/", method: .GET) { response in
let body = try XCTUnwrap(response.body)
XCTAssertEqual(String(buffer: body), "/test")
}

try app.XCTExecute(uri: "/test2/", method: .POST) { response in
let body = try XCTUnwrap(response.body)
XCTAssertEqual(String(buffer: body), "/test2")
}
}

/// Test correct endpoints are called from group
func testMethodEndpoint() throws {
let app = HBApplication(testing: .embedded)
Expand Down

0 comments on commit 91b85f8

Please sign in to comment.