http
HTTP/1.1 clients and servers over http:// and https://, built on the net module.
Every request needs a net.Access permission, made by net.access() in the program’s main file and passed to the code that makes requests. What comes back from the network is Untrusted: a Reply’s reason, header values and body, and a Request’s path, query, header values and body. Turn them into Str with a check such as as_name(), path_inside(&root) or to_i64(), or with unchecked() when the text is only shown or stored.
The defaults are safe for talking to servers you do not control: limits on time and size, certificate checks that cannot be turned off, and no header injection or request smuggling through this API.
Fetch a page
Section titled “Fetch a page”import httpimport net
let access = net.access()let reply = try http.get(&access, "https://example.com/")if reply.status != 200 { print(f"failed: {reply.status} {reply.reason.unchecked()}")} else { print(reply.body.unchecked())}match reply.headers.get("content-type") { Some(t) => print(t.unchecked()) None => {}}Handle errors
Section titled “Handle errors”HttpError covers everything that stops a request: a refused connection, a timeout, a bad certificate, a malformed or oversized answer. A reply with status 404 or 500 is not an error; check status.
import httpimport net
fn fetch(access: &net.Access, address: &Str) -> Str { let reply = http.get(access, address) catch { http.HttpError(e) => return f"error: {e.message}" } if reply.status >= 400 { return f"status {reply.status}" } return reply.body.unchecked()}
let access = net.access().public_only()print(fetch(&access, "https://example.com/"))Send JSON with headers and limits
Section titled “Send JSON with headers and limits”http.client makes a client with adjustable limits. send takes any method, headers and a body.
import httpimport jsonimport netimport time
let access = net.access().only(&["api.example.com"])let client = http.client(&access).with_timeout(time.seconds(10)).with_deadline(time.minutes(1)).with_max_body(1024 * 1024)let body = json.text(&json.Json.Object([("name", json.Json.Text("brass"))]))let headers = Map { "Content-Type": "application/json", "Authorization": "Bearer abc123" }let reply = try client.send("PUT", "https://api.example.com/projects/1", &headers, &body)let answer = try json.parse(&reply.body.unchecked())print(json.pretty(&answer))let created = try client.post("https://api.example.com/projects", &body, "application/json")print(created.status)Serve requests
Section titled “Serve requests”http.handle reads requests from one connection, calls the handler for each, and writes its response. Malformed or oversized requests are answered with 400 or 413, and idle clients are dropped.
import httpimport net
fn route(req: &http.Request) -> http.Response { if req.method == "GET" && req.path.is("/") { return http.response(200, "hello\n") } if req.method == "GET" && req.path.starts_with("/users/") { match req.path.unchecked().strip_prefix("/users/").unwrap_or("").to_i64() { Some(id) => return http.response(200, f"user {id}\n") None => return http.response(400, "bad id\n") } } return http.response(404, "not found\n")}
let access = net.access()let mut server = try access.listen("127.0.0.1", 8080)while true { let mut conn = server.accept() catch { net.NetError(_) => continue } http.handle(&mut conn, &route) catch { http.HttpError(e) => eprint(e.message) }}This serves one connection at a time. Move each accepted socket into thread.join or thread.each to serve several at once.
Reference
Section titled “Reference”import httpFunctions
Section titled “Functions”client
Section titled “client”pub fn client(access: &net.Access) -> Client30 s per wait, 5 minutes per request, 5 redirects, 64 MB bodies, 64 KB headers, system roots.
Defaults: 30 seconds for each connect, read or write; 5 minutes for the whole request; 5 redirects; 64 MB bodies; 64 KB of headers; the system’s trusted roots. Each with_ method takes the client and returns a changed one, so they chain.
limits
Section titled “limits”pub fn limits() -> Limits8 MB bodies, 64 KB headers, 30 s idle.
Defaults for servers: 8 MB bodies, 64 KB of headers, and 30 seconds of waiting for the next request before the client is dropped. handle uses these defaults; handle_with(conn, handler, &limits) takes your own.
parse_url
Section titled “parse_url”pub fn parse_url(url: &Str) -> Url ! HttpErrorhttp:// or https://, then host[:port][/path]; a URL with spaces or control bytes is refused.
Accepts only http:// and https:// URLs. User names and passwords in the URL (https://me:pw@host/) are refused; send an Authorization header instead. For other URLs and for reading queries, use the url module.
pub fn send(access: &net.Access, method: &Str, url: &Str, headers: &Map<Str, Str>, body: &Str) -> Reply ! HttpErrorOne request with the default client; see client for its limits.
The method must be upper-case letters, - or _. Setting Host, Content-Length or Transfer-Encoding yourself is an error: they are set from the URL and the body. Header names or values holding a line break are refused. Every request is sent with Connection: close, so each one opens a new connection. Without a User-Agent header, brass-http is sent.
pub fn get(access: &net.Access, url: &Str) -> Reply ! HttpErrorFollows up to 5 redirects (301, 302, 303, 307, 308). A redirect from https to plain http, or to another scheme, is refused with an error. post and send do not follow redirects; they return the 3xx reply.
pub fn post(access: &net.Access, url: &Str, body: &Str, content_type: &Str) -> Reply ! HttpErrorread_request
Section titled “read_request”pub fn read_request(conn: &mut net.Socket, within: &Limits) -> Option<Request> ! HttpErrorReads the next request from a client, or None if it closed the connection between requests.
Returns None when the client closed the connection between requests. A request with both Content-Length and chunked encoding, an unsupported Transfer-Encoding, or anything over the limits is an HttpError. Request lines are limited to 16 KB.
import httpimport netimport time
fn serve(conn: &mut net.Socket) ! http.HttpError { let within = http.limits().with_max_body(1024).with_idle(time.seconds(5)) while true { match try http.read_request(conn, &within) { Some(req) => try http.write_response(conn, &http.response(200, f"{req.body.len()} bytes\n")) None => return } }}
let access = net.access()let mut server = try access.listen("", 0)let mut conn = try server.accept()try serve(&mut conn)response
Section titled “response”pub fn response(status: i64, body: Str) -> ResponseA response with a text body and the usual reason phrase.
The reason phrase is filled in for common codes (OK, Not Found and so on). For other codes it is Status; set reason yourself if it matters.
write_response
Section titled “write_response”pub fn write_response(conn: &mut net.Socket, r: &Response) ! HttpErrorWrites a response; 1xx, 204 and 304 answers have no body, so giving them one is an error.
handle
Section titled “handle”pub fn handle(conn: &mut net.Socket, handler: &fn(&Request) -> Response) ! HttpErrorAnswers every request on one connection with handler, until the client closes it or errs.
handle_with
Section titled “handle_with”pub fn handle_with(conn: &mut net.Socket, handler: &fn(&Request) -> Response, within: &Limits) ! HttpErrorLike handle, with your own limits for request size and idle time.
HttpError
Section titled “HttpError”pub struct HttpError { pub message: Str}Response
Section titled “Response”pub struct Response { pub status: i64 pub reason: Str pub headers: Map<Str, Str> pub repeated: Vec<(Str, Str)> pub body: Str}Header names are kept in lower case, so headers.get("content-type") finds any spelling.
The value a server handler returns. http.response(status, body) makes one with a plain text content type; set others with set_header, which replaces a header of the same name in any spelling, and use add_header for a header that is sent more than once:
import http
let mut r = http.response(200, "<h1>hi</h1>")r.set_header(&"content-type", &"text/html; charset=utf-8")r.set_header(&"Cache-Control", &"no-store")r.add_header(&"Set-Cookie", &"theme=dark; Path=/")r.add_header(&"Set-Cookie", &"lang=en; Path=/")print(r.headers.len())print(r.status)print(r.reason)2200OKTwo entries in headers whose names differ only in case are an error when the response is written. Content-Length is computed from the body and must not be set. A 1xx, 204 or 304 response has no body and no Content-Length; giving it a body is an error. When handle answers a HEAD request, it sends the headers, with the length of the body, but not the body. If a handler’s response is invalid, handle answers 500 and closes the connection.
Response.set_header
Section titled “Response.set_header”pub fn set_header(&mut self, name: &Str, value: &Str)Sets a header, replacing any earlier one whose name differs only in case.
Response.add_header
Section titled “Response.add_header”pub fn add_header(&mut self, name: &Str, value: &Str)Adds one more header line, even if the name is already used; for headers like Set-Cookie.
pub struct Reply { pub status: i64 pub reason: Untrusted<Str> pub headers: Map<Str, Untrusted<Str>> pub header_list: Vec<(Str, Untrusted<Str>)> pub body: Untrusted<Str>}What a server sent back; it comes from outside, so its text is Untrusted.
Header names are lower case, so look them up as headers.get("content-type"). A header sent more than once is joined into one value with , in headers. That mangles Set-Cookie, whose values contain commas, so use header_values(&"set-cookie"), which gives each value separately, in order. header_list holds every header line as sent.
Reply.header_values
Section titled “Reply.header_values”pub fn header_values(&self, name: &Str) -> Vec<Untrusted<Str>>Each value of header name, in the order sent; use it for Set-Cookie.
Request
Section titled “Request”pub struct Request { pub method: Str pub path: Untrusted<Str> pub query: Untrusted<Str> pub headers: Map<Str, Untrusted<Str>> pub header_list: Vec<(Str, Untrusted<Str>)> pub body: Untrusted<Str>}What a client sent is untrusted: path, query, header values and body turn into Str only by a check.
method is a plain Str: it has been checked to be upper-case letters. path and query are split at the first ? and are still percent-encoded. Use url.parse_query(&req.query.unchecked()) to read the query into pairs, and path_inside(&root) to turn the path into a file path that cannot leave root:
import fsimport http
fn serve_file(req: &http.Request) -> http.Response { match req.path.path_inside("/srv/www") { Some(p) => { let body = fs.read(&p) catch { fs.IoError(_) => return http.response(404, "not found\n") } return http.response(200, body) } None => return http.response(400, "bad path\n") }}
let req = http.Request { method: "GET", path: Untrusted.new("/../etc/passwd"), query: Untrusted.new(""), headers: Map.new(), header_list: [], body: Untrusted.new("") }print(serve_file(&req).status)400Request.header_values
Section titled “Request.header_values”pub fn header_values(&self, name: &Str) -> Vec<Untrusted<Str>>Each value of header name, in the order sent.
pub struct Url {}Made only by parse_url, so a Url always holds a checked host, port and path.
It also has 4 private field(s), so outside this module it is made only by this module’s functions, which check what goes in.
Url.is_tls
Section titled “Url.is_tls”pub fn is_tls(&self) -> boolUrl.host
Section titled “Url.host”pub fn host(&self) -> StrUrl.port
Section titled “Url.port”pub fn port(&self) -> i64Url.path
Section titled “Url.path”pub fn path(&self) -> StrClient
Section titled “Client”pub struct Client {}Limits keep a slow or hostile server from hanging the program or filling its memory.
It also has 7 private field(s), so outside this module it is made only by this module’s functions, which check what goes in.
Client.with_timeout
Section titled “Client.with_timeout”pub fn with_timeout(self, d: time.Duration) -> ClientHow long one connect, read or write may wait.
Client.with_deadline
Section titled “Client.with_deadline”pub fn with_deadline(self, d: time.Duration) -> ClientHow long a whole request may take, however slowly the server sends.
The deadline caps one whole request: connecting, sending, and reading the answer and its body. For get, it covers all the redirects it follows together. A server that sends one byte just before each timeout cannot stretch a request past it.
Client.with_trust
Section titled “Client.with_trust”pub fn with_trust(self, trust: net.Trust) -> Clientnet.ca_file(&files, &path) gives a Trust for only the certificates signed by the CA in that PEM file, for internal services with their own CA. The certificate is still checked.
Client.with_max_redirects
Section titled “Client.with_max_redirects”pub fn with_max_redirects(self, n: i64) -> ClientClient.with_max_body
Section titled “Client.with_max_body”pub fn with_max_body(self, bytes: i64) -> ClientClient.send
Section titled “Client.send”pub fn send(&self, method: &Str, url: &Str, headers: &Map<Str, Str>, body: &Str) -> Reply ! HttpErrorSends one request and reads the answer, without following redirects.
Client.get
Section titled “Client.get”pub fn get(&self, url: &Str) -> Reply ! HttpErrorA GET that follows redirects, never from https to http; the deadline covers all of them together.
Client.post
Section titled “Client.post”pub fn post(&self, url: &Str, body: &Str, content_type: &Str) -> Reply ! HttpErrorLimits
Section titled “Limits”pub struct Limits {}Sizes a server accepts from one client; anything larger is answered with an error.
It also has 3 private field(s), so outside this module it is made only by this module’s functions, which check what goes in.
Limits.with_max_body
Section titled “Limits.with_max_body”pub fn with_max_body(self, bytes: i64) -> LimitsLimits.with_idle
Section titled “Limits.with_idle”pub fn with_idle(self, d: time.Duration) -> Limits