From 40ca463b5f59934e4ce15a2ae71670f77182ade1 Mon Sep 17 00:00:00 2001 From: Guoye Zhang Date: Tue, 28 Jan 2025 23:10:41 -0800 Subject: [PATCH] Request.url should return nil for situations where it is not applicable (#84) Regular CONNECT requests and OPTIONS * requests do not have URLs --- .../HTTPTypesFoundation/HTTPRequest+URL.swift | 5 ++++ .../HTTPTypesFoundationTests.swift | 25 +++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/Sources/HTTPTypesFoundation/HTTPRequest+URL.swift b/Sources/HTTPTypesFoundation/HTTPRequest+URL.swift index dec2bc2..288299c 100644 --- a/Sources/HTTPTypesFoundation/HTTPRequest+URL.swift +++ b/Sources/HTTPTypesFoundation/HTTPRequest+URL.swift @@ -24,6 +24,11 @@ extension HTTPRequest { /// fields. public var url: URL? { get { + if (self.method == .connect && self.extendedConnectProtocol == nil) + || (self.method == .options && self.path == "*") + { + return nil + } if let schemeField = self.pseudoHeaderFields.scheme, let authorityField = self.pseudoHeaderFields.authority, let pathField = self.pseudoHeaderFields.path diff --git a/Tests/HTTPTypesFoundationTests/HTTPTypesFoundationTests.swift b/Tests/HTTPTypesFoundationTests/HTTPTypesFoundationTests.swift index 627d58c..6302bc7 100644 --- a/Tests/HTTPTypesFoundationTests/HTTPTypesFoundationTests.swift +++ b/Tests/HTTPTypesFoundationTests/HTTPTypesFoundationTests.swift @@ -83,6 +83,31 @@ final class HTTPTypesFoundationTests: XCTestCase { XCTAssertEqual(request4.url?.absoluteString, "https://127.0.0.1:443/") } + func testNilRequestURL() { + let request1 = HTTPRequest( + method: .connect, + scheme: "https", + authority: "www.example.com:443", + path: "www.example.com:443" + ) + XCTAssertNil(request1.url) + + var request2 = HTTPRequest( + method: .connect, + scheme: "https", + authority: "www.example.com", + path: "/" + ) + request2.extendedConnectProtocol = "websocket" + XCTAssertEqual(request2.url?.absoluteString, "https://www.example.com/") + + let request3 = HTTPRequest(method: .options, scheme: "https", authority: "www.example.com", path: "*") + XCTAssertNil(request3.url) + + let request4 = HTTPRequest(method: .options, scheme: "https", authority: "www.example.com", path: "/") + XCTAssertEqual(request4.url?.absoluteString, "https://www.example.com/") + } + func testRequestToFoundation() throws { let request = HTTPRequest( method: .get,