Parâmetros de Rota e Middleware
Nesta página
Prefixar um segmento de rota com : captura seu valor em req.params. A query
string está disponível em req.query; o operador ?? aplica um padrão quando
a chave está ausente:
:id, req.params, req.query e ?? para valores opcionais.
// Feature: HTTP server — path params (`:id`) and query string
// Syntax: `:name` in the route; read via `req.params.name` and `req.query.k`.
// When to use: REST routes with IDs, slugs, optional filters.
use std::http
@get("/users/:id")
fn get_user(req) {
// `req.params` carries the matched segments.
let id = req.params.id
return #{
id,
name: "User {id}",
}
}
@get("/search")
fn search(req) {
// `req.query` is a map; `??` applies a default if absent.
let q = req.query.q ?? "(empty)"
let limit = req.query.limit ?? "10"
return #{
q,
limit,
}
}
@get("/posts/:author/:slug")
fn get_post(req) {
return #{
author: req.params.author,
slug: req.params.slug,
}
}
http.serve(3002)
// expected when running:
// curl http://localhost:3002/users/42 -> {"id":"42","name":"User 42"}
// curl 'http://localhost:3002/search?q=zolo&limit=5' -> {"q":"zolo","limit":"5"}
// curl http://localhost:3002/posts/devzolo/hello -> {"author":"devzolo","slug":"hello"}
Requer a CLI/host do Zolo — abra no playground ou rode localmente.
Middleware é uma função fn mw(req, next) que pode inspecionar a requisição,
chamar next(req) para continuar a cadeia e encadear cabeçalhos na resposta.
Registra-se com http.middleware(mw) no pipe do roteador:
Middleware de log e de CORS — next(req) e .with_headers(#{...}).
// Feature: HTTP server — middleware via pipe
// Syntax: `fn mw(req, next) { ... return next(req) }` and
// `router |> http.middleware(mw)`
// When to use: logging, CORS, authentication, common headers —
// cross-cutting code shared across routes.
use std::http
// Middleware 1: log every request.
fn logger(req, next) {
print("[{req.method}] {req.path}")
return next(req)
}
// Middleware 2: add CORS headers to the response.
fn cors(req, next) {
return next(req).with_headers(#{
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE",
"Access-Control-Allow-Headers": "Content-Type",
})
}
fn api_health() {
return #{status: "ok"}
}
fn api_echo(req) {
return req.json()
}
let router = http.router()
|> http.get("/api/health", api_health)
|> http.post("/api/echo", api_echo)
|> http.middleware(logger)
|> http.middleware(cors)
http.serve(3003, router)
// expected when running:
// curl http://localhost:3003/api/health -> {"status":"ok"}
// curl -i http://localhost:3003/api/health -> CORS headers present
Requer a CLI/host do Zolo — abra no playground ou rode localmente.
A ordem de registro importa: middlewares são executados na sequência em que aparecem no pipe, antes de qualquer handler de rota.
Desafio
Escreva um middleware de autenticação simples: se req.headers["Authorization"]
for nil, retorne http.response(401, "Unauthorized") sem chamar next.