Asynchronous HTTP server/client
.package(url: "https://github.com/swiftstack/http.git", .branch("dev"))
Quick Start [source]
// main.swift
import HTTP
import Async
async {
// entry point for async http server
}
loop.run()
Simple server running "http://localhost:8080":
// async body
let server = try Server(host: "localhost", port: 8080)
try registerRoutes(in: server)
try server.start()
// routes.swift
import HTTP
func registerRoutes(in server: Server) throws {
server.route(get: "/hello") {
return "Hey there!"
}
}
$ swift run main
$ curl http://localhost:8080/hello
> Hey there!
struct User: Decodable {
let name: String
}
func helloHandler(user: User) -> String {
return "Hello \(user.name)"
}
let application = Application(basePath: "/v1")
application.route(get: "/hello", to: helloHandler)
server.addApplication(application)
struct User: Decodable {
let name: String
}
struct Greeting: Encodable {
let message: String
}
func helloHandler(user: User) -> Greeting {
return .init(message: "Hello, \(user.name)!")
}
struct SwiftMiddleware: Middleware {
static func chain(with handler: @escaping RequestHandler) -> RequestHandler {
return { request in
if request.url.query?["name"] == "swift" {
return Response(string: "🤘")
}
return try handler(request)
}
}
}
let application = Application(basePath: "/v2")
application.route(
get: "/hello",
through: [SwiftMiddleware.self],
to: helloHandler)
server.addApplication(application)
$ swift run main
$ curl http://localhost:8080/v2/hello?name=swift
> 🤘
struct User: Decodable {
let name: String
}
struct Greeting: Encodable {
let message: String
}
func helloHandler(user: User) -> Greeting {
return .init(message: "Hello, \(user.name)!")
}
struct SwiftMiddleware: Middleware {
static func chain(with handler: @escaping RequestHandler) -> RequestHandler {
return { request in
if request.url.path.split(separator: "/").last == "swift" {
return Response(string: "🤘")
}
return try handler(request)
}
}
}
let application = Application(basePath: "/v3")
application.route(
get: "/hello/:name",
through: [SwiftMiddleware.self],
to: helloHandler)
server.addApplication(application)
$ swift run main
$ curl http://localhost:8080/v3/hello/swift
> 🤘