Cliente HTTP — GET
En esta página
El módulo std::http expone http.get(url, headers?), que devuelve un objeto
{status, ok, headers, body}. Se aplica la convención de errores de Zolo: en caso
de fallo la función retorna nil, mensaje — nunca lanza una excepción.
El ejemplo siguiente muestra cómo construir el mapa de cabeceras con el literal #{}
y acceder a los campos de la respuesta. Como requiere acceso de red real, la llamada
aparece comentada dentro del archivo; la línea print se ejecuta normalmente para
documentar la forma esperada:
http.get y la estructura de respuesta {status, ok, headers, body}.
// Feature: HTTP client — simple GET
// Syntax: `http.get(url, headers?)` returns `{status, headers, body, ok}`
// When to use: consuming HTTP APIs, light scraping, healthchecks.
//
// SKIP: live network call disabled — runs only in environments with
// outbound HTTP access. The shape below documents the response.
use std::http
// On error returns `nil, msg` — Zolo's standard pattern for fallible APIs.
//
// let resp, err = http.get("http://httpbin.org/get")
// if resp == nil {
// print("failed: {err}")
// } else {
// print("status: {resp.status}") // 200
// print("ok? {resp.ok}") // true
// let preview = resp.body.sub(1, 80)
// print("first 80 chars: {preview}")
// }
print("(http.get is documented above; live request skipped)")
Requiere la CLI o el host de Zolo; ábrelo en el playground o ejecútalo localmente.
Para pasar cabeceras personalizadas — Authorization, User-Agent, Accept —
basta con proporcionar un mapa como segundo argumento:
Construcción del mapa de cabeceras y acceso a campos individuales.
// Feature: HTTP client — GET with custom headers
// Syntax: `http.get(url, #{"Header-Name": "value"})`
// When to use: APIs that require `Authorization`, a specific `User-Agent`,
// or `Accept` for content negotiation.
//
// SKIP: live network call disabled — runs only in environments with
// outbound HTTP access. The shape below documents the response.
use std::http
let headers = #{
"User-Agent": "zolo-lang/0.1",
Accept: "application/json",
Authorization: "Bearer fake-token-here",
}
let ua = headers["User-Agent"]
let auth = headers["Authorization"]
print("User-Agent: {ua}")
print("Authorization: {auth}")
// let resp, err = http.get("http://httpbin.org/headers", headers)
// if resp != nil {
// print("status: {resp.status}") // 200
// print("body len: {resp.body.len()}") // headers echoed back
// } else {
// print("failed: {err}")
// }
Requiere la CLI o el host de Zolo; ábrelo en el playground o ejecútalo localmente.
Desafío
Añade una cabecera X-Request-Id con un valor aleatorio generado por
std::math.random() e imprímelo antes de enviar la solicitud.
Consulta también