52 / Networking

HTTP Middleware

The std/web framework provides a Flask-style API for building web applications. App holds routes and middleware, app_get/app_post register route handlers, and app_use adds middleware that runs before each request. Built-in middleware includes mw_logging and mw_cors.

52-http-middleware.nxSource →
// Web framework — registering routes and middleware
// Framework web — registrar rutas y middleware

import "std/http"
import "std/web"

fn handle_root(req: Request) -> Response {
    return response_new(200, "Welcome to Nyx!")
}

fn handle_api(req: Request) -> Response {
    return response_json(200, "{\"status\": \"ok\"}")
}

fn main() -> int {
    // Create an app and register middleware + routes
    let app: App = app_new()

    // Middleware runs before each request
    app_use(app, mw_logging)
    app_use(app, mw_cors)

    // Routes match method + path pattern
    app_get(app, "/", handle_root)
    app_get(app, "/api/status", handle_api)

    // The app is ready — in production you would pass it
    // to serve_app() from std/serve to start serving.
    // Here we just demonstrate the framework API.
    print("app configured with 2 routes and 2 middlewares")
    print("routes: GET / and GET /api/status")
    print("middleware: logging + CORS")

    return 0
}
Outputstdout
app configured with 2 routes and 2 middlewares
routes: GET / and GET /api/status
middleware: logging + CORS

How it works

app_new() creates an empty application. Route handlers take a Request struct (with fields such as method, path, query, headers_flat and body) and return a Response struct. Helper functions like response_new and response_json create responses with appropriate headers.

mw_logging logs each request's method, path, status, and latency. mw_cors handles OPTIONS preflight requests and adds CORS headers. You can configure CORS with cors_configure(origin, methods, headers).

In production you hand the app to serve_app(app, port, workers) from std/serve, which runs it on a thread pool. The framework itself does no I/O — it only registers routes and matches them.