49 / Redes

HTTP GET

std/http provee funciones de cliente HTTP de alto nivel construidas sobre primitivas TCP. http_get(url) maneja la resolución DNS, la conexión, el formateo de la petición y el parseo de la respuesta en una sola llamada. La respuesta se devuelve como un array: ["response", status, headers, body].

49-http-get.nxFuente →
// HTTP GET request using std/http
// Solicitud HTTP GET usando std/http

import "std/http"

fn main() -> int {
    // http_get returns an Array: ["response", status, headers, body]
    let resp: Array = http_get("http://example.com/")

    let status: int = http_status(resp)
    print("status: " + int_to_string(status))

    let body: String = http_body(resp)
    if body.length() > 100 {
        print("body (first 100 chars): " + body.substring(0, 100))
    } else {
        print("body: " + body)
    }

    // Access raw headers
    let hdrs: Array = http_headers(resp)
    print("header count: " + int_to_string(hdrs.length()))

    return 0
}
Salida ilustrativastdout
status: 200
body (first 100 chars): <!doctype html>...
header count: 10

Cómo funciona

http_get parsea la URL para extraer el host, el puerto y el path, luego abre una conexión TCP, envía una petición HTTP/1.1 GET y lee la respuesta. Las funciones auxiliares http_status, http_body y http_headers extraen campos del array de respuesta.

Si la conexión falla, el código de estado es -1 y el cuerpo contiene el mensaje de error. Para HTTPS, usa https_get, que agrega TLS vía OpenSSL.