Nyx con Ejemplos

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].

Código

// HTTP GET request using std/http

import "std/http"

fn main() -> int {
    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)
    }

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

    return 0
}

Salida

status: 200
body (first 100 chars): <!doctype html>...
header count: 10

Explicación

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.

← Anterior Siguiente →

Source: examples/by-example/49-http-get.nx