Nyx by Example

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.

Code

// Web framework — registering routes and 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 {
    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)

    print("app configured with 2 routes and 2 middlewares")
    print("routes: GET / and GET /api/status")
    print("middleware: logging + CORS")

    return 0
}

Output

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

Explanation

app_new() creates an empty application. Route handlers take a Request struct (with fields: method, path, query, headers_flat, 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, pass the app to serve_app(app, port, workers) from nyx-serve to start a multi-threaded HTTP server. This is how all four nyxlang.com sites are built.

← Previous Next →

Source: examples/by-example/52-http-middleware.nx