Parámetros de Ruta y Middleware
En esta página
Prefijar un segmento de ruta con : captura su valor en req.params. La query
string está disponible en req.query; el operador ?? aplica un valor por defecto
cuando la clave está ausente:
:id, req.params, req.query y ?? para valores opcionales.
// 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"}
Requiere la CLI o el host de Zolo; ábrelo en el playground o ejecútalo localmente.
Middleware es una función fn mw(req, next) que puede inspeccionar la solicitud,
llamar a next(req) para continuar la cadena y añadir cabeceras a la respuesta.
Se registra con http.middleware(mw) en el pipe del enrutador:
Middleware de log y de CORS — next(req) y .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
Requiere la CLI o el host de Zolo; ábrelo en el playground o ejecútalo localmente.
El orden de registro importa: los middlewares se ejecutan en la secuencia en que aparecen en el pipe, antes que cualquier handler de ruta.
Desafío
Escribe un middleware de autenticación simple: si req.headers["Authorization"]
es nil, retorna http.response(401, "Unauthorized") sin llamar a next.
Consulta también