Given the following code:
#if canImport(FoundationEssentials) && canImport(FoundationNetworking)
import FoundationEssentials
import FoundationNetworking
#else
import Foundation
#endif
#if canImport(Darwin)
import Darwin
#else
import Glibc
#endif
class MockURLProtocol: URLProtocol {
override class func canInit(with request: URLRequest) -> Bool {
print("canInit received, header fields are \(request.allHTTPHeaderFields ?? [:])")
return true
}
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
print("canonicalRequest received, header fields are \(request.allHTTPHeaderFields ?? [:])")
return request
}
override func startLoading() {
print("startLoading, got request: \(self.request)")
print("all header fields: \(self.request.allHTTPHeaderFields ?? [:])")
print("header for foo: \(self.request.value(forHTTPHeaderField: "Foo"))")
exit(0)
}
}
var config = URLSessionConfiguration.ephemeral
config.protocolClasses = [MockURLProtocol.self]
config.httpAdditionalHeaders = ["Foo" : "Bar"]
let session = URLSession(configuration: config)
let request = URLRequest(url: URL(string: "http://something.com")!)
print("data is \(try await session.data(for: request))")
If I run this on macOS, the httpAdditionalHeaders make it to URLProtocol.startLoading():
$ swift httptest.swift
canInit received, header fields are ["Foo": "Bar"]
canonicalRequest received, header fields are ["Foo": "Bar"]
startLoading, got request: http://something.com
all header fields: ["Foo": "Bar"]
header for foo: Optional("Bar")
However, if I run the same code on Linux, it does not:
$ container run --rm -v $(pwd):/opt/src -it swift swift /opt/src/httptest.swift
canInit received, header fields are [:]
startLoading, got request: http://something.com
all header fields: [:]
header for foo: nil
Is this expected, am I doing something wrong, or is this a bug? Same behavior results if I start with URLSessionConfiguration.default instead of .ephemeral. I also find it interesting that canonicalRequest() gets called on Darwin, but not on Linux.