Skip to content

HTTP middleware

Apply auth only under /api, enable CORS for browser clients on all routes.

Example source: vow-examples/vow-web-server/middleware_chain.vow

import lib.app
import lib.middleware
import lib.request
import lib.response
import lib.serve
fn health(_req: request.Request) -> response.Response {
return response.json("{\"ok\":true}");
}
fn secret(_req: request.Request) -> response.Response {
return response.json("{\"secret\":true}");
}
fn main(caps: Caps) -> int {
let a = app.use_cors(
app.use_at(
app.get(app.app(), "/health", health),
"/api",
middleware.kind_auth_header()
),
"*"
);
let a = app.get(a, "/api/secret", secret);
return match caps.net {
Some(cap) => serve.listen(a, cap, 8787),
None => 0 - 1,
};
}
Terminal window
./vow run vow-examples/vow-web-server/middleware_chain.vow -- --grant net:
# Public — no Authorization required
curl -sf http://127.0.0.1:8787/health
# Protected — 401 without header
curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8787/api/secret
# With Authorization
curl -sf http://127.0.0.1:8787/api/secret \
-H 'Authorization: Bearer dev-token'
# CORS preflight
curl -s -o /dev/null -w '%{http_code}' -X OPTIONS \
-H 'Origin: http://localhost' \
-H 'Access-Control-Request-Method: GET' \
http://127.0.0.1:8787/health
Mechanism This example
Path-scoped middleware use_at(a, "/api", kind_auth_header())
Global CORS use_cors(a, "*")
Auth halt Missing Authorization → 401 before handler
OPTIONS 204 preflight when CORS enabled
let a = /* build same app as main */;
assert app.try_handle(a, "GET /health") == 200;
assert app.try_handle(a, "GET /api/secret") == 401;