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.
// Minimal HTTP server using std/http // Servidor HTTP mínimo usando 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 blocks, accepting connections in a loop // Each request calls on_request and sends the response // Siempre se chequea el retorno del bind: si el puerto esta ocupado, // http_serve devuelve -1 y el programa seguiria "corriendo" sin servidor. if http_serve(8080, on_request) < 0 { print("no se pudo bindear el puerto 8080") return 1 } return 0 }
listening on :8080
How it works
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. It only returns on failure — a negative value when the port cannot be bound — so this example checks that return value and exits with status 1 instead of pretending to serve.
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 through channels — the same path a production HTTP server written in Nyx takes.