nyx-serve routes
nyx-serve's App framework supports RESTful routing with path parameters like /users/{id}. Parameters are captured in req.params as a Map.
Code
// nyx-serve routes -- GET, POST, PUT, DELETE handlers
import "std/http"
import "std/web"
fn get_users(req: Request) -> Response {
return response_json(200, "[{\"id\": 1, \"name\": \"Alice\"}]")
}
fn get_user_by_id(req: Request) -> Response {
// {id} is captured automatically in req.params
let id: String = req.params.get("id")
return response_json(200, "{\"id\": " + id + ", \"name\": \"User\"}")
}
fn create_user(req: Request) -> Response {
// req.body contains the raw request body
return response_json(201, "{\"created\": true, \"body\": \"" + req.body + "\"}")
}
fn delete_user(req: Request) -> Response {
let id: String = req.params.get("id")
return response_new(204, "")
}
fn main() -> int {
let app: App = app_new()
// RESTful routes with path parameters
app_get(app, "/users", get_users)
app_get(app, "/users/{id}", get_user_by_id)
app_post(app, "/users", create_user)
app_delete(app, "/users/{id}", delete_user)
print("REST API configured with 4 routes")
print(" GET /users")
print(" GET /users/{id}")
print(" POST /users")
print(" DELETE /users/{id}")
return 0
}
Output
REST API configured with 4 routes
GET /users
GET /users/{id}
POST /users
DELETE /users/{id}
Explanation
An App is a routing table plus a handler registry. Each app_get, app_post, app_put, app_delete call binds an HTTP method + path pattern to a function of signature fn (req: Request) -> Response. When a request arrives, nyx-serve matches method and path against the table and dispatches.
Path patterns support {name} placeholders. The matcher populates req.params — a Map from name to the captured string segment — so GET /users/42 hitting /users/{id} exposes req.params.get("id") == "42". Use req.body to read the raw request payload for POST/PUT, and req.query for parsed query-string parameters.
The helper constructors response_new(status, body), response_json, and response_html wrap headers and status code so handlers stay small. Start the server with http_serve_mt(app, port) to reach 73K req/s on a single node.