Pular para o conteúdo

Respostas e Workers

Nesta página

Por padrão, retornar uma string do handler gera 200 text/plain e retornar um mapa gera 200 application/json. Para outros cenários há três helpers:

  • http.html(str)200 text/html com o conteúdo fornecido.
  • http.redirect(caminho)302 Found para o caminho indicado.
  • http.response(status, corpo) — status e corpo arbitrários.

http.html, http.redirect e http.response com status customizado.

09-server-response-helpers.zolo
Playground
// Feature: HTTP server — `http.response`, `http.html`, `http.redirect`

// Syntax: handler returns a helper built from `http.*`.

// When to use: custom status, explicit content-type, redirects.


use std::json
use std::http

// Plain string -> 200 text/plain.

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

// Map -> 200 application/json.

fn handle_json(_req) {
  return #{message: "Hello", language: "Zolo"}
}

// Raw HTML with the correct Content-Type.

fn handle_html(_req) {
  return http.html("<h1>Hello from Zolo!</h1>")
}

// 302 redirect.

fn handle_redirect(_req) {
  return http.redirect("/")
}

// Custom status + body.

fn handle_status(_req) {
  return http.response(201, "Created!")
}

let app = http.router()
  |> http.get("/", handle_root)
  |> http.get("/json", handle_json)
  |> http.get("/html", handle_html)
  |> http.get("/redirect", handle_redirect)
  |> http.get("/status", handle_status)

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

//   curl http://localhost:3004/json     -> {"message":"Hello","language":"Zolo"}

//   curl http://localhost:3004/html     -> <h1>Hello from Zolo!</h1>

//   curl -i http://localhost:3004/status -> HTTP/1.1 201 Created

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

Para atender múltiplas requisições simultâneas sem que uma bloqueie a outra, http.workers(N) inicializa N VMs independentes que compartilham o mesmo registro de rotas e servem requisições em round-robin:

http.workers(4) antes de http.serve para paralelismo de requisições.

10-server-multi-worker.zolo
Playground
// Feature: HTTP server — multiple workers

// Syntax: `http.workers(N)` before `http.serve(...)`.

// When to use: parallelism for CPU-bound requests; each worker is an

// isolated VM running the same route registry.


use std::http

@get("/")
fn index() {
  return "Hello from a worker!"
}

@get("/heavy")
fn heavy() {
  // Some arbitrary work; in production, with multiple workers, concurrent

  // requests do not block one another.

  var acc = 0
  for i in 1..=10000 {
    acc = acc + i
  }
  return #{sum: acc}
}

// Spin up 4 workers (each with its own LuaState) serving round-robin.

http.workers(4)
http.serve(3005)
// expected when running:

//   curl http://localhost:3005/        -> Hello from a worker!

//   ab -n 1000 -c 50 http://localhost:3005/heavy   (load test)

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

Cada worker roda em sua própria LuaState, portanto não há estado compartilhado entre eles — o que elimina corridas de dados mas também significa que mutações de variáveis globais em um worker não são visíveis nos demais.

Desafio

Adicione uma rota /status que retorna http.response(503, "Unavailable") e verifique com curl -i que o código de status HTTP está correto.

Buscar no Zolo

9 resultados

enespt-br