Skip to content

Commit 54d1006

Browse files
authored
Add leading slash in relative URL requests if necessary (#747)
1 parent 07536f6 commit 54d1006

File tree

3 files changed

+34
-1
lines changed

3 files changed

+34
-1
lines changed

Sources/AsyncHTTPClient/HTTPHandler.swift

+1-1
Original file line numberDiff line numberDiff line change
@@ -662,7 +662,7 @@ extension URL {
662662
if self.path.isEmpty {
663663
return "/"
664664
}
665-
return URLComponents(url: self, resolvingAgainstBaseURL: false)?.percentEncodedPath ?? self.path
665+
return URLComponents(url: self, resolvingAgainstBaseURL: true)?.percentEncodedPath ?? self.path
666666
}
667667

668668
var uri: String {

Tests/AsyncHTTPClientTests/HTTPClientInternalTests.swift

+19
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,25 @@ class HTTPClientInternalTests: XCTestCase {
142142
XCTAssertEqual(request12.url.uri, "/some%2Fpathsegment1/pathsegment2")
143143
}
144144

145+
func testURIOfRelativeURLRequest() throws {
146+
let requestNoLeadingSlash = try Request(
147+
url: URL(
148+
string: "percent%2Fencoded/hello",
149+
relativeTo: URL(string: "http://127.0.0.1")!
150+
)!
151+
)
152+
153+
let requestWithLeadingSlash = try Request(
154+
url: URL(
155+
string: "/percent%2Fencoded/hello",
156+
relativeTo: URL(string: "http://127.0.0.1")!
157+
)!
158+
)
159+
160+
XCTAssertEqual(requestNoLeadingSlash.url.uri, "/percent%2Fencoded/hello")
161+
XCTAssertEqual(requestWithLeadingSlash.url.uri, "/percent%2Fencoded/hello")
162+
}
163+
145164
func testChannelAndDelegateOnDifferentEventLoops() throws {
146165
class Delegate: HTTPClientResponseDelegate {
147166
typealias Response = ([Message], [Message])

Tests/AsyncHTTPClientTests/HTTPClientTests.swift

+14
Original file line numberDiff line numberDiff line change
@@ -495,6 +495,20 @@ final class HTTPClientTests: XCTestCaseHTTPClientTestsBaseClass {
495495
XCTAssertEqual(.ok, response.status)
496496
}
497497

498+
func testLeadingSlashRelativeURL() throws {
499+
let noLeadingSlashURL = URL(string: "percent%2Fencoded/hello", relativeTo: URL(string: self.defaultHTTPBinURLPrefix)!)!
500+
let withLeadingSlashURL = URL(string: "/percent%2Fencoded/hello", relativeTo: URL(string: self.defaultHTTPBinURLPrefix)!)!
501+
502+
let noLeadingSlashURLRequest = try HTTPClient.Request(url: noLeadingSlashURL, method: .GET)
503+
let withLeadingSlashURLRequest = try HTTPClient.Request(url: withLeadingSlashURL, method: .GET)
504+
505+
let noLeadingSlashURLResponse = try self.defaultClient.execute(request: noLeadingSlashURLRequest).wait()
506+
let withLeadingSlashURLResponse = try self.defaultClient.execute(request: withLeadingSlashURLRequest).wait()
507+
508+
XCTAssertEqual(noLeadingSlashURLResponse.status, .ok)
509+
XCTAssertEqual(withLeadingSlashURLResponse.status, .ok)
510+
}
511+
498512
func testMultipleContentLengthHeaders() throws {
499513
let body = ByteBuffer(string: "hello world!")
500514

0 commit comments

Comments
 (0)