@server
Import this module with import @server.
An HTTP server module with dynamic handlers and path parameters.
Routing
Section titled “Routing”| 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 = "0.0.0.0") |
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 |
Response Builders
Section titled “Response Builders”| 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 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.
A request has 30 seconds in total to arrive, counted from the connection being accepted. A connection that has not sent a complete request by then is closed without a response, however slowly it is still sending. A request whose body ends before its declared Content-Length because the peer closed the connection is answered 400 Bad Request, and one whose headers and declared body do not fit in 64 KiB is answered 413 Payload Too Large; the handler runs for neither.
Request Type
Section titled “Request Type”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)}