Pular para o conteúdo

Servidor — Roteador e Decoradores

Nesta página

O servidor HTTP do Zolo roda no processo host (hyper + tokio) e não termina: ao chamar http.serve(porta, app) o script bloqueia e passa a atender requisições em loop. Para testá-lo, abra outro terminal e use curl.

A primeira abordagem usa composição por pipes: http.router() cria um roteador vazio; cada chamada http.get("/rota", handler) anexa uma rota e devolve o mesmo roteador, pronto para o próximo |>:

http.router() |> http.get(...) |> http.serve(porta, app).

05-server-router.zolo
Playground
// Feature: HTTP server — router via pipes

// Syntax: `http.router() |> http.get("/path", handler) |> ...`

// When to use: simple APIs; declarative composition of routes with pipes.


use std::http

// Each handler receives `req` and returns a string, map, or `http.response(...)`.

fn handle_root(_req) {
  return "Hello from the Zolo server!"
}

fn handle_health(_req) {
  return #{status: "ok"}
}

let app = http.router()
  |> http.get("/", handle_root)
  |> http.get("/health", handle_health)

// Runs in the foreground on port 3000.

http.serve(3000, app)
// expected when running:

//   curl http://localhost:3000/        -> Hello from the Zolo server!

//   curl http://localhost:3000/health  -> {"status":"ok"}

Requer a CLI/host do Zolo — abra no playground ou rode localmente.

A segunda abordagem é o estilo decorador: anotar uma fn com @get, @post, @put ou @delete registra a rota automaticamente; http.serve(porta) sem argumento de app usa o registro global:

@get/@post/@put/@delete — registro automático de rotas.

06-server-decorators.zolo
Playground
// Feature: HTTP server — `@get`/`@post`/`@put`/`@delete` decorators

// Syntax: annotate a `fn` with the route; `http.serve(port)` registers them all.

// When to use: "framework" style, APIs with many routes, ergonomics

// close to Flask/Express, without wiring up a router manually.


use std::http

@get("/")
fn index() {
  return "Hello from decorator routes!"
}

@get("/health")
fn health() {
  return #{status: "ok"}
}

@post("/echo")
fn echo(req) {
  // `req.json()` reads the body as JSON and returns it as a map.

  return req.json()
}

@put("/items/:id")
fn update_item(req) {
  return #{updated: req.params.id}
}

@delete("/items/:id")
fn delete_item(req) {
  return #{deleted: req.params.id}
}

http.serve(3001)
// expected when running:

//   curl http://localhost:3001/                       -> Hello from decorator routes!

//   curl -X POST -d '{"x":1}' http://localhost:3001/echo

//   curl -X PUT  http://localhost:3001/items/42       -> {"updated":"42"}

//   curl -X DELETE http://localhost:3001/items/42     -> {"deleted":"42"}

Requer a CLI/host do Zolo — abra no playground ou rode localmente.

Cada handler recebe req e pode retornar uma string (200 text/plain), um mapa (200 application/json) ou um valor construído com os helpers de resposta vistos mais à frente.

Buscar no Zolo

9 resultados

enespt-br