Nyx by Example

HTTP Server

A minimal HTTP server using http_serve from std/http. The handler function receives a parsed request array [type, method, path, headers, body] and returns an HTTP response string built with http_response. The server blocks in an accept loop, handling one request at a time.

Code

// Minimal HTTP server using std/http

import "std/http"

fn on_request(req: Array) -> String {
    let method: String = req[1]
    let path: String = req[2]

    if path == "/" {
        return http_response(200, "Hello from Nyx!")
    }
    if path == "/time" {
        let t: int = time()
        return http_response(200, "timestamp: " + int_to_string(t))
    }
    return http_response(404, "not found: " + path)
}

fn main() -> int {
    print("listening on :8080")
    http_serve(8080, on_request)
    return 0
}

Output

listening on :8080

Explanation

http_serve(port, handler) listens on the given port and enters an infinite accept loop. For each connection, it parses the HTTP request into an array, calls the handler function, sends the response, and closes the connection.

http_response(status, body) builds a properly formatted HTTP/1.1 response with Content-Length and Connection: close headers. For custom headers (like Content-Type: application/json), use http_response_with_headers.

For multi-threaded serving, use http_serve_mt(port, num_workers, handler) which dispatches connections to a thread pool via channels — this is how nyx-serve achieves 73K req/s.

← Previous Next →

Source: examples/by-example/51-http-server.nx