web
lib/web.vklib/web.vk
Pure-Veko HTTP/1.1 web micro-framework built over codec/http1, codec/url, io, and io/net.
Provides a data-driven router with :param path segments, middleware pipeline,
typed JSON/query helpers, multipart form-data parsing, SSE formatting, static file
serving with traversal protection, and io/Stream / TCP loopback server runners.
Request = struct { method str, path str, target str, query map[str], params map[str], headers map[str], body bytes }
Parsed HTTP/1.1 request passed to route handlers and middleware.
Response = struct { status i64 = ..., reason str = ..., headers map[str] = ..., body bytes = ..., has_stream bool = ..., stream any = ..., stream_len i64 = ..., file_path str = ..., file_off i64 = ... }
HTTP/1.1 / HTTP/2 / HTTP/3 response returned by handlers and middleware (supports eager body, positioned file streaming, and io/Stream chunked/fixed streaming).
Route = struct { method str, pattern str, handler any }
Single route entry (method: 'GET', 'POST', 'ANY', etc.; pattern: '/users/:id').
MultipartPart = struct { name str, filename str, content_type str, data bytes }
One parsed part from a multipart/form-data request body.
App = struct { routes block[Route], middlewares block[any], static_prefix str = ..., static_root str = ..., max_header_bytes i64 = ..., max_body_bytes i64 = ... }
Web application container holding routes, middleware, body/header limits, and optional static file mount.
status-reason = fn [code i64] str
Maps standard HTTP status codes to default reason phrases.
add-route = fn [mut app App, method str, pattern str, handler any]
Registers a route handler (fn [req Request] Response) on app.
get = fn [mut app App, pattern str, handler any]
Registers a GET route handler (also automatically serves HEAD with empty body unless an explicit HEAD route matches first).
delete-route = fn [mut app App, pattern str, handler any]
Registers a DELETE route handler.
use-mw = fn [mut app App, mw any]
Appends a middleware (fn [req Request, next any] Response) to app.
mount-static = fn [mut app App, url_prefix str, root_dir str]
Mounts a static file directory under url_prefix (e.g. '/static').
response = fn [status i64, content_type str, body bytes] Response
Builds a generic Response with explicit status, content-type, and body bytes.
stream-response = fn [status i64, content_type str, s io/Stream, content_len i64] Response
Builds a streaming Response reading from s (content_len >= 0 emits Content-Length; content_len < 0 emits HTTP/1.1 Transfer-Encoding: chunked).
chunked-response = fn [status i64, content_type str, s io/Stream] Response
Builds an HTTP/1.1 Transfer-Encoding: chunked (or HTTP/2 DATA-streamed) Response from s.
encode-chunk = fn [chunk bytes] bytes
Formats a single HTTP/1.1 chunk (<hex>\r\n<chunk>\r\n, or '0\r\n\r\n' when len chunk == 0).
view = fn [status i64, node any] Response
Renders a pure-Veko html/Node or Hiccup component block ([.div { class = 'x' } ['hi']]) as a text/html response.
page = fn [status i64, title str, head_extra block, body_children block] Response
Renders a complete HTML5 <!DOCTYPE html> document from pure-Veko components as a text/html response.
json-resp = fn [status i64, val any] Response
Builds an application/json response by JSON-encoding val.
sse-event = fn [event_name str, data str, id str] str
Formats one Server-Sent Events (SSE) payload (event: ...\ndata: ...\n\n).
sse-resp = fn [payload str] Response
Builds a text/event-stream SSE response containing one or more formatted events.
sse-write = fn [mut stream io/Stream, event_name str, data str, id str] i64
Streams a live Server-Sent Event frame directly over an open io/Stream.
build-multipart = fn [boundary str, fields map[str], files block[MultipartPart]] bytes
Encodes an RFC 7578 multipart/form-data payload from text fields and binary files.
unauthorized = fn [msg str] Response
not-found = fn [msg str] Response
server-error = fn [msg str] Response
header = fn [req Request, name str, default_val str] str
Looks up a request header case-insensitively (returns default_val if absent).
query-get = fn [req Request, key str, default_val str] str
Returns a query parameter or default_val.
param = fn [req Request, key str, default_val str] str
Returns a matched :param route parameter or default_val.
bind-form = fn [req Request] map[str]
Decodes an application/x-www-form-urlencoded request body into map[str].
cookie-get = fn [req Request, name str, default_val str] str
Extracts a named cookie value from the Cookie request header (or default_val if absent).
match-pattern = fn [pattern str, path str] map
Matches a route pattern like '/users/:id/posts/*rest' against path.
Returns { ok = true, params = map } or { ok = false, params = {} }.
use [web]
m = web/match-pattern '/api/:ver/items/:id' '/api/v1/items/42'
if not m.ok or (map/get m.params 'ver') != 'v1' or (map/get m.params 'id') != '42' [
err 'route match'
] else [ .ok ]
parse-multipart = fn [body bytes, boundary str] block[MultipartPart]
Parses a multipart/form-data body given its boundary string.
use [web]
body = bytes/from-str '--b1\r\nContent-Disposition: form-data; name="title"\r\n\r\nhello\r\n--b1--\r\n'
parts = web/parse-multipart body 'b1'
if (len parts) != 1 or parts[0].name != 'title' or (bytes/to-str parts[0].data) != 'hello' [
err 'multipart'
] else [ .ok ]
stream-file-range = fn [root_dir str, rel_path str, range_hdr str] Response
Streams a static file (supporting Range: bytes=... 206 Partial Content) in 64 KiB positioned os/pread chunks with zero whole-file RAM allocation.
stream-file = fn [root_dir str, rel_path str] Response
Streams a static file confined beneath root_dir without loading the file into RAM.
serve-static-range = fn [root_dir str, rel_path str, range_hdr str] Response
Serves a static file safely confined beneath root_dir (binary-safe, supporting HTTP Range: bytes=... 206 Partial Content;
automatically switches to 64 KiB positioned file streaming for slices > 256 KiB).
serve-static = fn [root_dir str, rel_path str] Response
Serves a static file safely confined beneath root_dir, rejecting path traversal.
mw-security-headers = fn [req Request, next any] Response
Built-in middleware that attaches defensive HTTP security headers.
use-security-headers = fn [mut app App]
Registers the built-in defensive HTTP security headers middleware on app.
handle-request = fn [app App, req Request] Response
Dispatches a Request through app's middleware chain and router (automatically stripping body on HEAD while preserving Content-Length).
use [web]
mut app = web/new-app
web/use-security-headers mut app
web/get mut app '/hello/:name' fn [req web/Request] web/Response [
web/json-resp 200 { greeting = str/join ['hi ' (web/param req 'name' '')] '' }
]
req = web/Request { method = 'GET', path = '/hello/veko', target = '/hello/veko', query = {}, params = {}, headers = {}, body = bytes/with-cap 0 }
resp = web/handle-request app req
if resp.status != 200 or (map/get resp.headers 'X-Frame-Options') != 'DENY' [ err 'web dispatch' ] else [ .ok ]
parse-http-request = fn [raw bytes] Request
Decodes raw HTTP/1.1 wire bytes into a structured Request.
encode-http-response = fn [resp Response] bytes
Encodes a Response into HTTP/1.1 wire bytes (materializing streamed payloads if invoked directly).
write-http-response-stream = fn [mut stream io/Stream, mut resp Response] i64
Streams resp directly onto stream without whole-file RAM buffering (supports positioned file_path, fixed-length io/Stream, and Transfer-Encoding: chunked).
read-http-request-stream-limits = fn [mut stream io/Stream, max_header_bytes i64, max_body_bytes i64] Request
Reads a complete HTTP/1.1 request enforcing max_header_bytes and max_body_bytes (returns err 'web: payload too large' on overflow).
read-http-request-stream = fn [mut stream io/Stream] Request
Reads a complete HTTP/1.1 request (headers + Content-Length or chunked body) from an io/Stream.
serve-stream = fn [mut stream io/Stream, app App] Response
Serves a single HTTP/1.1 request/response exchange over any io/Stream (TCP, TLS 1.3, or memory).
serve-once = fn [ln any, app App] Response
Accepts one connection from a TCP listener ln (net/listen-tcp) and serves one request.
serve-loop = fn [ln any, app App, max_requests i64] i64
Serves up to max_requests sequential connections on TCP listener ln.
AsyncServerOpts = struct { max_requests i64 = ..., max_connections i64 = ..., max_reqs_per_conn i64 = ..., read_timeout dur = ..., idle_timeout dur = ..., tick_timeout dur = ..., max_header_bytes i64 = ..., max_body_bytes i64 = ... }
Configuration for serve-reactor.
AsyncConn = struct { sock i64, token i64, state enum, rx bytes, tx bytes, tx_off i64, hdr_end i64, content_len i64, started_ns i64, reqs_served i64 = ..., keep_alive bool = ..., file_path str = ..., file_off i64 = ..., file_rem i64 = ... }
Per-connection non-blocking HTTP/1.1 state machine tracked inside serve-reactor (supports keep-alive reuse & positioned file streaming).
serve-reactor = fn [ln any, app App, opts AsyncServerOpts] i64
Serves concurrent HTTP/1.1 connections on a single thread using the OS readiness reactor
(epoll on Linux, kqueue on macOS, IOCP+WSAPoll on Windows, WASI net-poll on Wasm).
Supports HTTP/1.1 keep-alive reuse, max_connections DoS protection, 413 body limits, and 64 KiB non-blocking file streaming.
serve-async = fn [ln any, app App, max_requests i64] i64
Convenience wrapper serving up to max_requests concurrent HTTP/1.1 connections via serve-reactor.
HttpsServerOpts = struct { max_requests i64 = ..., max_reqs_per_conn i64 = ..., handshake_timeout dur = ..., idle_timeout dur = ..., alt_svc str = ... }
Configuration for serve-tls-conn-opts, serve-https, and https-worker-loop.
serve-h2-stream = fn [mut stream io/Stream, app App, max_requests i64, alt_svc str] i64
Serves an RFC 9113 HTTP/2 connection over stream, dispatching each stream through app (with streaming DATA support & DoS guards).
serve-tls-conn-opts = fn [sock i64, ident map, app App, opts HttpsServerOpts] i64
Serves an accepted TCP socket sock over pure-Veko TLS 1.3 (ident) with explicit HttpsServerOpts deadlines & body limits.
serve-tls-conn = fn [sock i64, ident map, app App, max_requests i64, alt_svc str] i64
Serves an accepted TCP socket sock over pure-Veko TLS 1.3 (ident), automatically dispatching
ALPN 'h2' to serve-h2-stream and 'http/1.1' to serve-stream.
https-accept-loop = fn [ln any, mut cert_reloader map, work_ch any, max_conns i64] i64
Multi-core shared-nothing HTTPS acceptor: accepts sockets on ln, snapshots closure-free TLS ident from cert_reloader,
and dispatches { sock, ident } onto bounded channel work_ch (shedding load cleanly on full backlog).
https-worker-loop = fn [work_ch any, app App, opts HttpsServerOpts] i64
Multi-core shared-nothing HTTPS worker loop: consumes { sock, ident } jobs from work_ch and serves TLS 1.3 (h2 + http/1.1).
serve-https = fn [ln any, mut cert_reloader map, app App, max_conns i64, alt_svc str] i64
Serves native HTTPS (TLS 1.3 + ALPN 'h2' / 'http/1.1' + zero-downtime certificate hot-reload) on TCP listener ln
multiplexed with reactor so idle HTTP/1.1 keep-alive sockets never block new accepts.
serve-h3 = fn [udp_sock i64, get_ident_fn any, app App, max_requests i64] i64
Serves pure-Veko HTTP/3 over QUIC v1 on bound UDP socket udp_sock (net/udp-bind), dispatching to app.
make-acme-redirect-app = fn [acme_webroot str, domain str, https_port i64] App
Builds a dedicated port :80 App serving RFC 8555 Let's Encrypt /.well-known/acme-challenge/:token
from acme_webroot and redirecting (301) all other HTTP requests to https://<domain>[:port]<target>.