Pular para o conteúdo

Cliente HTTP (std::http)

Nesta página

std::http expõe o sub-módulo client para comunicação HTTP síncrona com APIs externas. As chamadas retornam um par (resp, err): quando err != nil ocorreu uma falha de rede ou de protocolo; caso contrário resp contém status, ok, headers e body.

Nota: todos os exemplos abaixo executam requisições de rede reais e por isso são marcados como | norun no sandbox WASM. Rode localmente com zolo run.


GET simples

A operação mais comum: buscar um recurso por URL.

Exemplo de GET com tratamento de erro; a resposta traz status, ok e body.

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

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


POST com corpo JSON

Envie dados estruturados combinando std::json para serializar o payload e http.client.post para transmiti-lo.

POST com payload JSON e leitura do eco retornado pelo servidor.

02-post-json.zolo
Playground
// 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

// }

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


Cabeçalhos personalizados

Autenticação Bearer, User-Agent e chaves de idempotência são passados como mapa #{chave: valor} no argumento de cabeçalhos (segundo parâmetro no GET, terceiro no POST/PUT). Os métodos put, delete e patch seguem o mesmo padrão.

Cabeçalhos de autorização e User-Agent; visão geral de PUT/DELETE/PATCH.

03-headers.zolo
Playground
// 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?)

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

Desafio

Adapte o exemplo de POST para enviar um webhook e valide a assinatura HMAC usando std::hash.hmac (veja o módulo hash).

Buscar no Zolo

9 resultados

enespt-br