module use "std/http.nib"
Http
HTTP/1.1 requests and responses as values: Http.parse turns bytes into a Request, Http.text/html/json build a Response, and Http.render turns it back into bytes.
Http is HTTP written as plain functions over values. A Http.Request is a record — method, target, version, headers, body — and a Http.Response is a status, headers and a body. Http.parse and Http.render convert between those values and the bytes on the wire, and neither touches a socket, so a handler — a function from Request to Response — can be tested by calling it.
let r = Http.parse("GET /hello?name=ada HTTP/1.1\r\nHost: example.com\r\n\r\n");
let answer = Http.text(200, "you asked for {r.target}\n");
Http.render(answer)
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Content-Length: 30
Connection: close
you asked for /hello?name=ada
To serve requests, hand a handler to Server.run, which owns the sockets, keep-alive and limits; Route adds path patterns, query strings and form bodies. The socket functions on this page — Http.listen, Http.read, Http.write — are for a program that writes its own loop.
Errors
Every function that slices strings can raise Err.IndexOutOfRange, and says so. The named refusals are data declared on this page: Http.BadRequest (the client sent something that is not a request — answer 400), Http.TooLarge (a declared body over 1 MiB — answer 413), and Http.BadHeader and Http.BadStatus, which are mistakes in the program's own response, caught when the bytes are made. Http.header raises Err.Missing for a header the client did not send.
Data
data BadRequest where
BadRequest(String)
Raised when bytes cannot be read as a request: no blank line ending the head, a malformed request line, a Content-Length that is not a decimal number (or two that disagree), a body shorter than declared, or a head over 64 KiB. The payload is a sentence saying which. The usual answer is a 400 with that sentence as its body.
try
let r = Http.parse("GET / HTTP/1.1\r\nContent-Length: 5x\r\n\r\nhello");
"parsed"
rescue BadRequest(msg) => "400: {msg}" end
400: a 'Content-Length' must be decimal digits
data BadHeader where
BadHeader(String)
Raised by Http.render when the response carries a header that cannot be sent safely: an empty name, a name with a colon, a value containing a carriage return or line feed, or a Content-Length or Connection header the program set itself. Refusing it here means a value from user input can never smuggle in an extra header line.
let r = Http.with_header(Http.text(200, "ok"), "X-Note", "line one\r\nSet-Cookie: x=1");
try Http.render(r) rescue BadHeader(msg) => msg end
the value of header 'X-Note' has a CR in it
data BadStatus where
BadStatus(String)
Raised by Http.render for a status outside 100–599, or for a 204 or 304 with a body — use Http.nothing for those.
try Http.render(Http.text(204, "gone")) rescue BadStatus(msg) => msg end
a 204 answer carries no body; use Http.nothing(204)
data TooLarge where
TooLarge(String)
Raised by Http.wanted and Http.read when a request declares a body larger than Http.max_body. It is raised from the head alone, before any body is read. The usual answer is a 413.
data Header where
name :: String;
value :: String
One header line: a name and a value. Names keep the case they were written in; Http.header compares them without it.
data Request where
method :: String;
target :: String;
version :: String;
headers :: Vec<Header>;
body :: String
One parsed request.
method—"GET","POST", … exactly as sent.target— the raw request target, path and query string together ("/search?q=nib").Route.pathandRoute.querysplit it.version— the third word of the request line, such as"HTTP/1.1", or""if the client sent only two.headers— every header line, in order, names as the client wrote them. Read them withHttp.header, which ignores case.body— exactly as many bytes asContent-Lengthdeclares;""when there is none.
Because it is a record, a test builds one directly:
let r = Http.Request{ method: "POST", target: "/notes", version: "HTTP/1.1",
headers: #[Http.Header{ name: "Content-Type", value: "text/plain" }],
body: "remember the milk" };
"{r.method} {r.target}: {String.length(r.body)} bytes"
POST /notes: 17 bytes
data Response where
status :: Int;
headers :: Vec<Header>;
body :: String
One answer: a status, the headers the program chose, and the body. Content-Length and Connection are not part of it — Http.render measures the one and decides the other, so a response can never declare a length its body disagrees with. Build one with Http.text, Http.html, Http.json or Http.nothing and add headers with Http.with_header.
let r = Http.json(200, "[\"ada\", \"bo\"]");
(r.status, Vec.size(r.headers), r.body)
(200, 1, "["ada", "bo"]")
Functions
func parse :: raw: String -> Request raises BadRequest, IndexOutOfRange
Reads one request from raw: the head, then exactly Content-Length bytes of body. Bytes after that are ignored, so raw should hold one request. Raises Http.BadRequest for anything that is not a well-formed request.
let r = Http.parse("POST /notes HTTP/1.1\r\nContent-Length: 5\r\n\r\nhello");
(r.method, r.target, r.version, r.body)
("POST", "/notes", "HTTP/1.1", "hello")
func header :: r: Request, name: String -> String raises Missing, IndexOutOfRange
The value of the request's header called name, compared without case: Accept, accept and ACCEPT are the same header. If the header appears more than once, the first wins. Raises Err.Missing when the client did not send it, so a missing header and an empty one stay different; Http.header_or answers a default instead.
let r = Http.parse("GET / HTTP/1.1\r\nUser-Agent: curl/8.4\r\n\r\n");
Http.header(r, "user-agent")
curl/8.4
func header_or :: r: Request, name: String, otherwise: String -> String raises IndexOutOfRange
Like Http.header, but answers otherwise when the header is absent.
let r = Http.parse("GET / HTTP/1.1\r\n\r\n");
Http.header_or(r, "Accept-Language", "en")
en
func text :: status: Int, body: String -> Response
A response with status, body, and Content-Type: text/plain; charset=utf-8.
let r = Http.text(404, "no such page\n");
(r.status, r.body)
(404, "no such page
")
func html :: status: Int, body: String -> Response
A response with status, body, and Content-Type: text/html; charset=utf-8.
func json :: status: Int, body: String -> Response
A response with status, body, and Content-Type: application/json; charset=utf-8. The body is sent as given; build it with Json or by hand.
func nothing :: status: Int -> Response
A response with status, no headers and no body — what 204 No Content and 304 Not Modified require.
Http.render(Http.nothing(204))
HTTP/1.1 204 No Content
Content-Length: 0
Connection: close
func with_header :: r: Response, name: String, value: String -> Response
r with one more header line added after the ones it has. Nothing is checked here; Http.render refuses a header that cannot be sent.
let r = Http.with_header(Http.text(302, ""), "Location", "/home");
Http.render(r)
HTTP/1.1 302 Found
Content-Type: text/plain; charset=utf-8
Location: /home
Content-Length: 0
Connection: close
func render_with :: r: Response, connection: String -> String raises BadHeader, BadStatus, IndexOutOfRange
Like Http.render, but with the Connection word chosen by the caller: "close" or "keep-alive", and nothing else — any other word raises Http.BadHeader. For a loop that keeps connections open.
Http.render_with(Http.nothing(204), "keep-alive")
HTTP/1.1 204 No Content
Content-Length: 0
Connection: keep-alive
func render :: r: Response -> String raises BadHeader, BadStatus, IndexOutOfRange
The bytes of r: the status line, the program's headers in order, a measured Content-Length, Connection: close, a blank line, and the body. Raises Http.BadHeader or Http.BadStatus for a response that cannot be sent as it is.
Http.render(Http.html(200, "<p>hi</p>"))
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 9
Connection: close
<p>hi</p>
func wants_close :: r: Request -> Bool raises IndexOutOfRange
Whether the connection should close after answering r. Connection: close says yes and Connection: keep-alive says no, in any case; with neither, an HTTP/1.1 request stays open and every other version closes.
let a = Http.parse("GET / HTTP/1.1\r\n\r\n");
let b = Http.parse("GET / HTTP/1.0\r\n\r\n");
let c = Http.parse("GET / HTTP/1.1\r\nConnection: Close\r\n\r\n");
(Http.wants_close(a), Http.wants_close(b), Http.wants_close(c))
(false, true, true)
func reason :: status: Int -> String
The reason phrase for a status, such as "Not Found" for 404. A status it does not know answers "Unknown"; the number is what clients act on.
(Http.reason(404), Http.reason(503), Http.reason(299))
("Not Found", "Service Unavailable", "Unknown")
func listen :: host: String, port: Int -> () raises BindFailed
Binds the listener, through Net.Socket. Calling it again for the same address does nothing; a different address raises Err.BindFailed.
func max_head :: -> Int
The largest request head, in bytes, that Http.wanted and Http.read will buffer: 64 KiB.
func max_body :: -> Int
The largest request body, in bytes, a request may declare: 1 MiB.
func wanted :: buf: String -> Int raises BadRequest, TooLarge, IndexOutOfRange
How many bytes of buf make one complete request, for a loop that keeps its own buffer. Answers -1 while the head is still incomplete; otherwise the offset just past the request's body, so String.slice(buf, 0, n) is one request and the rest is the start of the next. Raises Http.BadRequest when an unfinished head is already longer than Http.max_head, and Http.TooLarge as soon as the head declares a body over Http.max_body.
let two = "GET /a HTTP/1.1\r\n\r\nGET /b HTTP/1.1\r\n\r\n";
(Http.wanted("GET /a HT"), Http.wanted(two), String.length(two))
(-1, 19, 38)
func read :: conn: Handle -> String raises BadRequest, TooLarge, Closed, HandleRefused, IndexOutOfRange
Reads one request's bytes from conn: the head, then exactly the declared body, leaving anything after it unread. Answers "" if the peer closed without sending anything. Raises Http.BadRequest, Http.TooLarge, Err.Closed or HandleRefused.
func request :: conn: Handle -> Request raises BadRequest, TooLarge, Closed, HandleRefused, IndexOutOfRange
Http.read followed by Http.parse: the next request on conn as a value. Raises Err.Closed if the peer sent nothing.
func write :: conn: Handle, r: Response -> () raises BadHeader, BadStatus, Closed, HandleRefused, IndexOutOfRange
Renders r with Http.render and sends it on conn. The answer says Connection: close, so close conn afterwards.
A one-request-per-connection loop needs only these three functions:
use "std/http.nib"
use "std/net.nib"
module Tiny where
func serve_one :: -> () ! Net.Socket raises BadHeader, BadRequest, BadStatus, TooLarge, Err.BindFailed, Err.Closed, HandleRefused, Err.IndexOutOfRange =
let conn = @Net.Socket.accept(1000);
let r = Http.request(conn);
let _ = Http.write(conn, Http.text(200, "you sent {r.method} {r.target}\n"));
@Net.Socket.close(conn)
func main :: -> () ! Net.Socket raises BadHeader, BadRequest, BadStatus, TooLarge, Err.BindFailed, Err.Closed, HandleRefused, Err.IndexOutOfRange =
let _ = Http.listen("127.0.0.1", 8080);
Tiny.serve_one()
wire W runs Tiny.main where Net.Socket = Net.Native
Internal helpers
These are reachable — nib has no private functions — but they are the module's own plumbing, not an interface it promises to keep.
21 signature(s)
func lower :: s: String -> String raises IndexOutOfRange
func lower_byte :: ch: String -> String raises IndexOutOfRange
func ltrim :: s: String -> String raises Err.IndexOutOfRange
func ltrim_from :: s: String, at: Int, n: Int -> String raises IndexOutOfRange
func decimal :: s: String -> Int raises BadRequest, IndexOutOfRange
func check_digits :: digits: Vec<String>, at: Int -> () raises BadRequest, IndexOutOfRange
func decimal_from :: digits: Vec<String>, at: Int, n: Int -> Int raises BadRequest, IndexOutOfRange
func digit :: ch: String -> Int
func version_of :: start: Vec<String> -> String raises IndexOutOfRange
func headers_from :: lines: Vec<String>, at: Int, acc: Vec<Header> -> Vec<Header> raises IndexOutOfRange
func value_after :: line: String, colon: Int -> String raises IndexOutOfRange
func first_header :: hs: Vec<Header>, want: String, at: Int -> String raises Missing, IndexOutOfRange
func check_connection :: connection: String -> () raises BadHeader
func closes_by_default :: version: String -> Bool
func check_status :: status: Int, body: String -> () raises BadStatus
func header_line :: h: Header -> String raises BadHeader, IndexOutOfRange
func read_more :: conn: Handle, buf: String -> String raises BadRequest, TooLarge, Closed, HandleRefused, IndexOutOfRange
func read_body :: conn: Handle, buf: String, want: Int -> String raises BadRequest, Closed, HandleRefused, IndexOutOfRange
func complete :: buf: String -> Bool raises BadRequest, IndexOutOfRange
func declared_length :: head: String -> Int raises BadRequest, IndexOutOfRange
func length_scan :: lines: Vec<String>, at: Int, n: Int, seen: Bool -> Int raises BadRequest, IndexOutOfRange