nish/net/http-server
One handler for HTTP/1.1, HTTP/2 (over TLS and cleartext) and HTTP/3, with Alt-Svc advertising the HTTP/3 port.
import {
HttpServer,
HttpServerLimits,
HttpServerRequest,
} from "nish/net/http-server";
const server = new HttpServer(new HttpServerLimits(), router)
server.listenHttp1(tcpFd, new Http1Config(), 256)
server.listenHttp2Tls(tlsFd, tlsConfig, new Http2Config(), 64)
server.listenHttp3(udpFd, quicConfig, new Http3Config(), 64, entropy)
for (;;) {
server.waitSigned(1000, key)
while (server.ready()) {
const r: HttpServerRequest = server.take()
if (r.route === HELLO) {
server.send(r, 200, TEXT_PLAIN, HELLO_BODY, 0, HELLO_BODY.length)
} else {
server.refuse(r)
}
}
}
HttpServer
One handler for HTTP/1.1, HTTP/2 over TLS and HTTP/3: configure up to one listener of each kind, then loop on waitSigned (or wait), ready and take, answering each request with send, json and sendJson, problem, refuse, or start, write and end.
HttpServerLimits
The caps an HttpServer holds itself to; every listener's carrier is checked against them.
HttpServerRequest
One request, whole, from any version: its head copied out of the carrier and its body.
HttpServer is HttpHandler's pull loop (nish/net/handler) over up to
four listeners at once. The program builds a Router, configures the
listeners, and loops on waitSigned (or wait, when every listener is
cleartext), ready and take, switching on r.route; one route body
answers every version.
One copy in
Every version copies the request head once into the
request's own head, a buffer of limits.maxHead bytes made on the
request's first use and never grown: each listen call checks that no head
its carrier accepts can overrun it. The body is held whole, up to
limits.maxBody; past it the request is answered 413 on every version.
A fixed pool
limits.requests requests are shared by every listener.
With none free, an HTTP/1.1 connection stops being read until one is, an
HTTP/2 stream is refused with REFUSED_STREAM and an HTTP/3 one with
H3_REQUEST_REJECTED, so the client may retry. No connection holds more
than a quarter of the pool.
Alt-Svc
Once an HTTP/3 listener is configured, every HTTP/1.1 and
HTTP/2 over TLS response names its port (h3=":443"; ma=86400); with
altSvcMaxAge 0 they say alt-svc: clear instead. A response whose fields
already hold an alt-svc keeps the program's. An h2c response carries
none: it reaches clients through a proxy, and would name the backend's port.
One HTTP/2 slot space
The TLS and the cleartext HTTP/2 carriers share
the stream tables: each listener's slots follow the other's, so every
HTTP/2 path below names a slot of either and the carrier is looked up once,
in the h2Holds family.
Classes
HttpServer
One handler for HTTP/1.1, HTTP/2 over TLS and HTTP/3: configure up to one
listener of each kind, then loop on waitSigned (or wait), ready and
take, answering each request with send, json and sendJson,
problem, refuse, or start, write and end.
class HttpServer
| Member | |
|---|---|
new HttpServer(limits: HttpServerLimits, router: Router) |
A server routing through router, held to limits. It has no listener yet: add them with listenHttp1, listenHttp2Tls and listenHttp3. Panics on a limit outside its range. |
scratch: u8[] |
json and problem write here. |
connections(): i32 |
How many connections are open, of every version. |
drain(): void |
Begins a graceful stop: the server accepts no more connections, closes each idle HTTP/1.1 connection now and each other one once its request is answered, and sends GOAWAY on each HTTP/2 and HTTP/3 connection, which then closes once its streams are done. A request already read is still handed over and answered. The listeners are the program's to close. |
empty(r: HttpServerRequest, status: i32): i32 |
Answers r with status and no body. |
end(r: HttpServerRequest): i32 |
Ends r's response. r is the server's again: it goes back once the carrier has taken every byte. Panics on another server's request, when the response is not started, or its body is short of the declared length. |
fired(id: i32): boolean |
Whether watched descriptor id was ready in the last turn. |
hungUp(r: HttpServerRequest): boolean |
Whether the client of r has hung up: its connection is closed or reused, its HTTP/2 or HTTP/3 stream was reset, or, on HTTP/1.1 and HTTP/2, the peer ended its byte stream while r is held. On HTTP/2 that is the connection's end of input, an end of file or a read error, so it includes a client that half-closed TCP after sending its request and may still read an answer: send then says which. Panics on another server's request. |
json(): JsonWriter |
The JSON writer, reset onto the server's scratch buffer: write one value with it, then sendJson. One JSON body at a time, since every request shares the buffer. |
listenH2c(fd: i32, config: Http2Config, slots: i32): void |
Serves cleartext HTTP/2 (h2c, prior knowledge: no Upgrade from HTTP/1.1) on fd, a listening TCP socket the program made, with up to slots connections. Meant for a server behind a TLS-terminating proxy or on a trusted network: nothing on it is encrypted. A connection that has not sent its 24-byte preface within limits.prefaceTimeout is closed, and one with no open stream after it within limits.idleTimeout. Its responses carry no Alt-Svc, and its requests say secure false. Each connection holds at most config.maxStreams requests and a quarter of limits.requests, as on listenHttp2Tls. Panics on a second h2c listener, a maxHeaderListSize past limits.maxHead, or enableConnectProtocol. wait serves it: it reads no key. |
listenHttp1(fd: i32, config: Http1Config, slots: i32): void |
Serves HTTP/1.1 on fd, a listening TCP socket the program made, with up to slots connections. Panics on a second HTTP/1.1 listener, or when config would let in a head past limits.maxHead (its maxTarget, its maxHeaderBytes and 44 bytes of request line) or more fields than limits.maxFields. config.maxBody is set to limits.maxBody. |
listenHttp2Tls(fd: i32, tls: TlsServerConfig, config: Http2Config, slots: i32): void |
Serves HTTP/2 over TLS (ALPN h2) on fd, a listening TCP socket the program made, with up to slots connections. Each connection holds at most config.maxStreams requests and a quarter of limits.requests; a stream past that is refused with REFUSED_STREAM. Panics on a second listener of this kind, a maxHeaderListSize past limits.maxHead, or enableConnectProtocol. Serve it with waitSigned. |
listenHttp3(fd: i32, quic: QuicServerConfig, config: Http3Config, slots: i32, entropy: u8[]): void |
Serves HTTP/3 on fd, a bound UDP socket the program made, with up to slots QUIC connections, and from then on names its port in an Alt-Svc field on every HTTP/1.1 and HTTP/2 response. Each connection holds at most quic.maxStreamsBidi requests and a quarter of limits.requests; a stream past that is rejected with H3_REQUEST_REJECTED. Panics on a second HTTP/3 listener, a maxFieldSectionSize past limits.maxHead, or webtransportSessions above 0. Serve it with waitSigned. |
problem(r: HttpServerRequest, status: i32, title: string, detail: string): i32 |
Answers r with an RFC 9457 problem: application/problem+json with type about:blank, title, status and, when not empty, detail. Nothing of the request is echoed. |
ready(): boolean |
Whether a whole request is waiting for take. Requests whose connection or stream closed while queued are handed back here. |
refuse(r: HttpServerRequest): i32 |
Answers a request the router refused, by its route: 405 with an Allow field naming the methods the path has, and 404 for anything else. |
send(r: HttpServerRequest, status: i32, contentType: u8[], body: u8[], off: i32, len: i32): i32 |
Answers r with status, a Content-Type of contentType and the body body[off .. off + len), in one call. |
sendFields(r: HttpServerRequest, status: i32, names: u8[][], values: u8[][], body: u8[], off: i32, len: i32): i32 |
Answers r with status, the fields names[k]: values[k] and the body body[off .. off + len), in one call. |
sendJson(r: HttpServerRequest, status: i32): i32 |
Answers r with status and the value json's writer holds, as application/json. A value the writer refused or did not finish is answered as a 500 problem instead. Panics when no value was begun with json. |
start(r: HttpServerRequest, status: i32, names: u8[][], values: u8[][], bodyLength: i32): i32 |
Starts r's response: status (200 to 599), the fields names[k]: values[k], and a body of bodyLength bytes or HTTP1_CHUNKED for one of unknown length; then write the body and end. On HTTP/2 and HTTP/3 the field names must be lowercase, and a content-length is added for a known length the fields do not give; on HTTP/1.1 and HTTP/2 the Alt-Svc field is added when an HTTP/3 listener is set and the fields have none. Panics on another server's request, a request not taken or already answered, a status outside the range, a body length below HTTP1_CHUNKED, or fields the carrier refuses. |
take(): HttpServerRequest |
The next whole request, of any version, which the program now owes an answer. Panics when none is ready. |
wait(timeoutMs: i32): i32 |
One turn of the loop for a server with no TLS or QUIC listener: as waitSigned, with no key. It serves HTTP/1.1 and h2c (listenH2c). Panics when an HTTP/2 over TLS or HTTP/3 listener is configured, since a handshake there needs the key. |
waitSigned(timeoutMs: i32, key: Secret<u8[]>): i32 |
One turn of the loop: waits up to timeoutMs (-1 for no limit) for a socket to be ready, accepts, reads and writes what is, signs each TLS and QUIC handshake with key, closes what is past its timeouts, and answers how many whole requests are waiting for take. |
watch(fd: i32, id: i32): void |
Adds fd to the descriptors wait and waitSigned block on, as id: fired(id) then says whether it was readable in the last turn. For a program's own descriptors, such as signalFd() for a graceful stop. Panics on an id outside 0 to HANDLER_MAX_WATCHED - 1. |
write(r: HttpServerRequest, buf: u8[], off: i32, len: i32): i32 |
Writes buf[off .. off + len) of r's body. What the carrier has no room for is copied and sent as room comes, so buf is the caller's again on return. Body bytes of a HEAD, 204 or 304 response are dropped. Panics on another server's request, when the response is not started, on a window outside buf, or on more bytes than the declared length leaves. |
HttpServerLimits
The caps an HttpServer holds itself to; every listener's carrier is checked against them.
class HttpServerLimits
| Member | |
|---|---|
new HttpServerLimits() |
|
altSvcMaxAge: i32 |
Seconds a client may remember the Alt-Svc advertisement; 0 sends alt-svc: clear. |
altSvcPort: i32 |
The port Alt-Svc names; 0 names the HTTP/3 socket's own. |
bodyTimeout: i32 |
Milliseconds from a request's head to the end of its body. |
idleTimeout: i32 |
Milliseconds an HTTP/2 connection (over TLS or h2c) with no open stream is kept. |
jsonBytes: i32 |
Bytes in the JSON scratch buffer. At least 256. |
maxBody: i32 |
The largest request body, in bytes; past it a request is answered 413. 0 to 2^30. |
maxEvents: i32 |
The most readiness events one wait takes. |
maxFields: i32 |
The most fields a request may carry. 1 to 1024. |
maxHead: i32 |
The largest request head (method, target and fields), in bytes. 256 to 2^20. |
maxResponseFields: i32 |
The most fields a response may carry, Alt-Svc and content-length included. 2 to 256. |
prefaceTimeout: i32 |
Milliseconds a cleartext HTTP/2 connection (listenH2c) has to send its 24-byte preface; after it, idleTimeout applies. |
requests: i32 |
The most requests held at once, across every connection and version. 1 to 65536. |
HttpServerRequest
One request, whole, from any version: its head copied out of the carrier
and its body. Every position is an offset into head or body, which are
the request's own and stay valid until it is answered.
class HttpServerRequest
| Member | |
|---|---|
new HttpServerRequest(index: i32) |
An empty request for the server's pool; its buffers are made on its first use. |
body: u8[] |
The body, body[0 .. bodyLength). |
bodyLength: i32 |
How many bytes of body are the request's body, 0 for none; read the body as body[0 .. bodyLength). |
head: u8[] |
The method, the target and the header section (field names lowercased); on HTTP/2 and 3, :authority is the field host. |
index: i32 |
Its index in the server's pool. |
methodEnd: i32 |
Where the method ends in head, one past its last byte. |
methodStart: i32 |
Where the method starts in head; the method is head[methodStart .. methodEnd). |
queryValueEnd: i32 |
Where the raw value queryIndex found ends in head, one past its last byte; it starts at queryValueStart. |
queryValueStart: i32 |
The span queryIndex found, raw. |
route: i32 |
The index Router.add answered for the route, or a negative ROUTER_* code. |
secure: boolean |
Whether it came over TLS or QUIC: true on HTTP/2 over TLS and on HTTP/3. |
slot: i32 |
The connection's slot in its carrier. |
targetEnd: i32 |
Where the request target ends in head, one past its last byte. |
targetStart: i32 |
Where the request target (path and query) starts in head; the target is head[targetStart .. targetEnd). |
version: i32 |
The HTTP version it came in on: 1, 2 or 3. |
hasQuery(name: string): boolean |
Whether the query holds a parameter named name. |
header(name: string): i32 |
The index of the first field named name, which is lowercase, or HANDLER_ABSENT. |
headerIs(name: string, value: string): boolean |
Whether the first field named name (lowercase) has exactly the value value. |
methodIs(method: string): boolean |
Whether the method is exactly method (methods are case-sensitive, RFC 9110 §9.1). |
param(k: i32, out: u8[]): i32 |
Parameter k percent-decoded into out from 0 (routerDecode): its length, ROUTER_BAD_ESCAPE for a malformed escape, or ROUTER_NO_ROOM when out is too short. Nothing is written on a code. |
paramDecimal(k: i32): i32 |
Parameter k read as a decimal number that is not negative and fits an i32, or -1. |
paramEnd(k: i32): i32 |
Where parameter k ends in head. |
paramIs(k: i32, text: string): boolean |
Whether parameter k, raw, is exactly text. |
paramStart(k: i32): i32 |
Where parameter k starts in head. Panics on a parameter the route does not have. |
pathIs(path: string): boolean |
Whether the path, the target up to its ?, is exactly path. |
query(name: string, out: u8[]): i32 |
The first query parameter named name, its value decoded into out from 0 — + as a space and %XX as its byte, the form encoding (application/x-www-form-urlencoded) — and its length; a name is compared decoded too. HANDLER_ABSENT when no parameter has the name, ROUTER_BAD_ESCAPE for a malformed escape in its value, ROUTER_NO_ROOM when out is too short. A name with no = has an empty value. |
queryIndex(name: string): i32 |
Finds the first parameter named name: where its pair starts, or -1; its raw value goes to queryValue.... |
valueEnd(i: i32): i32 |
Where field i's value ends in head. |
valueStart(i: i32): i32 |
Where field i's value starts in head. |

