Cliente HTTP (std::http)
En esta página
std::http expone el sub-módulo client para comunicación HTTP síncrona con
APIs externas. Las llamadas devuelven un par (resp, err): cuando err != nil
ocurrió un fallo de red o de protocolo; de lo contrario resp contiene
status, ok, headers y body.
Nota: todos los ejemplos a continuación realizan peticiones de red reales y por eso están marcados como
| norunen el sandbox WASM. Ejecútalos localmente conzolo run.
GET simple
La operación más común: obtener un recurso por URL.
Ejemplo de GET con manejo de errores; la respuesta incluye status, ok y body.
// Feature: http.client.get — HTTP GET request
// When to use: consume REST APIs, download pages, healthchecks.
// Response: { status, headers, body, status_text, ok } or (nil, err) on failure.
//
// SKIP: this example performs a live HTTP request (httpbin.org).
// In offline / sandboxed environments the call surfaces an internal
// error from the runtime rather than a clean (nil, err) result, so
// the body of the function is shown only as a comment.
use std::http
use std::log
fn fetch_status(url: str) {
// let resp, err = http.client.get(url)
// if err != nil {
// log.error("failure: {err}")
// return nil
// }
// return resp
print("(would GET {url})")
return nil
}
let _ = fetch_status("http://httpbin.org/get")
// Expected response shape (when the request succeeds):
// resp.status -> 200
// resp.ok -> true
// resp.headers["content-type"] -> "application/json"
// resp.body -> raw response body string
Requiere la CLI o el host de Zolo; ábrelo en el playground o ejecútalo localmente.
POST con cuerpo JSON
Envía datos estructurados combinando std::json para serializar el payload y
http.client.post para transmitirlo.
POST con payload JSON y lectura del eco devuelto por el servidor.
// Feature: http.client.post — POST with a JSON body
// When to use: create resources, send webhooks, talk to REST APIs.
//
// SKIP: this example performs a live HTTP request (httpbin.org).
// In offline / sandboxed environments the call surfaces an internal
// error from the runtime rather than a clean (nil, err) result, so
// the network call is shown only as a comment.
use std::http
use std::json
use std::log
let payload = json.encode(#{
user_id: 42,
action: "login",
ts: 1700000000,
})
let headers = #{
"Content-Type": "application/json",
Accept: "application/json",
}
let ct = headers["Content-Type"]
print("payload: {payload}")
print("Content-Type: {ct}")
// Signature: http.client.post(url, body, headers?)
// let resp, err = http.client.post("http://httpbin.org/post", payload, headers)
//
// if err != nil {
// log.error("error: {err}")
// } else {
// print(resp.status) // expected: 200
// // The httpbin server echoes the body back — try decoding it.
// let echo = json.decode(resp.body)
// print(echo["json"]["action"]) // expected: login
// }
Requiere la CLI o el host de Zolo; ábrelo en el playground o ejecútalo localmente.
Cabeceras personalizadas
La autenticación Bearer, User-Agent y las claves de idempotencia se pasan como
un mapa #{clave: valor} en el argumento de cabeceras (segundo parámetro en
GET, tercero en POST/PUT). Los métodos put, delete y patch siguen el mismo
patrón.
Cabeceras de autorización y User-Agent; resumen de PUT/DELETE/PATCH.
// Feature: http.client — custom headers in requests
// When to use: authentication (Bearer), custom User-Agent, Accept-Language, idempotency keys.
//
// SKIP: this example performs a live HTTP request (httpbin.org).
// In offline / sandboxed environments the call surfaces an internal
// error from the runtime rather than a clean (nil, err) result, so
// the network call is shown only as a comment.
use std::http
let headers = #{
Authorization: "Bearer secret-token",
"User-Agent": "zolo-client/0.1",
Accept: "application/json",
"X-Request-Id": "abc123",
}
let auth = headers["Authorization"]
let ua = headers["User-Agent"]
print("Authorization: {auth}")
print("User-Agent: {ua}")
// GET with headers (optional as the second argument).
// let resp, err = http.client.get("http://httpbin.org/headers", headers)
//
// if err == nil {
// print(resp.status) // expected: 200
// print(resp.body) // httpbin echoes the headers it received
// }
// PUT/DELETE/PATCH follow the same pattern:
// http.client.put(url, body, headers?)
// http.client.delete(url, headers?)
// http.client.patch(url, body, headers?)
Requiere la CLI o el host de Zolo; ábrelo en el playground o ejecútalo localmente.
Desafío
Adapta el ejemplo de POST para enviar un webhook y valida la firma HMAC usando
std::hash.hmac (consulta el módulo hash).
Consulta también