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
letserver=tryServer(host:"localhost", port:8080)tryregisterRoutes(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!structUser:Decodable{letname:String}func helloHandler(user:User)->String{return"Hello \(user.name)"}letapplication=Application(basePath:"/v1")
application.route(get:"/hello", to: helloHandler)
server.addApplication(application)structUser:Decodable{letname:String}structGreeting:Encodable{letmessage:String}func helloHandler(user:User)->Greeting{return.init(message:"Hello, \(user.name)!")}structSwiftMiddleware:Middleware{staticfunc chain(with handler:@escapingRequestHandler)->RequestHandler{return{ request inif request.url.query?["name"]=="swift"{returnResponse(string:"🤘")}returntryhandler(request)}}}letapplication=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
> 🤘structUser:Decodable{letname:String}structGreeting:Encodable{letmessage:String}func helloHandler(user:User)->Greeting{return.init(message:"Hello, \(user.name)!")}structSwiftMiddleware:Middleware{staticfunc chain(with handler:@escapingRequestHandler)->RequestHandler{return{ request inif request.url.path.split(separator:"/").last =="swift"{returnResponse(string:"🤘")}returntryhandler(request)}}}letapplication=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
> 🤘