Skip to content

A small web server

A server listens with a net.Access permission, accepts connections and hands each to http.handle with a function that turns a request into a response. The request’s path, query, headers and body are Untrusted, so they have to pass a check before they are used as text.

This example starts the server on a free local port, makes three requests to it from a second thread, and stops after answering them.

import http
import net
import thread
fn answer(r: &http.Request) -> http.Response {
if r.path.is(&"/") {
return http.response(200, "welcome")
}
match r.path.path_inside(&"/srv/files") {
Some(file) => return http.response(200, "would send " + file)
None => return http.response(400, "bad path")
}
}
fn serve(listener: &mut net.Listener, count: i64) ! http.HttpError {
for _ in 0..count {
let mut conn = listener.accept() catch {
return http.HttpError { message: "accept failed" }
}
try http.handle(&mut conn, &answer)
}
}
fn ask(access: &net.Access, port: i64) -> Vec<Str> ! http.HttpError {
let mut out: Vec<Str> = []
for p in ["/", "/notes/today.txt", "/../../etc/passwd"] {
let reply = try http.get(access, &(f"http://127.0.0.1:{port}" + p))
out.push(f"{reply.status} {reply.body.unchecked()}")
}
return out
}
let access = net.access()
let listener = try access.listen(&"127.0.0.1", 0)
let port = listener.port()
let (_, lines) = try thread.join(fn() -> i64 ! http.HttpError [mut listener] {
try serve(&mut listener, 3)
return 0
}, fn() -> Vec<Str> ! http.HttpError [&access, port] => ask(&access, port))
for line in &lines {
print(line)
}
200 welcome
200 would send /srv/files/notes/today.txt
400 bad path

http.handle serves one connection, with an idle timeout so a silent client cannot hold it forever. To serve many at once, accept in one thread and pass connections over a Channel to thread.workers(n, ...).