HummingbirdCore

基于 Swift NIO 的 HTTP 服务器。它是 Hummingbird Web 框架 v1.0 的核心 HTTP 服务器组件。

用法

HummingbirdCore 包含一个基于 Swift NIO 的 HTTP 服务器。启动服务器时,您需要提供一个符合 HBHTTPResponder 协议的结构体,以定义服务器应该如何响应请求。例如,以下是一个始终返回包含 "Hello" 单词的响应体的 responder。

struct HelloResponder: HBHTTPResponder {
    func respond(to request: HBHTTPRequest, context: ChannelHandlerContext, onComplete: @escaping (Result<HBHTTPResponse, Error>) -> Void) {
        let responseHead = HTTPResponseHead(version: .init(major: 1, minor: 1), status: .ok)
        let responseBody = context.channel.allocator.buffer(string: "Hello")
        let response = HBHTTPResponse(head: responseHead, body: .byteBuffer(responseBody))
        onComplete(.success(response))
    }
}

以下代码将使用上述 HelloResponder 启动一个服务器。

let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)
let server = HBHTTPServer(
    group: eventLoopGroup, 
    configuration: .init(address: .hostname("127.0.0.1", port: 8080))
)
try server.start(responder: HelloResponder()).wait()
// Wait until server closes which never happens as server channel is never closed
try server.wait()

Swift 服务生命周期

如果您在 Hummingbird 之外使用 HummingbirdCore,理想情况下,您应该将其与 swift-server 库 swift-service-lifecycle 一起使用。 这为您提供了一个框架,用于干净地初始化和关闭服务器。 以下代码设置了一个 Lifecycle,它初始化 HTTP 服务器并在应用程序关闭时停止它。

import Lifecycle
import LifecycleNIOCompat

let lifecycle = ServiceLifecycle()
lifecycle.register(
    label: "HTTP Server",
    start: .eventLoopFuture { self.server.start(responder: MyResponder()) },
    shutdown: .eventLoopFuture(self.server.stop)
)
lifecycle.start { error in
    if let error = error {
        print("ERROR: \(error)")
    }
}
lifecycle.wait()

HummingbirdCore 扩展

可以通过 HummingbirdTLS 和 HummingbirdHTTP2 库扩展 HummingbirdCore,以支持 TLS 和 HTTP2。 以下代码将添加 TLS 支持

import HummingbirdTLS
server.addTLS(tlsConfiguration: myTLSConfiguration)

以下代码将添加 HTTP2 升级选项

import HummingbirdHTTP2
server.addHTTP2Upgrade(tlsConfiguration: myTLSConfiguration)

由于 HTTP2 升级需要 TLS 连接,因此在启用 HTTP2 升级时会自动添加 TLS 连接。 因此,不要同时调用这两个函数,因为这会设置两个 TLS 处理程序。

文档

HummingbirdCore 和 Hummingbird 的参考文档可以在此处找到