Pular para o conteúdo

Cliente HTTP — GET

Nesta página

O módulo std::http expõe http.get(url, headers?), que retorna um objeto {status, ok, headers, body}. A convenção de erro do Zolo se aplica: em caso de falha a função retorna nil, mensagem — nunca lança exceção.

O exemplo abaixo mostra como construir o mapa de cabeçalhos com a literal #{} e acessar os campos da resposta. Como requer acesso de rede real, a chamada aparece comentada dentro do arquivo; a linha print roda normalmente para documentar a forma esperada:

http.get e a estrutura de resposta {status, ok, headers, body}.

01-client-get.zolo
Playground
// 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)")

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

Para passar cabeçalhos customizados — Authorization, User-Agent, Accept — basta fornecer um mapa como segundo argumento:

Construção do mapa de cabeçalhos e acesso a campos individuais.

02-client-headers.zolo
Playground
// 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}")

// }

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

Desafio

Adicione um cabeçalho X-Request-Id com um valor aleatório gerado por std::math.random() e imprima-o antes de enviar a requisição.

Buscar no Zolo

9 resultados

enespt-br