Swift HTTP 类型

Swift HTTP 类型是版本独立的 HTTP 通用类型,专为客户端和服务器设计。它们为 HTTP 请求和响应提供了一组通用的表示形式,侧重于现代 HTTP 功能。

入门

将以下依赖项子句添加到您的 Package.swift 中

dependencies: [
    .package(url: "https://github.com/apple/swift-http-types.git", from: "1.0.0")
]

HTTPTypes 库公开了核心 HTTP 通用类型,包括 HTTPRequestHTTPResponseHTTPFields

HTTPTypesFoundation 库提供了使用新的 HTTP 类型与 Foundation 的便利功能,包括新类型和 Foundation URL 类型之间的双向转换器,以及带有新类型的 URLSession 便利方法。

NIOHTTPTypesNIOHTTPTypesHTTP1NIOHTTPTypesHTTP2 库提供了通道处理器,用于将特定版本的 NIO HTTP 类型转换为新的 HTTP 类型。 它们可以在 swift-nio-extras 中找到。

用法

创建请求

let request = HTTPRequest(method: .get, scheme: "https", authority: "www.example.com", path: "/")

从 Foundation URL 创建请求

var request = HTTPRequest(method: .get, url: URL(string: "https://www.example.com/")!)
request.method = .post
request.path = "/upload"

创建响应

let response = HTTPResponse(status: .ok)

访问和修改标头字段

extension HTTPField.Name {
    static let myCustomHeader = Self("My-Custom-Header")!
}

// Set
request.headerFields[.userAgent] = "MyApp/1.0"
request.headerFields[.myCustomHeader] = "custom-value"
request.headerFields[values: .acceptLanguage] = ["en-US", "zh-Hans-CN"]

// Get
request.headerFields[.userAgent] // "MyApp/1.0"
request.headerFields[.myCustomHeader] // "custom-value"
request.headerFields[.acceptLanguage] // "en-US, zh-Hans-CN"
request.headerFields[values: .acceptLanguage] // ["en-US", "zh-Hans-CN"]

与 URLSession 一起使用

var request = HTTPRequest(method: .post, url: URL(string: "https://www.example.com/upload")!)
request.headerFields[.userAgent] = "MyApp/1.0"
let (responseBody, response) = try await URLSession.shared.upload(for: request, from: requestBody)
guard response.status == .created else {
    // Handle error
}

与 SwiftNIO 一起使用

channel.configureHTTP2Pipeline(mode: .server) { channel in
    channel.pipeline.addHandlers([
        HTTP2FramePayloadToHTTPServerCodec(),
        ExampleChannelHandler()
    ])
}.map { _ in () }
final class ExampleChannelHandler: ChannelDuplexHandler {
    typealias InboundIn = HTTPTypeServerRequestPart
    typealias OutboundOut = HTTPTypeServerResponsePart

    func channelRead(context: ChannelHandlerContext, data: NIOAny) {
        switch unwrapInboundIn(data) {
        case .head(let request):
            // Handle request headers
        case .body(let body):
            // Handle request body
        case .end(let trailers):
            // Handle complete request
            let response = HTTPResponse(status: .ok)
            context.write(wrapOutboundOut(.head(response)), promise: nil)
            context.writeAndFlush(wrapOutboundOut(.end(nil)), promise: nil)
        }
    }
}

开发 HTTP 类型

在大多数情况下,HTTP 类型的开发与其他 SwiftPM 项目一样简单明了。 然而,在您贡献之前,我们有一些流程值得理解。 有关详细信息,请参阅此存储库中的 CONTRIBUTING.md

请注意,所有 HTTP 类型的开发都受到 Swift HTTP 类型行为准则 的约束。