Skip to content

@server

Import this module with import @server.

An HTTP server module with dynamic handlers and path parameters.

Function Signature Description
add_router () -> Router Create a new router
add_route (router Router, method string, path string, handler func(HttpRequest) -> HttpResponse) Add a route with handler function
listen (router Router, port i64, [host string]) Start HTTP server on port, bound to host (default "0.0.0.0"); blocks until killed
cors (router Router, origin string) Enable CORS with the given origin
add_middleware (router Router, middleware func(^HttpRequest, ^HttpResponse)) Register a middleware function
Function Signature Description
text (status i64, body string) -> HttpResponse Response with headers["Content-Type"] set to text/plain
json (status i64, body string) -> HttpResponse Response with headers["Content-Type"] set to application/json
html (status i64, body string) -> HttpResponse Response with headers["Content-Type"] set to text/html
redirect (status i64, url string) -> HttpResponse Response with an empty body and headers["Location"] set to url

A handler returns an HttpResponse (see the HttpResponse Type under @http). The server sends every entry in its headers map, and sets Content-Length and Connection itself: a Content-Length, Transfer-Encoding or Connection entry in the map is not sent. A header key or value containing CR or LF panics with P0132.

The HttpRequest type is only available when @server is imported. Importing @http alone does not provide this type.

Every handler receives an HttpRequest struct:

Field Type Description
method string HTTP method (GET, POST, etc.)
path string Request path
query map[string:string] Query parameters
headers map[string:string] Request headers
params map[string:string] Path parameters (from :param segments)
body string Raw request body
import @server
do home(req HttpRequest) -> HttpResponse {
return server.text(200, "Welcome!")
}
do get_user(req HttpRequest) -> HttpResponse {
mut id = req.params["id"]
return server.json(200, "{\"id\": \"${id}\"}")
}
do main() {
mut r = server.add_router()
server.cors(r, "*")
server.add_route(r, "GET", "/", ()home)
server.add_route(r, "GET", "/users/:id", ()get_user)
server.listen(r, 8080)
}