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

MethodDescription
web.app() → appCreate a new app.
app.get(path, handler)Register a GET route. path supports :param segments.
app.post(path, handler), .put, .patch, .delete, .headSame 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) → serverStart. 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.

BuilderDescription
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.headers
  • req.params:id etc. from the route pattern
  • req.query — parsed ?a=b&c=d
  • req.body — raw body string (for buffered serving)
  • req.cookies — parsed cookies map

Helpers: web.parse_form(req), web.parse_json(req).

Streaming + WebSocket

FunctionDescription
web.serve_stream(opts, handler)Server mode where the handler receives the request as a stream — handle huge bodies without buffering.
web.upgrade(req) → connUpgrade an HTTP request to a raw connection (use with the ws module).
web.set_views(dir)Default directory for web.view.

See also