web module
Bnlang's HTTP server framework. Declarative routing, before/after middleware, automatic response coercion, streaming, file serving, templating, and WebSocket upgrade in one module.
import "web" as web;
var app = web.app();
app.get("/", function (req) { return "Hello!"; });
app.get("/users/:id", function (req) { return { id: req.params.id }; });
app.post("/upload", function (req) { return web.json({ ok: true }); });
app.listen({ port: 3000 });
App builder
| Method | Description |
|---|---|
web.app() → app | Create a new app. |
app.get(path, handler) | Register a GET route. path supports :param segments. |
app.post(path, handler), .put, .patch, .delete, .head | Same shape for other methods. |
app.before(fn) | Run fn(req) before each handler. Return non-null to short-circuit (treated as the response). |
app.after(fn) | Run fn(resp, req) after each handler. Mutate or replace resp. |
app.not_found(fn) | Custom 404. |
app.on_error(fn) | Catch handler exceptions. |
app.static(prefix, dir) | Serve files from dir at prefix/.... |
app.listen(opts) → server | Start. opts: {port, host?, tls?, max_body_size?, idle_timeout?}. Returns {port, close()}. |
Response builders
Return any of these from a handler — or just a string / map / list and web coerces it.
| Builder | Description |
|---|---|
web.text(s) | text/plain response. |
web.html(s) | text/html. |
web.json(value) | application/json (serialized via the json module). |
web.redirect(url) | 302 redirect. |
web.error(status, msg) | Status-coded error. |
web.file(path) | Stream a file (sets content-type by extension). |
web.view(path, ctx) | Render a template via the template module. |
Request object
req exposes:
req.method,req.path,req.url,req.headersreq.params—:idetc. from the route patternreq.query— parsed?a=b&c=dreq.body— raw body string (for buffered serving)req.cookies— parsed cookies map
Helpers: web.parse_form(req), web.parse_json(req).
Streaming + WebSocket
| Function | Description |
|---|---|
web.serve_stream(opts, handler) | Server mode where the handler receives the request as a stream — handle huge bodies without buffering. |
web.upgrade(req) → conn | Upgrade an HTTP request to a raw connection (use with the ws module). |
web.set_views(dir) | Default directory for web.view. |