mirror of
https://github.com/apple/swift-nio-http2
synced 2026-11-22 04:30:43 +00:00
Motivation: Standardised formatting makes the project cleaner to look at and work on. Modifications: Setup swift-format with the same settings as Swift-NIO Result: Common formatting throughout
172 lines
6.4 KiB
Swift
172 lines
6.4 KiB
Swift
//===----------------------------------------------------------------------===//
|
|
//
|
|
// This source file is part of the SwiftNIO open source project
|
|
//
|
|
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
|
|
// Licensed under Apache License v2.0
|
|
//
|
|
// See LICENSE.txt for license information
|
|
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
|
//
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// This example server currently does not know how to negotiate HTTP/2. That will come in a future enhancement. For now, you can
|
|
// hit it with curl like so: curl --http2-prior-knowledge http://localhost:8888/
|
|
|
|
import Foundation
|
|
import NIOCore
|
|
import NIOHTTP1
|
|
import NIOHTTP2
|
|
import NIOPosix
|
|
|
|
final class HTTP1TestServer: ChannelInboundHandler {
|
|
public typealias InboundIn = HTTPServerRequestPart
|
|
public typealias OutboundOut = HTTPServerResponsePart
|
|
|
|
private var head: HTTPRequestHead? = nil
|
|
|
|
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
|
|
switch self.unwrapInboundIn(data) {
|
|
case .head(let head):
|
|
self.head = head
|
|
return
|
|
case .body:
|
|
return
|
|
case .end:
|
|
// Deliberate fallthrough
|
|
()
|
|
}
|
|
|
|
let requestHead = self.head!
|
|
self.head = nil
|
|
|
|
// Insert an event loop tick here. This more accurately represents real workloads in SwiftNIO, which will not
|
|
// re-entrantly write their response frames.
|
|
let channel = context.channel
|
|
let loopBoundContext = NIOLoopBound(context, eventLoop: context.eventLoop)
|
|
let loopBoundSelf = NIOLoopBound(self, eventLoop: context.eventLoop)
|
|
context.eventLoop.execute {
|
|
channel.getOption(HTTP2StreamChannelOptions.streamID).flatMap { (streamID) -> EventLoopFuture<Void> in
|
|
let http1TestServer = loopBoundSelf.value
|
|
var headers = HTTPHeaders()
|
|
headers.add(name: "content-length", value: "5")
|
|
headers.add(name: "x-stream-id", value: String(Int(streamID)))
|
|
channel.write(
|
|
http1TestServer.wrapOutboundOut(
|
|
HTTPServerResponsePart.head(
|
|
HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok, headers: headers)
|
|
)
|
|
),
|
|
promise: nil
|
|
)
|
|
|
|
if requestHead.method != .HEAD {
|
|
var buffer = channel.allocator.buffer(capacity: 12)
|
|
buffer.writeStaticString("hello")
|
|
channel.write(
|
|
http1TestServer.wrapOutboundOut(HTTPServerResponsePart.body(.byteBuffer(buffer))),
|
|
promise: nil
|
|
)
|
|
}
|
|
|
|
return channel.writeAndFlush(http1TestServer.wrapOutboundOut(HTTPServerResponsePart.end(nil)))
|
|
}.whenComplete { _ in
|
|
loopBoundContext.value.close(promise: nil)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
final class ErrorHandler: ChannelInboundHandler {
|
|
typealias InboundIn = Never
|
|
|
|
func errorCaught(context: ChannelHandlerContext, error: Error) {
|
|
print("Server received error: \(error)")
|
|
context.close(promise: nil)
|
|
}
|
|
}
|
|
|
|
// First argument is the program path
|
|
let arguments = ProcessInfo.processInfo.arguments
|
|
let arg1 = arguments.dropFirst().first
|
|
let arg2 = arguments.dropFirst().dropFirst().first
|
|
let arg3 = arguments.dropFirst().dropFirst().dropFirst().first
|
|
|
|
let defaultHost = "::1"
|
|
let defaultPort: Int = 8888
|
|
let defaultHtdocs = "/dev/null/"
|
|
|
|
enum BindTo {
|
|
case ip(host: String, port: Int)
|
|
case unixDomainSocket(path: String)
|
|
}
|
|
|
|
let htdocs: String
|
|
let bindTarget: BindTo
|
|
switch (arg1, arg1.flatMap { Int($0) }, arg2, arg2.flatMap { Int($0) }, arg3) {
|
|
case (.some(let h), _, _, .some(let p), let maybeHtdocs):
|
|
// second arg an integer --> host port [htdocs]
|
|
bindTarget = .ip(host: h, port: p)
|
|
htdocs = maybeHtdocs ?? defaultHtdocs
|
|
case (_, .some(let p), let maybeHtdocs, _, _):
|
|
// first arg an integer --> port [htdocs]
|
|
bindTarget = .ip(host: defaultHost, port: p)
|
|
htdocs = maybeHtdocs ?? defaultHtdocs
|
|
case (.some(let portString), .none, let maybeHtdocs, .none, .none):
|
|
// couldn't parse as number --> uds-path [htdocs]
|
|
bindTarget = .unixDomainSocket(path: portString)
|
|
htdocs = maybeHtdocs ?? defaultHtdocs
|
|
default:
|
|
htdocs = defaultHtdocs
|
|
bindTarget = BindTo.ip(host: defaultHost, port: defaultPort)
|
|
}
|
|
|
|
let group = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)
|
|
let bootstrap = ServerBootstrap(group: group)
|
|
// Specify backlog and enable SO_REUSEADDR for the server itself
|
|
.serverChannelOption(ChannelOptions.backlog, value: 256)
|
|
.serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
|
|
|
|
// Set the handlers that are applied to the accepted Channels
|
|
.childChannelInitializer { channel in
|
|
channel.configureHTTP2Pipeline(mode: .server) { streamChannel -> EventLoopFuture<Void> in
|
|
streamChannel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).flatMap {
|
|
() -> EventLoopFuture<Void> in
|
|
streamChannel.pipeline.addHandler(HTTP1TestServer())
|
|
}.flatMap { () -> EventLoopFuture<Void> in
|
|
streamChannel.pipeline.addHandler(ErrorHandler())
|
|
}
|
|
}.flatMap { (_: HTTP2StreamMultiplexer) in
|
|
channel.pipeline.addHandler(ErrorHandler())
|
|
}
|
|
}
|
|
|
|
// Enable TCP_NODELAY and SO_REUSEADDR for the accepted Channels
|
|
.childChannelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
|
|
.childChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
|
|
.childChannelOption(ChannelOptions.maxMessagesPerRead, value: 1)
|
|
|
|
defer {
|
|
try! group.syncShutdownGracefully()
|
|
}
|
|
|
|
print("htdocs = \(htdocs)")
|
|
|
|
let channel = try { () -> Channel in
|
|
switch bindTarget {
|
|
case .ip(let host, let port):
|
|
return try bootstrap.bind(host: host, port: port).wait()
|
|
case .unixDomainSocket(let path):
|
|
return try bootstrap.bind(unixDomainSocketPath: path).wait()
|
|
}
|
|
}()
|
|
|
|
print("Server started and listening on \(channel.localAddress!), htdocs path \(htdocs)")
|
|
|
|
// This will never unblock as we don't close the ServerChannel
|
|
try channel.closeFuture.wait()
|
|
|
|
print("Server closed")
|