-
Notifications
You must be signed in to change notification settings - Fork 58
Description
Hello,
This issue is a feature request for a new API in the HTTPTypesFoundation module:
extension HTTPRequest {
public func url(baseURL: URL) -> URL?
}
I met a need for this API while using http://github.com/apple/swift-openapi-generator
When writing a ClientMiddleware
that processes http requests performed through URLSession
, I need an absolute Foundation.URL
in order to use various services such as HTTPCookieStorage
.
This package defines a HTTPRequest.url
property that looks very promising.
But the HTTPRequest
I get from OpenAPIRuntime is not absolute. It is relative to a base URL, and its url
property is nil:
struct MyMiddleware: ClientMiddleware {
func intercept(
_ request: HTTPRequest,
body requestBody: HTTPBody?,
baseURL: URL,
operationID: String,
next: (HTTPRequest, HTTPBody?, URL) async throws -> (HTTPResponse, HTTPBody?)
) async throws -> (HTTPResponse, HTTPBody?)
{
print(request.url) // nil
}
}
Since my requests are performed through URLSession
, I was pretty sure to find some code that turns a (request, baseURL) pair into an absolute URL
, suitable for URLRequest
. Indeed, it is there.
This code is not public, so I defined my own version, inspired from the above implementation:
extension HTTPRequest {
/// Returns an absolute URL.
///
/// Inspired from <https://github.com/apple/swift-openapi-urlsession/blob/0.3.0/Sources/OpenAPIURLSession/URLSessionTransport.swift#L185-L208>
func url(baseURL: URL) -> URL? {
guard
var baseUrlComponents = URLComponents(string: baseURL.absoluteString),
let requestUrlComponents = URLComponents(string: path ?? "")
else {
return nil
}
let path = requestUrlComponents.percentEncodedPath
baseUrlComponents.percentEncodedPath += path
baseUrlComponents.percentEncodedQuery = requestUrlComponents.percentEncodedQuery
return baseUrlComponents.url
}
}
Since the implementation is not quite trivial, I believe it is a good candidate for inclusion in HTTPTypesFoundation
.
What do you think?