-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathURLResponse+HTTPTypes.swift
62 lines (56 loc) · 2.23 KB
/
URLResponse+HTTPTypes.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2023 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
import HTTPTypes
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
#if !os(WASI)
extension HTTPURLResponse {
/// Create an `HTTPURLResponse` from an `HTTPResponse`.
/// - Parameter httpResponse: The HTTP response to convert from.
/// - Parameter url: The URL of the response.
public convenience init?(httpResponse: HTTPResponse, url: URL) {
var combinedFields = [HTTPField.Name: String](minimumCapacity: httpResponse.headerFields.count)
for field in httpResponse.headerFields {
if let existingValue = combinedFields[field.name] {
combinedFields[field.name] = "\(existingValue), \(field.isoLatin1Value)"
} else {
combinedFields[field.name] = field.isoLatin1Value
}
}
var headerFields = [String: String](minimumCapacity: combinedFields.count)
for (name, value) in combinedFields {
headerFields[name.rawName] = value
}
self.init(url: url, statusCode: httpResponse.status.code, httpVersion: "HTTP/1.1", headerFields: headerFields)
}
/// Convert the `HTTPURLResponse` into an `HTTPResponse`.
public var httpResponse: HTTPResponse? {
guard (0...999).contains(self.statusCode) else {
return nil
}
var response = HTTPResponse(status: .init(code: self.statusCode))
if let fields = self.allHeaderFields as? [String: String] {
response.headerFields.reserveCapacity(fields.count)
for (name, value) in fields {
if let name = HTTPField.Name(name) {
response.headerFields.append(HTTPField(name: name, isoLatin1Value: value))
}
}
}
return response
}
}
#endif