Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

410 Commits

Repository files navigation

HTTP

Asynchronous HTTP server/client

Package.swift

.package(url:"https://github.com/swiftstack/http.git",.branch("dev"))

Quick Start [source]

First we need to create a root fiber and run the event loop:

// 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()

Simple get route:

// routes.swift
import HTTP
func registerRoutes(in server:Server)throws{
server.route(get:"/hello"){return"Hey there!"}}

At this point our server is ready to be friendly:

$ swift run main
$ curl http://localhost:8080/hello
> Hey there!

More advanced version:

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)

Most advanced version:

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
> 🤘

The same route using human readable urls

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
> 🤘

About

Lightweight HTTP in Swfit

Topics

Resources

Stars

3 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages