El framework std/web ofrece una API estilo Flask para construir aplicaciones web. App guarda las rutas y el middleware, app_get/app_post registran los handlers de ruta, y app_use agrega middleware que se ejecuta antes de cada petición. El middleware incluido de fábrica incluye mw_logging y mw_cors.
// 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 }
app configured with 2 routes and 2 middlewares routes: GET / and GET /api/status middleware: logging + CORS
Cómo funciona
app_new() crea una aplicación vacía. Los handlers de ruta reciben una struct Request (con campos como method, path, query, headers_flat y body) y retornan una struct Response. Funciones auxiliares como response_new y response_json crean respuestas con los headers apropiados.
mw_logging registra el método, la ruta, el status y la latencia de cada petición. mw_cors maneja las peticiones OPTIONS de preflight y agrega los headers CORS. Puedes configurar CORS con cors_configure(origin, methods, headers).
En producción le pasas la app a serve_app(app, port, workers) de std/serve, que la ejecuta sobre un pool de hilos. El framework en sí no hace E/S — solo registra rutas y las hace coincidir.