Nyx by Example

HTTP GET

std/http provides high-level HTTP client functions built on top of TCP primitives. http_get(url) handles DNS resolution, connection, request formatting, and response parsing in a single call. The response is returned as an array: ["response", status, headers, body].

Code

// 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
}

Output

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

Explanation

http_get parses the URL to extract host, port, and path, then opens a TCP connection, sends an HTTP/1.1 GET request, and reads the response. Helper functions http_status, http_body, and http_headers extract fields from the response array.

If the connection fails, the status code is -1 and the body contains the error message. For HTTPS, use https_get which adds TLS via OpenSSL.

← Previous Next →

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