### Basic HTTP Server Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/README.md This example demonstrates how to create a basic HTTP server, define a root route, and start the server. ```APIDOC ## Basic HTTP Server ### Description Creates a basic HTTP server that listens on a specified port and responds to requests on the root path. ### Method ```swift let server = HTTPServer(port: 8080) await server.appendRoute("GET /", closure: { request in HTTPResponse(statusCode: .ok, body: "Hello, World!".data(using: .utf8)!) }) try await server.run() ``` ``` -------------------------------- ### Basic HTTP Server Setup Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/README.md Initializes an HTTPServer on a specified port and appends a basic route for the root path. This is a starting point for creating a simple web server. ```swift import FlyingFox let server = HTTPServer(port: 8080) await server.appendRoute("GET /") { request in HTTPResponse(statusCode: .ok, body: "Hello, World!".data(using: .utf8)!) } try await server.run() ``` -------------------------------- ### HTTPVersion Examples Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/httprequest-and-response.md Shows how to use the standard HTTP/1.1 version and initialize a custom HTTPVersion. ```swift HTTPVersion.http11 // "HTTP/1.1" let version = HTTPVersion("HTTP/1.1") ``` -------------------------------- ### Example: Append a GET Route for Users Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/httpserver.md Shows how to add a handler named `usersHandler` for the HTTP route 'GET /api/users' to the server. ```swift await server.appendRoute("GET /api/users", to: usersHandler) ``` -------------------------------- ### Example: Stop HTTPServer Gracefully Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/httpserver.md Demonstrates starting a server in a background task, waiting for a period, then gracefully stopping it with a 3-second timeout before cancelling the task. ```swift let task = Task { try await server.run() } try await Task.sleep(nanoseconds: 5_000_000_000) await server.stop(timeout: 3) task.cancel() ``` -------------------------------- ### HTTPServer Timeout Examples Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/configuration.md Demonstrates setting different timeout values for HTTPServer configuration, ranging from fast requests to long uploads, including an example for no timeout (not recommended for production). ```swift // Fast timeout for high-frequency short requests let config1 = HTTPServer.Configuration(address: .loopback(port: 8080), timeout: 5) // Default timeout for typical APIs let config2 = HTTPServer.Configuration(address: .loopback(port: 8080), timeout: 15) // Long timeout for large file uploads let config3 = HTTPServer.Configuration(address: .loopback(port: 8080), timeout: 120) // No timeout (production not recommended) let config4 = HTTPServer.Configuration(address: .loopback(port: 8080), timeout: .infinity) ``` -------------------------------- ### Custom HTTP Header Example Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/httprequest-and-response.md Demonstrates creating a custom HTTP header using string initialization. ```swift let header = HTTPHeader("X-Custom-Header") ``` -------------------------------- ### Serving Static Files Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/README.md This example demonstrates how to configure the server to serve static files from the local file system. ```APIDOC ## Serving Static Files ### Description Configures routes to serve static files, including a default index file and files from a specific directory. ### Method ```swift await server.appendRoute("GET /", to: .file(named: "index.html")) await server.appendRoute("GET /static/*", to: .directory(subPath: "Public", serverPath: "static")) ``` ``` -------------------------------- ### Example: Create HTTPServer with Socket Addresses Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/flyingsocks.md Demonstrates creating an HTTPServer instance using both standard IP addresses (loopback) and Unix domain sockets. ```swift let server = HTTPServer(address: .loopback(port: 8080)) let unixServer = HTTPServer(address: .unix(path: "/tmp/server.sock")) ``` -------------------------------- ### Start the HTTP Server Source: https://github.com/swhitty/flyingfox/blob/main/README.md Initialize and run the HTTPServer on a specified port. The server runs within the current task. ```swift import FlyingFox let server = HTTPServer(port: 80) try await server.run() ``` -------------------------------- ### Example: Ensure Server is Listening Before Requests Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/httpserver.md Shows how to run the server in a separate task and then use `waitUntilListening()` to confirm it's ready before proceeding, ensuring requests are not sent prematurely. ```swift async let serverTask = server.run() try await server.waitUntilListening() // Safe to make requests now ``` -------------------------------- ### Example: Create HTTPServer with Custom Address Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/httpserver.md Shows how to initialize an HTTPServer using a specific socket address, such as the loopback interface on port 8080. ```swift let address = sockaddr_in.loopback(port: 8080) let server = HTTPServer(address: address) ``` -------------------------------- ### Example: Print HTTPServer Listening Address Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/httpserver.md Demonstrates how to access the `listeningAddress` property and print the address where the server is currently listening. ```swift if let addr = await server.listeningAddress { print("Server listening at \(addr)") } ``` -------------------------------- ### DirectoryHTTPHandler Initializer Example Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/handlers.md Initializes a DirectoryHTTPHandler to serve static files from a specified root directory. ```swift let handler = DirectoryHTTPHandler( root: URL(fileURLWithPath: "/var/www/public") ) ``` -------------------------------- ### WebSocket Upgrade Example Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/README.md Demonstrates upgrading an HTTP connection to a WebSocket connection. An HTTPResponse is returned with a WebSocket handler. ```swift await server.appendRoute("GET /ws") { request in HTTPResponse(webSocket: wsHandler) // Upgrade to WebSocket } ``` -------------------------------- ### EchoFrameHandler Example Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/websockets.md An example implementation of the WSHandler protocol that echoes received frames back to the client. This is useful for testing or simple passthrough scenarios. ```swift struct EchoFrameHandler: WSHandler { func makeFrames(for client: AsyncThrowingStream) async throws -> AsyncStream { AsyncStream { continuation in Task { for try await frame in client { continuation.yield(frame) } continuation.finish() } } } } ``` -------------------------------- ### FileHTTPHandler Initializer Example Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/handlers.md Initializes a FileHTTPHandler to serve a specific HTML file with its content type. ```swift let handler = FileHTTPHandler( path: URL(fileURLWithPath: "/path/to/index.html"), contentType: "text/html" ) ``` -------------------------------- ### Routing with Path Parameters Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/README.md This example shows how to define routes that capture parameters from the URL path and use them in the handler. ```APIDOC ## Routing with Path Parameters ### Description Appends a route that captures an integer parameter from the URL path and uses it in the response. ### Method ```swift await server.appendRoute("GET /users/:id") { (id: Int) in HTTPResponse(statusCode: .ok, body: "User: \(id)".data(using: .utf8)!) } ``` ``` -------------------------------- ### Route Matching Order Example Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/README.md Illustrates how routes are matched in the order they are registered. The first matching route handles the request, demonstrating specificity. ```swift await server.appendRoute("GET /admin/*", to: adminHandler) await server.appendRoute("GET /*", to: defaultHandler) // /admin/dashboard -> adminHandler // /other/path -> defaultHandler ``` -------------------------------- ### EchoMessageHandler Example Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/websockets.md An example implementation of the WSMessageHandler protocol that echoes received messages back to the client. This simplifies message handling by abstracting away frame details. ```swift struct EchoMessageHandler: WSMessageHandler { func makeMessages(for client: AsyncStream) async throws -> AsyncStream { AsyncStream { continuation in Task { for await message in client { continuation.yield(message) } continuation.finish() } } } } ``` -------------------------------- ### WSFrame.close Example Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/websockets.md Example of creating a WebSocket close frame with a specific reason message. This is used to initiate or respond to a connection closure. ```swift WSFrame.close(message: "Server shutting down") ``` -------------------------------- ### Run HTTPServer with Unix Domain Socket Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/configuration.md Example of running an HTTPServer configured to listen on a Unix domain socket. Includes instructions for connecting with netcat. ```swift let config = HTTPServer.Configuration(address: .unix(path: "/tmp/http.sock")) let server = HTTPServer(config: config) try await server.run() // Connect with netcat: // nc -U /tmp/http.sock ``` -------------------------------- ### WSMessage Example Usage Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/websockets.md Demonstrates the creation of various WSMessage types, including text, binary data, and a close message. ```swift let messages: [WSMessage] = [ .text("Hello"), .data("binary data".data(using: .utf8)!), .close(WSCloseCode.normalClosure) ] ``` -------------------------------- ### FileHTTPHandler Range Request Example Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/handlers.md Demonstrates serving a video file with support for partial downloads using Range requests. ```swift await server.appendRoute("GET /video/*", to: .file(named: "video.mp4")) // Supports Range: bytes=0-1000 for partial downloads ``` -------------------------------- ### Custom HTTPHandler Implementation Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/handlers.md Example of a custom handler that only processes GET requests and throws HTTPUnhandledError for others. ```swift struct CustomHandler: HTTPHandler { func handleRequest(_ request: HTTPRequest) async throws -> HTTPResponse { guard request.method == .GET else { throw HTTPUnhandledError() } return HTTPResponse(statusCode: .ok) } } ``` -------------------------------- ### Configure HTTPServer with Loopback Address Source: https://github.com/swhitty/flyingfox/blob/main/README.md Start an HTTPServer listening only on the local loopback interface on a specified port. ```swift // only listens on localhost 8080 let server = HTTPServer(address: .loopback(port: 8080)) ``` -------------------------------- ### AsyncSocketPool.run() Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/flyingsocks.md Starts the event loop for the socket pool, processing events. ```APIDOC ## AsyncSocketPool.run() ### Description Runs the event loop for the socket pool, processing socket events. ### Method `async throws` ### Parameters None ### Endpoint N/A (This is a method on an `AsyncSocketPool` instance) ### Request Example ```swift // try await socketPool.run() ``` ### Response #### Success Response None (The loop typically runs indefinitely until stopped or an error occurs) #### Response Example None ERROR HANDLING: - `SocketError` — event loop failed ``` -------------------------------- ### Async Request/Response Handling Example Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/README.md Demonstrates handling an HTTP request asynchronously, including fetching data using await. The handler returns an HTTPResponse with the fetched data. ```swift await server.appendRoute("GET /data") { request in // Can use async/await here let data = try await fetchData() return HTTPResponse(statusCode: .ok, body: data) } ``` -------------------------------- ### Configure HTTPServer with Unix Domain Socket Source: https://github.com/swhitty/flyingfox/blob/main/README.md Start an HTTPServer listening on a Unix domain socket at the specified path for inter-process communication. ```swift // only listens on Unix socket "Ants" let server = HTTPServer(address: .unix(path: "Ants")) ``` -------------------------------- ### Create WebSocket Close Code Instance Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/websockets.md Example of how to create an instance of a WebSocket close code with a specific code and reason. ```swift let closeCode = WSCloseCode(1000, reason: "Normal closure") ``` -------------------------------- ### Configure Server Using Environment Variables Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/configuration.md While FlyingFox does not directly use environment variables, this example shows how to load configuration values like port and timeout from environment variables and apply them to the server configuration. ```swift let port = UInt16(ProcessInfo.processInfo.environment["PORT"] ?? "8080") ?? 8080 let timeout = TimeInterval(ProcessInfo.processInfo.environment["REQUEST_TIMEOUT"] ?? "30") ?? 30 let config = HTTPServer.Configuration( address: sockaddr_in.inet(port: port), timeout: timeout ) let server = HTTPServer(config: config) try await server.run() ``` -------------------------------- ### Install FlyingFox with Swift Package Manager Source: https://github.com/swhitty/flyingfox/blob/main/README.md Add the FlyingFox package to your project's dependencies in Package.swift. ```swift .package(url: "https://github.com/swhitty/FlyingFox.git", .upToNextMajor(from: "0.26.0")) ``` -------------------------------- ### Timeout Handling with withThrowingTimeout Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/errors.md Shows how to wrap an asynchronous operation, like starting an HTTPServer, with a timeout to prevent indefinite execution. ```swift do { let server = HTTPServer(port: 8080) try await withThrowingTimeout(seconds: 30) { try await server.run() } } catch let error as SocketError { if case .timeout(let message) = error { print("Server timeout: \(message)") } } ``` -------------------------------- ### Type-Safe Route Parameters Example Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/README.md Illustrates defining routes with type-safe parameters. Route parameters are automatically converted to the specified types (e.g., Int) at definition time. ```swift await server.appendRoute("GET /items/:id?page=:num") { (id: Int, num: Int) in // id and num are automatically Int, with type checking at route definition return HTTPResponse(statusCode: .ok) } ``` -------------------------------- ### Run HTTPServer Indefinitely Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/httpserver.md Starts the HTTP server, making it listen for incoming connections. This method runs until explicitly stopped or the parent task is cancelled. It throws SocketError on binding failure. ```swift public func run() async throws ``` -------------------------------- ### WebSocket Handshake Error Response Example Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/errors.md Illustrates the structure of an HTTP response returned when a WebSocket handshake fails due to invalid headers or missing required information. ```swift HTTPResponse( version: .http11, statusCode: .badRequest, headers: [:], body: error.localizedDescription.data(using: .utf8)! ) ``` -------------------------------- ### Initialize HTTPServer with Configuration Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/httpserver.md Initializes a server using a pre-built Configuration object. An optional root handler can also be provided. ```swift public init( config: Configuration, handler: (any HTTPHandler)? = nil ) ``` -------------------------------- ### Initialize HTTPServer with Full Configuration Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/configuration.md Customize all HTTPServer configuration parameters, including address, timeout, buffer sizes, socket pool, and logger. ```swift let config = HTTPServer.Configuration( address: .loopback(port: 8080), timeout: 30, sharedRequestBufferSize: 8192, sharedRequestReplaySize: 5_242_880, // 5 MB pool: try await AsyncSocketPool.client, logger: CustomLogger() ) let server = HTTPServer(config: config, handler: rootHandler) ``` -------------------------------- ### Initialize HTTPMethod Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/httprequest-and-response.md Demonstrates initializing HTTPMethod with standard static properties and custom string values. ```swift let method = HTTPMethod.GET let custom = HTTPMethod("CUSTOM") ``` -------------------------------- ### sockname() Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/flyingsocks.md Gets the local address of the socket. ```APIDOC ## sockname() ### Description Gets the socket's local address. ### Method `public func sockname() throws -> Address` ### Returns SocketAddress of socket ### Throws - `SocketError` — getsockname failed ``` -------------------------------- ### remotePeer() Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/flyingsocks.md Gets the remote peer address of the socket connection. ```APIDOC ## remotePeer() ### Description Gets the remote peer address. ### Method `public func remotePeer() throws -> Address` ### Returns SocketAddress of peer ### Throws - `SocketError` — getpeername failed ``` -------------------------------- ### Initialize HTTPServer with Port Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/httpserver.md Initializes a server to listen on a specified port. Defaults to 15 seconds timeout and no root handler. ```swift public init( port: UInt16, timeout: TimeInterval = 15, handler: (any HTTPHandler)? = nil ) ``` -------------------------------- ### Retrieve Listening Address Source: https://github.com/swhitty/flyingfox/blob/main/README.md Get the current network address the server is listening on. ```swift await server.listeningAddress ``` -------------------------------- ### Get Socket Local Address Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/flyingsocks.md Retrieves the local address of the socket. Throws SocketError if the operation fails. ```swift public func sockname() throws -> Address ``` -------------------------------- ### Connect to a Unix Domain Socket with Netcat Source: https://github.com/swhitty/flyingfox/blob/main/README.md Demonstrates how to connect to a Unix domain socket using the `nc` (netcat) command-line utility. ```bash % nc -U Ants ``` -------------------------------- ### Route Parameters in Handler AppendRoute Source: https://github.com/swhitty/flyingfox/blob/main/README.md Example of appending a route with named parameters and accessing them within the handler closure. ```swift handler.appendRoute("GET /creature/:name?type=:beast") { request in let name = request.routeParameters["name"] let beast = request.routeParameters["beast"] return HTTPResponse(statusCode: .ok) } ``` -------------------------------- ### HTTPServer Initializers Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/httpserver.md Provides different ways to initialize an HTTPServer, allowing configuration by port, address, or a dedicated configuration object. ```APIDOC ## HTTPServer Initializers ### init(port:timeout:handler:) Initializes a server listening on the specified port (IPv6 on non-Windows platforms, IPv4 on Windows). #### Parameters - **port** (UInt16) - Yes - Port number to listen on - **timeout** (TimeInterval) - No - 15 - Request timeout in seconds - **handler** (HTTPHandler?) - No - nil - Optional root handler to process requests #### Example ```swift let server = HTTPServer(port: 8080) try await server.run() ``` ### init(address:timeout:pool:logger:handler:) Initializes a server with a custom socket address (IPv4, IPv6, or Unix socket). #### Parameters - **address** (some SocketAddress) - Yes - Address to bind and listen on - **timeout** (TimeInterval) - No - 15 - Request timeout in seconds - **pool** (some AsyncSocketPool) - No - defaultPool() - Custom event loop pool - **logger** (any Logging) - No - defaultLogger() - Custom logging implementation - **handler** (HTTPHandler?) - No - nil - Optional root handler #### Example ```swift let address = sockaddr_in.loopback(port: 8080) let server = HTTPServer(address: address) ``` ### init(config:handler:) Initializes a server with explicit configuration. #### Parameters - **config** (Configuration) - Yes - Pre-built server configuration - **handler** (HTTPHandler?) - No - nil - Optional root handler ``` -------------------------------- ### Get Socket Option Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/flyingsocks.md Retrieves the value of a specific socket option. This allows querying current socket configurations. ```swift public func getValue(for option: O) throws -> O.Value ``` -------------------------------- ### HTTPHeaders Initializers Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/httprequest-and-response.md Shows different ways to initialize an HTTPHeaders collection, including empty, from a dictionary, and from variadic tuples. ```swift public init() public init(_ headers: [HTTPHeader: String]) public init(dictionaryLiteral elements: (HTTPHeader, String)...) ``` -------------------------------- ### Initialize HTTPServer Configuration with Port Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/configuration.md Simple initialization of HTTPServer configuration using a port number. The server automatically selects an appropriate address based on the operating system. ```swift let config = HTTPServer.Configuration(port: 8080) let server = HTTPServer(config: config) ``` -------------------------------- ### HTTPRoute Initializer with Methods and Path Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/routes.md Creates an HTTPRoute with an explicit set of HTTP methods and a path pattern. ```APIDOC ## init(methods:path:headers:body:) ### Description Creates a route with explicit method set. ### Parameters #### Path Parameters - **methods** (Set) - Required - Set of HTTP methods to match - **path** (String) - Required - Path pattern - **headers** ([HTTPHeader: String]) - Optional - Header patterns - **body** (HTTPBodyPattern) - Optional - Body pattern ### Request Example ```swift let route = HTTPRoute( methods: [.GET, .HEAD], path: "/files/:name" ) ``` ``` -------------------------------- ### Basic HTTPRoute Matching Source: https://github.com/swhitty/flyingfox/blob/main/README.md Demonstrates basic route matching using HTTPRoute and HTTPRequest. Routes can be matched against the path only. ```swift let route = HTTPRoute("/hello/world") route ~= HTTPRequest(method: .GET, path: "/hello/world") // true route ~= HTTPRequest(method: .POST, path: "/hello/world") // true route ~= HTTPRequest(method: .GET, path: "/hello/") // false ``` -------------------------------- ### Get Remote Peer Address Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/flyingsocks.md Retrieves the address of the remote peer connected to the socket. Throws SocketError if the operation fails. ```swift public func remotePeer() throws -> Address ``` -------------------------------- ### HTTPServer.Configuration Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/types.md Configuration struct for setting up an HTTPServer, including address, timeouts, buffer sizes, and the socket pool. ```APIDOC ## HTTPServer.Configuration ### Description Configuration for HTTPServer. See [HTTPServer](api-reference/httpserver.md). ### Struct `HTTPServer.Configuration` ### Properties - **address** (any SocketAddress) - The socket address for the server. - **timeout** (TimeInterval) - The timeout duration for server operations. - **sharedRequestBufferSize** (Int) - The size of the shared buffer for requests. - **sharedRequestReplaySize** (Int) - The replay size for shared requests. - **pool** (any AsyncSocketPool) - The asynchronous socket pool to use. - **logger** (any Logging) - The logger instance for the server. ``` -------------------------------- ### Trailing Wildcard Path Matching Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/routes.md Matches paths that start with a specific prefix followed by any characters. Does not match the prefix alone. ```swift let route: HTTPRoute = "/files/*" // Matches: GET /files/doc.txt, GET /files/a/b/c.txt // Does not match: GET /files ``` -------------------------------- ### HTTPBodyPattern Protocol Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/routes.md Defines the `HTTPBodyPattern` protocol for creating custom body matching logic, including an example for maximum size validation. ```APIDOC ## HTTPBodyPattern Protocol ```swift public protocol HTTPBodyPattern: Sendable { func evaluate(_ body: Data) -> Bool } ``` Custom body patterns can be created by conforming to this protocol. The pattern's `evaluate` method returns true if the body matches. **Example:** ```swift struct MaxSizePattern: HTTPBodyPattern { let maxBytes: Int func evaluate(_ body: Data) -> Bool { body.count <= maxBytes } } let route = HTTPRoute( "POST /upload", body: MaxSizePattern(maxBytes: 1_000_000) ) ``` ``` -------------------------------- ### HTTPRoute Initializer with Sequence of Methods and Path Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/routes.md Creates an HTTPRoute from a sequence of HTTP methods and a path pattern. ```APIDOC ## init(methods:path:headers:body:) ### Description Creates a route from a sequence of methods. ### Parameters #### Path Parameters - **methods** (some Sequence) - Required - Sequence of HTTP methods to match - **path** (String) - Required - Path pattern - **headers** ([HTTPHeader: String]) - Optional - Header patterns - **body** (HTTPBodyPattern) - Optional - Body pattern ### Request Example ```swift let route = HTTPRoute( methods: [.GET, .POST], path: "/api/data" ) ``` ``` -------------------------------- ### Standard HTTP Methods Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/httprequest-and-response.md Access standard HTTP methods like GET, POST, PUT, DELETE, etc., as static properties. ```swift HTTPMethod.GET // GET HTTPMethod.POST // POST HTTPMethod.PUT // PUT HTTPMethod.DELETE // DELETE HTTPMethod.PATCH // PATCH HTTPMethod.HEAD // HEAD HTTPMethod.OPTIONS // OPTIONS HTTPMethod.CONNECT // CONNECT HTTPMethod.TRACE // TRACE ``` -------------------------------- ### HTTPRoute Matching with Path Parameters Source: https://github.com/swhitty/flyingfox/blob/main/README.md Shows how to define routes with named parameters (e.g., :beast) that can be extracted from the request. ```swift let route = HTTPRoute("GET /hello/:beast/world") let beast = request.routeParameters["beast"] ``` -------------------------------- ### HTTPRoute Initializer with String Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/routes.md Creates an HTTPRoute from a string pattern, allowing for flexible definition of methods, path, headers, and body. ```APIDOC ## init(String) ### Description Creates a route from a string pattern. ExpressibleByStringLiteral conformance allows string literals in route context. ### Parameters #### Path Parameters - **string** (String) - Required - Route pattern string - **headers** ([HTTPHeader: String]) - Optional - Header match patterns - **body** (HTTPBodyPattern) - Optional - Body match pattern ### Pattern Formats: - `/path` — any method, exact path - `GET /path` — specific method, exact path - `GET,POST /path` — multiple methods, exact path - `/path/:param` — path parameter extraction - `/path/*` — wildcard matching - `/path?query=value` — required query parameter - `/path?query=*` — wildcard query value ### Request Example ```swift let route1: HTTPRoute = "/api/users" let route2: HTTPRoute = "GET /api/users/:id" let route3: HTTPRoute = "POST /api/users?admin=*" ``` ``` -------------------------------- ### HTTPRoute Initializer with Single Method and Path Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/routes.md Creates an HTTPRoute with a single specified HTTP method and a path pattern. ```APIDOC ## init(method:path:headers:body:) ### Description Creates a route with a single HTTP method. ### Parameters #### Path Parameters - **method** (HTTPMethod) - Required - The HTTP method to match - **path** (String) - Required - Path pattern - **headers** ([HTTPHeader: String]) - Optional - Header patterns - **body** (HTTPBodyPattern) - Optional - Body pattern ### Request Example ```swift let route = HTTPRoute(method: .POST, path: "/api/items") ``` ``` -------------------------------- ### Serve Static Directory Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/handlers.md Appends a route to serve files from a specified directory. Use this to serve static assets like CSS, JavaScript, and images. ```swift await server.appendRoute("GET /static/*", to: .directory( subPath: "Public", serverPath: "static" )) ``` -------------------------------- ### HTTPRoute Initializer from Sequence of Methods Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/routes.md Creates an HTTPRoute from a sequence of HTTP methods, a path pattern, and optional headers and body patterns. ```swift public init( methods: some Sequence, path: String, headers: [HTTPHeader: String] = [:], body: (any HTTPBodyPattern)? = nil ) ``` ```swift let route = HTTPRoute( methods: [.GET, .POST], path: "/api/data" ) ``` -------------------------------- ### Conditional Handler Routing Example Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/README.md Shows how to chain handlers using HTTPUnhandledError. The first handler (authenticationHandler) must pass before the second (apiHandler) is attempted. ```swift await server.appendRoute("POST /api/*", to: authenticationHandler) // Must pass auth await server.appendRoute("POST /api/*", to: apiHandler) // Processes if auth passed ``` -------------------------------- ### Simple Echo Handler (Messages) Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/websockets.md An example of a WSMessageHandler that echoes back received text and data messages to the client. It closes the connection when a close message is received. ```APIDOC ## Simple Echo Handler (Messages) ```swift struct EchoMessageHandler: WSMessageHandler { func makeMessages(for client: AsyncStream) async throws -> AsyncStream { AsyncStream { continuation in Task { for await message in client { switch message { case .text(let text): continuation.yield(.text("Echo: \(text)")) case .data(let data): continuation.yield(.data(data)) case .close: continuation.finish() return } } } } } } await server.appendRoute("GET /echo", to: .webSocket(EchoMessageHandler())) ``` ``` -------------------------------- ### Upgrade HTTP to WebSocket Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/websockets.md Demonstrates how to return an HTTPResponse with a WSHandler to upgrade an HTTP connection to a WebSocket connection. ```swift await server.appendRoute("GET /ws") { request in HTTPResponse(webSocket: echoHandler) } ``` -------------------------------- ### Serving Static Files from a File Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/README.md Configures the server to serve a specific HTML file for the root path. This is useful for single-page applications or landing pages. ```swift await server.appendRoute("GET /", to: .file(named: "index.html")) ``` -------------------------------- ### Serving Static Files from a Directory Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/README.md Configures the server to serve files from a directory, mapping a URL path prefix to a file system subpath. This is ideal for serving assets like CSS, JavaScript, and images. ```swift await server.appendRoute("GET /static/*", to: .directory(subPath: "Public", serverPath: "static")) ``` -------------------------------- ### Initialize HTTPServer Configuration with Explicit Address Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/configuration.md Explicitly specify the binding address for the HTTPServer using IPv4 loopback, IPv6 any, or a Unix domain socket. ```swift // IPv4 loopback let config = HTTPServer.Configuration(address: .loopback(port: 8080)) // IPv6 any let config = HTTPServer.Configuration(address: .inet6(port: 8080)) // Unix domain socket let config = HTTPServer.Configuration(address: .unix(path: "/tmp/server.sock")) let server = HTTPServer(config: config) ``` -------------------------------- ### Implement Conditional HTTP Handler Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/errors.md An example of an HTTPHandler that throws HTTPUnhandledError for requests not matching its specific criteria (e.g., only handling POST requests). This enables fallback to other handlers. ```swift struct ConditionalHandler: HTTPHandler { func handleRequest(_ request: HTTPRequest) async throws -> HTTPResponse { // Only handle POST requests guard request.method == .POST else { throw HTTPUnhandledError() } return HTTPResponse(statusCode: .ok) } } ``` -------------------------------- ### AsyncSocketPool.prepare() Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/flyingsocks.md Initializes the event loop pool for managing socket events. ```APIDOC ## AsyncSocketPool.prepare() ### Description Initializes the event loop pool for managing socket events. ### Method `async throws` ### Parameters None ### Endpoint N/A (This is a method on an `AsyncSocketPool` instance) ### Request Example ```swift // try await socketPool.prepare() ``` ### Response #### Success Response None #### Response Example None ERROR HANDLING: - `SocketError` — initialization failed ``` -------------------------------- ### Configuration Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/httpserver.md Configuration options for HTTPServer, including address, timeout, buffer sizes, pool, and logger. ```APIDOC ## Configuration ### Description Configuration options for HTTPServer. ### Fields - **address** (SocketAddress) - Required - Binding address. - **timeout** (TimeInterval) - Optional - Request timeout in seconds (Default: 15). - **sharedRequestBufferSize** (Int) - Optional - Initial buffer size for reading requests (Default: 4096). - **sharedRequestReplaySize** (Int) - Optional - Maximum body size for replay (Default: 2097152). - **pool** (AsyncSocketPool) - Optional - Event loop pool implementation (Default: default). - **logger** (Logging) - Optional - Logging implementation (Default: default). ### Example ```swift let config = Configuration( address: try TCPSocket.Address(ipAddress: "127.0.0.1", port: 8080)!, timeout: 30, sharedRequestBufferSize: 8192, sharedRequestReplaySize: 4194304, pool: MultiThreadedEventLoopGroup(numberOfThreads: 4), logger: Logger(label: "my.app") ) let server = HTTPServer(configuration: config) ``` ``` -------------------------------- ### Get HTTPServer Listening Address Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/httpserver.md Retrieves the socket address the server is currently listening on. Returns nil if the server is not active. This property is useful for discovering the actual listening port, especially when dynamically assigned. ```swift public var listeningAddress: Socket.Address? ``` -------------------------------- ### HTTPRoute Initializer with Single Method Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/routes.md Creates an HTTPRoute for a single specified HTTP method and a path pattern. Optional headers and body patterns can also be provided. ```swift public init( method: HTTPMethod, path: String, headers: [HTTPHeader: String] = [:], body: (any HTTPBodyPattern)? = nil ) ``` ```swift let route = HTTPRoute(method: .POST, path: "/api/items") ``` -------------------------------- ### Custom HTTPBodyPattern Implementation Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/routes.md Shows how to create a custom body pattern by conforming to the HTTPBodyPattern protocol and implementing the evaluate method. ```swift public protocol HTTPBodyPattern: Sendable { func evaluate(_ body: Data) -> Bool } struct MaxSizePattern: HTTPBodyPattern { let maxBytes: Int func evaluate(_ body: Data) -> Bool { body.count <= maxBytes } } let route = HTTPRoute( "POST /upload", body: MaxSizePattern(maxBytes: 1_000_000) ) ``` -------------------------------- ### Initialize HTTPServer with Socket Address Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/httpserver.md Initializes a server with a custom socket address, allowing for IPv4, IPv6, or Unix sockets. Includes options for timeout, socket pool, logger, and a root handler. ```swift public init( address: some SocketAddress, timeout: TimeInterval = 15, pool: some AsyncSocketPool = defaultPool(), logger: any Logging = defaultLogger(), handler: (any HTTPHandler)? = nil ) ``` -------------------------------- ### Initialize HTTPStatusCode Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/httprequest-and-response.md Demonstrates creating an HTTPResponse with a standard status code and a custom status code with a phrase. ```swift HTTPResponse(statusCode: .ok) HTTPResponse(statusCode: HTTPStatusCode(404, phrase: "Not Found")) ``` -------------------------------- ### HTTPRoute Matching Specific Query Items Source: https://github.com/swhitty/flyingfox/blob/main/README.md Demonstrates matching routes based on specific query parameters and their values. ```swift let route = HTTPRoute("/hello?time=morning") route ~= HTTPRequest(method: .GET, path: "/hello?time=morning") // true route ~= HTTPRequest(method: .GET, path: "/hello?count=one&time=morning") // true route ~= HTTPRequest(method: .GET, path: "/hello") // false route ~= HTTPRequest(method: .GET, path: "/hello?time=afternoon") // false ``` -------------------------------- ### HTTPRoute Initializer from String Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/routes.md Creates an HTTPRoute from a string pattern, supporting various pattern formats for path, query, and headers. ExpressibleByStringLiteral conformance is enabled. ```swift public init( _ string: String, headers: [HTTPHeader: String] = [:], body: (any HTTPBodyPattern)? = nil ) ``` ```swift let route1: HTTPRoute = "/api/users" let route2: HTTPRoute = "GET /api/users/:id" let route3: HTTPRoute = "POST /api/users?admin=*" ``` -------------------------------- ### Socket.init(domain:type:) Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/flyingsocks.md Creates a socket with an explicitly defined address family and socket type (stream or datagram). ```APIDOC ## Socket.init(domain:type:) ### Description Creates a socket with an explicit address family and socket type. ### Method `throws` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **domain** (Int32) - Required - Address family (e.g., AF_INET, AF_INET6). - **type** (SocketType) - Required - The type of socket, either `.stream` (TCP) or `.datagram` (UDP). ### Request Example ```swift // Create a UDP socket let udpSocket = try Socket(domain: AF_INET, type: .datagram) // Create a TCP socket let tcpSocket = try Socket(domain: AF_INET6, type: .stream) ``` ### Response #### Success Response A new `Socket` instance. #### Response Example N/A (Initializer) ERROR HANDLING: - `SocketError` — socket creation failed ``` -------------------------------- ### Initialize AsyncSocket Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/flyingsocks.md Initializes an AsyncSocket by wrapping an existing Socket with async operations. Requires an underlying socket and an event loop pool. ```swift public init(socket: Socket, pool: some AsyncSocketPool) throws ``` -------------------------------- ### HTTPRoute Matching Headers with Wildcards Source: https://github.com/swhitty/flyingfox/blob/main/README.md Demonstrates using wildcards for header values to match any provided value. ```swift let route = HTTPRoute("*", headers: [.authorization: "*"]) route ~= HTTPRequest(headers: [.authorization: "abc"]) // true route ~= HTTPRequest(headers: [.authorization: "xyz"]) // true route ~= HTTPRequest(headers: [:]) // false ``` -------------------------------- ### Socket.init(domain:) Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/flyingsocks.md Creates a TCP stream socket using the specified address family. ```APIDOC ## Socket.init(domain:) ### Description Creates a TCP stream socket. ### Method `throws` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **domain** (Int32) - Required - Address family (e.g., AF_INET for IPv4, AF_INET6 for IPv6, AF_UNIX for Unix domain sockets). ### Request Example ```swift #if os(Windows) let socket = try Socket(domain: AF_INET) // IPv4 #else let socket = try Socket(domain: AF_INET6) // IPv6 #endif ``` ### Response #### Success Response A new `Socket` instance. #### Response Example N/A (Initializer) ERROR HANDLING: - `SocketError` — socket creation failed ``` -------------------------------- ### Socket.listen(maxPendingConnection:) Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/flyingsocks.md Marks a socket as ready to accept incoming connections, specifying the maximum number of pending connections. ```APIDOC ## Socket.listen(maxPendingConnection:) ### Description Marks the socket for listening for incoming connections. ### Method `throws` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **maxPendingConnection** (Int32) - Optional - The maximum number of pending connections allowed. Defaults to `SOMAXCONN`. ### Request Example ```swift // Listen with default backlog // try socket.listen() // Listen with a specific backlog // try socket.listen(maxPendingConnection: 10) ``` ### Response #### Success Response None #### Response Example None ERROR HANDLING: - `SocketError` — listen failed ``` -------------------------------- ### HTTPRoute Initializer with Explicit Methods Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/routes.md Creates an HTTPRoute by explicitly providing a set of HTTP methods and a path pattern. Supports optional headers and body patterns. ```swift public init( methods: Set, path: String, headers: [HTTPHeader: String] = [:], body: (any HTTPBodyPattern)? = nil ) ``` ```swift let route = HTTPRoute( methods: [.GET, .HEAD], path: "/files/:name" ) ``` -------------------------------- ### HTTPRoute Matching with Path Wildcards Source: https://github.com/swhitty/flyingfox/blob/main/README.md Demonstrates using wildcards (*) within the path of an HTTPRoute to match any segment. ```swift let route = HTTPRoute("GET /hello/*/world") route ~= HTTPRequest(method: .GET, path: "/hello/fish/world") // true route ~= HTTPRequest(method: .GET, path: "/hello/dog/world") // true route ~= HTTPRequest(method: .GET, path: "/hello/fish/sea") // false ``` -------------------------------- ### Establish and Use an Async Socket Connection Source: https://github.com/swhitty/flyingfox/blob/main/README.md Connect to a remote IP address and port using AsyncSocket. This is useful for low-level network communication. ```swift import FlyingSocks let socket = try await AsyncSocket.connected(to: .inet(ip4: "192.168.0.100", port: 80)) try await socket.write(Data([0x01, 0x02, 0x03])) try socket.close() ``` -------------------------------- ### HTTPRoute Matching Query Items with Wildcards Source: https://github.com/swhitty/flyingfox/blob/main/README.md Shows how to use wildcards in query item values for flexible matching. ```swift let route = HTTPRoute("/hello?time=*") route ~= HTTPRequest(method: .GET, path: "/hello?time=morning") // true route ~= HTTPRequest(method: .GET, path: "/hello?time=afternoon") // true route ~= HTTPRequest(method: .GET, path: "/hello") // false ``` -------------------------------- ### Wait Until Server is Listening Source: https://github.com/swhitty/flyingfox/blob/main/README.md Pause execution until the server is confirmed to be listening and ready to accept connections. ```swift try await server.waitUntilListening() ``` -------------------------------- ### Development Server Configuration Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/configuration.md A basic HTTP server configuration suitable for development. It uses default settings for address, timeout, buffer, pool, and logger. ```swift let server = HTTPServer(port: 8080) try await server.run() ``` -------------------------------- ### HTTPServer Methods Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/httpserver.md Core methods for managing the lifecycle and state of the HTTP server, including running, stopping, and checking its listening status. ```APIDOC ## HTTPServer Methods ### run() Starts the server and runs indefinitely, listening for connections. Throws `SocketError` if the server cannot bind to the address. This method blocks until the server is stopped via `stop()` or its parent task is cancelled. #### Throws - `SocketError` — binding failed or socket errors during operation #### Example ```swift let server = HTTPServer(port: 8080) try await server.run() ``` ### stop(timeout:) Gracefully stops the server. Closes the listening socket and allows existing connections to complete. If timeout expires, forces closure of remaining connections. #### Parameters - **timeout** (TimeInterval) - No - 0 - Seconds to wait for connections to close #### Example ```swift let task = Task { try await server.run() } try await Task.sleep(nanoseconds: 5_000_000_000) await server.stop(timeout: 3) task.cancel() ``` ### waitUntilListening() Suspends until the server is listening and ready to accept connections. Useful for ensuring the server is ready before making requests. #### Throws - `SocketError` — if the server fails to start #### Example ```swift async let serverTask = server.run() try await server.waitUntilListening() // Safe to make requests now ``` ### listeningAddress Returns the socket address the server is currently listening on, or nil if not listening. On systems that assign ports dynamically, this property provides the actual port. #### Example ```swift if let addr = await server.listeningAddress { print("Server listening at \(addr)") } ``` ``` -------------------------------- ### HTTPRoute Matching Specific Headers Source: https://github.com/swhitty/flyingfox/blob/main/README.md Illustrates matching routes based on specific HTTP headers and their values. ```swift let route = HTTPRoute("*", headers: [.contentType: "application/json"]) route ~= HTTPRequest(headers: [.contentType: "application/json"]) // true route ~= HTTPRequest(headers: [.contentType: "application/xml"]) // false ``` -------------------------------- ### HTTPResponse Initializer: version, statusCode, headers, body: HTTPBodySequence Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/httprequest-and-response.md Initializes a response with a streaming body, allowing specification of version, status code, headers, and an async sequence for the body data. ```APIDOC #### init(version:statusCode:headers:body:HTTPBodySequence) ```swift public init( version: HTTPVersion = .http11, statusCode: HTTPStatusCode, headers: HTTPHeaders = [:], body: HTTPBodySequence ) ``` Initializes a response with streaming body. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | version | HTTPVersion | No | HTTP/1.1 | HTTP version | | statusCode | HTTPStatusCode | Yes | — | Status code | | headers | HTTPHeaders | No | empty | Response headers | | body | HTTPBodySequence | Yes | — | Async sequence of body data | ``` -------------------------------- ### Create IPv6 Socket Addresses Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/flyingsocks.md Factory methods for creating IPv6 socket addresses. Supports specifying IP and port, just port (defaults to [::]), or loopback address ([::1]). ```swift static func inet6(ip6: String, port: UInt16) -> sockaddr_in6 static func inet6(port: UInt16) -> sockaddr_in6 // [::] static func loopback(port: UInt16) -> sockaddr_in6 // [::1] ``` -------------------------------- ### DirectoryHTTPHandler Struct Initializers Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/types.md Initializes a DirectoryHTTPHandler to serve files from a directory with wildcard matching. Supports initialization with a root URL or from a bundle with a subpath. ```swift public struct DirectoryHTTPHandler: HTTPHandler { public init(root: URL, serverPath: String = "/", cacheControl: [HTTPCacheControl.ResponseDirective] = [.private]) public init(bundle: Bundle, subPath: String = "", serverPath: String, cacheControl: [HTTPCacheControl.ResponseDirective] = [.private]) } ``` -------------------------------- ### Route-Level Error Handling with do-catch Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/errors.md Illustrates how to implement route-level error handling using a do-catch block to manage potential errors during data fetching and response creation. ```swift await server.appendRoute("GET /api/users") { request in do { let users = try await fetchUsers() return HTTPResponse( statusCode: .ok, body: try JSONEncoder().encode(users) ) } catch { return HTTPResponse( statusCode: .internalServerError, body: "Error fetching users".data(using: .utf8)! ) } } ``` -------------------------------- ### Accessing String Route Parameters Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/routes.md Demonstrates how to access route parameters as optional strings within a handler. ```swift await server.appendRoute("GET /users/:id") { request in let userId = request.routeParameters["id"] // userId is String? return HTTPResponse(statusCode: .ok) } ``` -------------------------------- ### Initializing HTTPResponse with Streaming Body Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/httprequest-and-response.md Initializes an HTTP response with a streaming body represented by an `HTTPBodySequence`. This is suitable for large or dynamically generated responses. ```swift public init( version: HTTPVersion = .http11, statusCode: HTTPStatusCode, headers: HTTPHeaders = [:], body: HTTPBodySequence ) ``` -------------------------------- ### Listen for Incoming Connections Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/flyingsocks.md Marks the socket for listening and specifies the maximum number of pending connections. This should be called after binding. ```swift public func listen(maxPendingConnection: Int32 = SOMAXCONN) throws ``` -------------------------------- ### Containerized Deployment Configuration Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/configuration.md Configuration for deploying an HTTP server within a containerized environment. It uses IPv6 any address, a moderate timeout, larger buffer sizes for headers, and a JSON logger for structured log aggregation. ```swift let config = HTTPServer.Configuration( address: .inet6(port: 8080), timeout: 20, sharedRequestBufferSize: 16384, logger: JSONLogger() ) let server = HTTPServer(config: config, handler: containerHandler) try await server.run() ``` -------------------------------- ### HTTPResponse Initializer: statusCode, headers, body Source: https://github.com/swhitty/flyingfox/blob/main/_autodocs/api-reference/httprequest-and-response.md Initializes a response with a data body, allowing specification of version, status code, headers, and body data. ```APIDOC ### HTTPResponse Initializers #### init(statusCode:headers:body:) ```swift public init( version: HTTPVersion = .http11, statusCode: HTTPStatusCode, headers: HTTPHeaders = [:], body: Data = Data() ) ``` Initializes a response with data body. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | version | HTTPVersion | No | HTTP/1.1 | HTTP version | | statusCode | HTTPStatusCode | Yes | — | Status code | | headers | HTTPHeaders | No | empty | Response headers | | body | Data | No | empty | Response body | **Example:** ```swift let response = HTTPResponse( statusCode: .ok, headers: [.contentType: "application/json"], body: jsonData ) ``` ```