HTTP middleware
Use case: public health, protected /api
Section titled “Use case: public health, protected /api”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.appimport lib.middlewareimport lib.requestimport lib.responseimport 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, };}./vow run vow-examples/vow-web-server/middleware_chain.vow -- --grant net:
# Public — no Authorization requiredcurl -sf http://127.0.0.1:8787/health
# Protected — 401 without headercurl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8787/api/secret
# With Authorizationcurl -sf http://127.0.0.1:8787/api/secret \ -H 'Authorization: Bearer dev-token'
# CORS preflightcurl -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/healthKey concepts
Section titled “Key concepts”| 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 |
Unit tests
Section titled “Unit tests”let a = /* build same app as main */;assert app.try_handle(a, "GET /health") == 200;assert app.try_handle(a, "GET /api/secret") == 401;