std.http
HTTP/1.1 requests and responses, a client (send, fetch, TLS for https://) and a server (serve, a Router), over any std.net.Stream.
A handler is a function (Request) -> Response, which tests call directly; the wire functions take a Stream, so tests pass a mock connection.
Pattern
Section titled “Pattern”type Pattern = String where matches(it, "/[-a-zA-Z0-9_.~:/]*")A path whose segments may be names: /users/:id.
Router
Section titled “Router”type Router = { routes: List[Route] }Routes, tried in the order they were added. Dispatch is a linear scan.
Request
Section titled “Request”type Request = { method: Method, /// The path without the query, as sent: percent escapes stay /// (`/files/a%2Fb`), so a `/` inside a part is told apart from one /// between parts. `Router` decodes each part after splitting. path: String, /// The decoded query parameters: `?sort=year` is `{"sort": "year"}`. query: Dict[String, String], /// Header names are lowercase. Read them with `header` or `header_values`. headers: Headers, /// The body as UTF-8 text. body: String, /// The path parts its route named (`:id` in `/users/:id`), decoded, set by `Router.handle`. params: Dict[String, String],}A request as the server read it (read_request), handed to a handler.
Method
Section titled “Method”type Method = String where matches(it, "GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS")An HTTP method in capitals: GET, POST, ….
Response
Section titled “Response”type Response = { status: Status, headers: Headers, body: String }A response. The server refuses header values that hold line breaks.
Status
Section titled “Status”type Status = Int where 100 <= it && it <= 599An HTTP status code.
HttpError
Section titled “HttpError”type HttpError = NetError | BadMessage | BadUrlWhy an HTTP exchange failed: the network’s error, a message that isn’t the HTTP/1.1 this module reads, or a URL it can’t use.
BadMessage
Section titled “BadMessage”type BadMessage = { message: String }What arrived isn’t HTTP/1.1 as this module reads it, or passes a limit.
BadUrl
Section titled “BadUrl”type BadUrl = { url: String, message: String }A URL send can’t use.
type Url = { tls: Bool, host: String, port: Port, target: String }A URL split for a request: https://api.example.com:8443/v1/x?y=1 is
TLS to api.example.com on 8443, asking for /v1/x?y=1.
Streaming
Section titled “Streaming”type Streaming = { status: Status, headers: Headers, body: Body }A response whose body is still arriving: its status and headers, and the
body to read from the open connection. Made by open.
type Body = { conn: TcpStream, chunked: Bool, /// Bytes left: of the `content-length`, or of the current chunk. -1: up /// to the end of the stream. left: Int, /// Bytes read from the connection; those before `start` were given out. pending: List[Int] = [], /// Where the bytes not yet given out start in `pending`. start: Natural = 0, /// `pending` holds no `\n` from `start` up to here. scanned: Natural = 0, ended: Bool = false,}A response’s body read from its connection as it arrives, by
content-length, by chunks, or up to the end of the stream. Close it
when done (Body.close).
Headers
Section titled “Headers”type Headers = List[(String, String)]Header fields, in order: a name given twice (two set-cookies) is there
twice.
ServerLimits
Section titled “ServerLimits”type ServerLimits = { /// Connections open at once. More wait in the listener's backlog. connections: Positive, /// The longest wait for the next request on a connection, read whole. read: Duration, /// The longest wait to send a response. write: Duration,}How long serve waits on a connection, and how many connections it
keeps open.
Methods
Section titled “Methods”Request.param
Section titled “Request.param”fn param(self, name: String) -> Option[String]The path part the route named name: req.param("id") for /users/:id.
None if the route has no such part or the request didn’t come through a Router.
Router.new
Section titled “Router.new”fn new() -> RouterA router with no routes.
Router.on
Section titled “Router.on”fn on( mut self, method: Method, pattern: Pattern, handler: (Request) -> Response,)Sends method requests whose path fits pattern to handler.
Router.get
Section titled “Router.get”fn get(mut self, pattern: Pattern, handler: (Request) -> Response)Router.post
Section titled “Router.post”fn post(mut self, pattern: Pattern, handler: (Request) -> Response)Router.put
Section titled “Router.put”fn put(mut self, pattern: Pattern, handler: (Request) -> Response)Router.patch
Section titled “Router.patch”fn patch(mut self, pattern: Pattern, handler: (Request) -> Response)Router.delete
Section titled “Router.delete”fn delete(mut self, pattern: Pattern, handler: (Request) -> Response)Router.handle
Section titled “Router.handle”fn handle(self, req: Request) -> ResponseThe response of the first route that fits, with the named path parts in req.params.
- A
HEADrequest uses theGETroutes. - No route for the path gives 404. Routes for it, but not for this method, give 405.
Body.read_line
Section titled “Body.read_line”fn read_line(mut self) -> Result[Option[String], HttpError]The next line of the body, without its \n or \r\n: None at its
end. A line longer than line_limit() is an error.
Body.rest
Section titled “Body.rest”fn rest(mut self) -> Result[String, HttpError]The rest of the body, as text.
Body.more
Section titled “Body.more”fn more(mut self) -> Result[Bool, HttpError]Reads more of the body into pending: false at its end.
Body.close
Section titled “Body.close”fn close(mut self)Closes the connection.
Functions
Section titled “Functions”get_request
Section titled “get_request”fn get_request(path: String) -> RequestA GET request for path with no query, headers or body, for tests.
ok_html
Section titled “ok_html”fn ok_html(body: String) -> Response200 with an HTML page, such as std.web.document makes.
respond
Section titled “respond”fn respond(status: Status, content_type: String, body: String) -> ResponseA response with this status, content type and body.
ok_text
Section titled “ok_text”fn ok_text(body: String) -> Response200 with plain text.
ok_json
Section titled “ok_json”fn ok_json[T: Json](value: T) -> Response200 with value as JSON.
500 with the message when it has no JSON form, such as an integer beyond
what a JSON number holds exactly.
redirect
Section titled “redirect”fn redirect(location: String) -> Response303: the browser goes to location with a GET. Used after a form is
posted, so reloading doesn’t post it again.
match_path
Section titled “match_path”fn match_path(pattern: String, path: String) -> Option[Dict[String, String]]The names pattern gives to the parts of path, if it fits. path
is split at /, then each part is decoded (percent_decode), so
/files/a%2Fb fits /files/:name with name a/b.
method_not_allowed
Section titled “method_not_allowed”fn method_not_allowed() -> Response405: the path exists, but not for this method.
not_found
Section titled “not_found”fn not_found() -> Responsefn fetch(net: Net, url: String) -> Result[Response, HttpError]GET url.
fn send( net: Net, method: Method, url: String, headers: List[(String, String)], body: String,) -> Result[Response, HttpError]Sends a request and reads the response, on a connection of its own
(TLS for https://), closed after. Sends content-length, host and
connection: close besides headers.
parse_url
Section titled “parse_url”fn parse_url(url: String) -> Result[Url, BadUrl]http:// or https://, a host, maybe :port, then the target (/
when there is none). A host or target holding a space, a control
character or a byte past ASCII is an error: it would break the request
line or the host header.
exchange
Section titled “exchange”fn exchange( mut conn: Stream, method: Method, host: String, target: String, headers: List[(String, String)], body: String,) -> Result[Response, HttpError]Writes a request on conn and reads its response: any Stream, so a
test passes a mock. The request asks the server to close after.
read_response
Section titled “read_response”fn read_response( mut conn: Stream, method: Method,) -> Result[Response, HttpError]A response as the server sent it to a method request: the status
line, the headers (lowercase names, each as it came), the body by
content-length, chunks, or up to the end of the stream. A response to
HEAD, a 1xx, 204 or 304 has no body.
line_limit
Section titled “line_limit”fn line_limit() -> NaturalThe longest request or status line and header line read: 16 KB.
body_limit
Section titled “body_limit”fn body_limit() -> NaturalThe largest body read: 64 MB.
fn serve( listener: Listener, handler: (Request) -> Response, clock: Clock,) -> NetErrorserve_limited with server_limits().
serve_connection
Section titled “serve_connection”fn serve_connection( mut conn: Stream, handler: (Request) -> Response, clock: Clock, limits: ServerLimits,) -> Result[Natural, NetError]Answers the requests on one connection with handler until the client
closes it or asks to (connection: close), then closes it. Returns how
many requests were answered.
- A request it can’t read gets a 400 and ends the connection.
- A request not read whole within
limits.readends the connection, as
a response not sent within limits.write does.
- Each request is handled in a supervised task, a thread of its own: a
handler that panics gets the request a 500 and ends the connection.
- A
HEADrequest gets the head of the response, with the
content-length of its body.
read_request
Section titled “read_request”fn read_request(mut conn: Stream) -> Result[Option[Request], HttpError]The next request on conn: None if the client closed first. A path
with a . or .. part, as sent or once decoded, is an error.
percent_decode
Section titled “percent_decode”fn percent_decode(s: String, plus: Bool) -> String%20 as a space, and + too when plus (a query). An escape that
isn’t two hexadecimal digits, or bytes that aren’t UTF-8, stay as
written.
parse_query
Section titled “parse_query”fn parse_query(query: String) -> Dict[String, String]a=1&b=x%20y as {"a": "1", "b": "x y"}. A + is a space. A name
given twice keeps its last value.
write_response
Section titled “write_response”fn write_response(mut conn: Stream, r: Response) -> Result[(), NetError]Writes r with its content-length. A header holding a line break is
left out.
fn open( net: Net, method: Method, url: String, headers: List[(String, String)], body: String,) -> Result[Streaming, HttpError]Sends a request and reads the response’s status and headers, leaving
its body to be read as it arrives: for server-sent events and other
long responses. TLS for https://. The connection is the body’s.
header_values
Section titled “header_values”fn header_values(headers: Headers, name: String) -> List[String]The values of the header name, in any case, in order.
header
Section titled “header”fn header(headers: Headers, name: String) -> Option[String]The header name, in any case: its values joined by , when it is
given more than once (RFC 9110 5.3). None when it isn’t there. A
set-cookie can’t be joined so: read it with header_values.
visible
Section titled “visible”fn visible(s: String) -> BoolWhether s is printable ASCII without spaces, and not empty: what a
request line’s target and the host header may hold.
write_head
Section titled “write_head”fn write_head(mut conn: Stream, r: Response) -> Result[(), NetError]Writes the head of r alone, with the content-length of its body:
the answer to a HEAD request.
server_limits
Section titled “server_limits”fn server_limits() -> ServerLimits256 connections, 30 seconds to read a request and 30 to send a response.
serve_limited
Section titled “serve_limited”fn serve_limited( listener: Listener, handler: (Request) -> Response, clock: Clock, limits: ServerLimits,) -> NetErrorAccepts connections on listener and answers each in a task of its
own (serve_connection), until the listener is closed or the task is
cancelled. Returns why it stopped.
At most limits.connections are open at once: the next waits in the
backlog until one closes.
An accept the system refuses (no file descriptors left, say) is
skipped after a pause of 10 ms, and the connection waits in the backlog.