std::http
An HTTP client and server. A Request is a value; http.fetch
sends it with the ambient client and reads the whole response, and
http.stream returns a StreamedResponse, its body still arriving,
for defer StreamedResponse.close(response) to close. A status is never
an error: a 404 is a Response whose status a program checks with
Status.is_success.
response = http.get(Url"https://api.example.com/users")? if Status.is_success(response.status) then dbg Response.text(response)?
Every request runs under the context in force: its deadline bounds the
request, and cancelling the task cancels it. std::http::testing.run serves
requests with a function instead of the network, in tests and in the
tour. A Client made with Client.new holds its own options and
connection pool.
A server never reads more of a request’s body than a limit allows.
Request.form and post_form read at most 10 MB of a URL-encoded body
(Go’s ParseForm limit), and multipart_form and form_file at most
32 MB of a multipart one; they stop one byte past the limit and return
Error.BodyTooLarge. A limit on the request replaces both defaults, up
or down: Request.limit_body or the http.limit_body middleware for a
route, and the Server’s max_body for every request. Limits on one
request only lower each other, so a route cannot pass the server’s.
Request.text and json_as read a body whole under the same limit as a
URL-encoded form. Body.read_all and Body.reader read what the stream
holds, stopped only by such a limit.
Import with import std::http.
Exports
Section titled “Exports”Types
MethodStatusHeadersBodyFormPartFormFileMultipartFormProtocolRequestResponseHandlerErrorRedirectsRedirectProxyTransportProtocolsHttp2OptionsStreamedResponseClientOptionsClientServerListenerRouteEntryRouterOriginCrossOriginCorsSecurityHeadersCompressSameSiteMaxAgeCookieCookieJarConnStateProxyRequestReverseProxyTracerTraceEventPart
Interfaces
Values
continue_statusswitching_protocolsprocessingearly_hintsokcreatedacceptednon_authoritative_infono_contentreset_contentpartial_contentmulti_statusalready_reportedim_usedmultiple_choicesmoved_permanentlyfoundsee_othernot_modifieduse_proxytemporary_redirectpermanent_redirectbad_requestunauthorizedpayment_requiredforbiddennot_foundmethod_not_allowednot_acceptableproxy_auth_requiredrequest_timeoutconflictgonelength_requiredprecondition_failedrequest_entity_too_largerequest_uri_too_longunsupported_media_typerequested_range_not_satisfiableexpectation_failedteapotmisdirected_requestunprocessable_entitylockedfailed_dependencytoo_earlyupgrade_requiredprecondition_requiredtoo_many_requestsrequest_header_fields_too_largeunavailable_for_legal_reasonsinternal_server_errornot_implementedbad_gatewayservice_unavailablegateway_timeouthttp_version_not_supportedvariant_also_negotiatesinsufficient_storageloop_detectednot_extendednetwork_authentication_requireddefault
Middleware
Section titled “Middleware”A middleware takes a handler first and returns a handler, so a stack
of them reads as a pipe, each stage wrapping the ones before it:
Router.handler(router) |> http.limit_body(1_000_000). wrap_routes
wraps only a group of routes, such as every /admin route.
enum Method
Section titled “enum Method”enum Method Get Head Post Put Patch Delete Connect Options Trace Other String end
A request method. Other holds any method Go sends as written.
Method.text
Section titled “Method.text”fn text(method: Method) -> String
type function on Method
The method as it is written on the wire: GET, or Other’s text.
import std::http.Method
assert Method.text(Method.Patch) == "PATCH"
assert Method.text(Method.Other("PURGE")) == "PURGE"
Method.parse
Section titled “Method.parse”fn parse(text: String) -> Method
type function on Method
The method text names, Other for one Go has no constant for.
import std::http.Method
assert Method.parse("DELETE") == Method.Delete
assert Method.parse("PURGE") == Method.Other("PURGE")
Method.to_string
Section titled “Method.to_string”impl Display for Method
fn to_string(method: Method) -> String
impl Display.to_string
Method.inspect
Section titled “Method.inspect”impl Debug for Method
fn inspect(value: Method) -> String
impl Debug.inspect
Method.equal
Section titled “Method.equal”impl Equatable for Method
fn equal(a: Method, b: Method) -> Bool
impl Equatable.equal
Method.hash
Section titled “Method.hash”impl Hashable for Method
fn hash(value: Method) -> Int
impl Hashable.hash
type Status
Section titled “type Status”type Status Int
An HTTP status code. Any code from 100 to 999 is a Status; the
constants name the ones Go names.
Status.continue_status
Section titled “Status.continue_status”once continue_status: Status
Status.switching_protocols
Section titled “Status.switching_protocols”once switching_protocols: Status
Status.processing
Section titled “Status.processing”once processing: Status
Status.early_hints
Section titled “Status.early_hints”once early_hints: Status
Status.ok
Section titled “Status.ok”once ok: Status
Status.created
Section titled “Status.created”once created: Status
Status.accepted
Section titled “Status.accepted”once accepted: Status
Status.non_authoritative_info
Section titled “Status.non_authoritative_info”once non_authoritative_info: Status
Status.no_content
Section titled “Status.no_content”once no_content: Status
Status.reset_content
Section titled “Status.reset_content”once reset_content: Status
Status.partial_content
Section titled “Status.partial_content”once partial_content: Status
Status.multi_status
Section titled “Status.multi_status”once multi_status: Status
Status.already_reported
Section titled “Status.already_reported”once already_reported: Status
Status.im_used
Section titled “Status.im_used”once im_used: Status
Status.multiple_choices
Section titled “Status.multiple_choices”once multiple_choices: Status
Status.moved_permanently
Section titled “Status.moved_permanently”once moved_permanently: Status
Status.found
Section titled “Status.found”once found: Status
Status.see_other
Section titled “Status.see_other”once see_other: Status
Status.not_modified
Section titled “Status.not_modified”once not_modified: Status
Status.use_proxy
Section titled “Status.use_proxy”once use_proxy: Status
Status.temporary_redirect
Section titled “Status.temporary_redirect”once temporary_redirect: Status
Status.permanent_redirect
Section titled “Status.permanent_redirect”once permanent_redirect: Status
Status.bad_request
Section titled “Status.bad_request”once bad_request: Status
Status.unauthorized
Section titled “Status.unauthorized”once unauthorized: Status
Status.payment_required
Section titled “Status.payment_required”once payment_required: Status
Status.forbidden
Section titled “Status.forbidden”once forbidden: Status
Status.not_found
Section titled “Status.not_found”once not_found: Status
Status.method_not_allowed
Section titled “Status.method_not_allowed”once method_not_allowed: Status
Status.not_acceptable
Section titled “Status.not_acceptable”once not_acceptable: Status
Status.proxy_auth_required
Section titled “Status.proxy_auth_required”once proxy_auth_required: Status
Status.request_timeout
Section titled “Status.request_timeout”once request_timeout: Status
Status.conflict
Section titled “Status.conflict”once conflict: Status
Status.gone
Section titled “Status.gone”once gone: Status
Status.length_required
Section titled “Status.length_required”once length_required: Status
Status.precondition_failed
Section titled “Status.precondition_failed”once precondition_failed: Status
Status.request_entity_too_large
Section titled “Status.request_entity_too_large”once request_entity_too_large: Status
Status.request_uri_too_long
Section titled “Status.request_uri_too_long”once request_uri_too_long: Status
Status.unsupported_media_type
Section titled “Status.unsupported_media_type”once unsupported_media_type: Status
Status.requested_range_not_satisfiable
Section titled “Status.requested_range_not_satisfiable”once requested_range_not_satisfiable: Status
Status.expectation_failed
Section titled “Status.expectation_failed”once expectation_failed: Status
Status.teapot
Section titled “Status.teapot”once teapot: Status
Status.misdirected_request
Section titled “Status.misdirected_request”once misdirected_request: Status
Status.unprocessable_entity
Section titled “Status.unprocessable_entity”once unprocessable_entity: Status
Status.locked
Section titled “Status.locked”once locked: Status
Status.failed_dependency
Section titled “Status.failed_dependency”once failed_dependency: Status
Status.too_early
Section titled “Status.too_early”once too_early: Status
Status.upgrade_required
Section titled “Status.upgrade_required”once upgrade_required: Status
Status.precondition_required
Section titled “Status.precondition_required”once precondition_required: Status
Status.too_many_requests
Section titled “Status.too_many_requests”once too_many_requests: Status
Status.request_header_fields_too_large
Section titled “Status.request_header_fields_too_large”once request_header_fields_too_large: Status
Status.unavailable_for_legal_reasons
Section titled “Status.unavailable_for_legal_reasons”once unavailable_for_legal_reasons: Status
Status.internal_server_error
Section titled “Status.internal_server_error”once internal_server_error: Status
Status.not_implemented
Section titled “Status.not_implemented”once not_implemented: Status
Status.bad_gateway
Section titled “Status.bad_gateway”once bad_gateway: Status
Status.service_unavailable
Section titled “Status.service_unavailable”once service_unavailable: Status
Status.gateway_timeout
Section titled “Status.gateway_timeout”once gateway_timeout: Status
Status.http_version_not_supported
Section titled “Status.http_version_not_supported”once http_version_not_supported: Status
Status.variant_also_negotiates
Section titled “Status.variant_also_negotiates”once variant_also_negotiates: Status
Status.insufficient_storage
Section titled “Status.insufficient_storage”once insufficient_storage: Status
Status.loop_detected
Section titled “Status.loop_detected”once loop_detected: Status
Status.not_extended
Section titled “Status.not_extended”once not_extended: Status
Status.network_authentication_required
Section titled “Status.network_authentication_required”once network_authentication_required: Status
Status.from_code
Section titled “Status.from_code”fn from_code(code: Int) -> Result<Status, Error>
type function on Status
The status with code, or an Err outside 100 to 999.
import std::http.Status
assert Status.from_code(404) == Ok(Status.not_found)
assert Status.from_code(42) |> Result.is_err()
Status.code
Section titled “Status.code”fn code(status: Status) -> Int
type function on Status
The status’s number.
Status.text
Section titled “Status.text”fn text(status: Status) -> String
type function on Status
The reason phrase registered for the status, “Not Found” for 404, or "" for a code that has none.
import std::http.Status
assert Status.text(Status.not_found) == "Not Found"
assert Status.text(Status(599)) == ""
Status.line
Section titled “Status.line”fn line(status: Status) -> String
type function on Status
The status line’s code and text: “404 Not Found”.
import std::http.Status
assert Status.line(Status.teapot) == "418 I'm a teapot"
Status.is_informational
Section titled “Status.is_informational”fn is_informational(status: Status) -> Bool
type function on Status
1xx.
Status.is_success
Section titled “Status.is_success”fn is_success(status: Status) -> Bool
type function on Status
2xx.
import std::http.Status
assert Status.is_success(Status.no_content)
assert not Status.is_success(Status.found)
Status.is_redirect
Section titled “Status.is_redirect”fn is_redirect(status: Status) -> Bool
type function on Status
3xx.
Status.is_client_error
Section titled “Status.is_client_error”fn is_client_error(status: Status) -> Bool
type function on Status
4xx.
Status.is_server_error
Section titled “Status.is_server_error”fn is_server_error(status: Status) -> Bool
type function on Status
5xx.
Status.to_string
Section titled “Status.to_string”impl Display for Status
fn to_string(status: Status) -> String
impl Display.to_string
The status line’s code and text, as Status.line.
Status.inspect
Section titled “Status.inspect”impl Debug for Status
fn inspect(value: Status) -> String
impl Debug.inspect
Status.equal
Section titled “Status.equal”impl Equatable for Status
fn equal(a: Status, b: Status) -> Bool
impl Equatable.equal
Status.hash
Section titled “Status.hash”impl Hashable for Status
fn hash(value: Status) -> Int
impl Hashable.hash
type Headers
Section titled “type Headers”type Headers List<(String, String)>
Header fields in order. A name may appear more than once, and names compare without case.
Headers.canonical_key
Section titled “Headers.canonical_key”fn canonical_key(name: String) -> String
type function on Headers
name as HTTP writes header names, each word capitalized:
content-type is Content-Type. A name that holds a space or other
character a header name cannot is returned as it is.
import std::http.Headers
assert Headers.canonical_key("x-request-id") == "X-Request-Id"
Headers.get
Section titled “Headers.get”fn get(headers: Headers, name: String) -> Maybe<String>
type function on Headers
The first value of name.
import std::http.Headers
h = Headers[("Accept", "text/html"), ("accept", "*/*")]
assert Headers.get(h, "ACCEPT") == Some("text/html")
assert Headers.values(h, "accept") == ["text/html", "*/*"]
Headers.values
Section titled “Headers.values”fn values(headers: Headers, name: String) -> List<String>
type function on Headers
Every value of name, in order.
Headers.has
Section titled “Headers.has”fn has(headers: Headers, name: String) -> Bool
type function on Headers
Whether name has a value.
Headers.set
Section titled “Headers.set”fn set(headers: Headers, name: String, value: String) -> Headers
type function on Headers
The fields with name’s values replaced by value, in the place of
its first value, or added at the end.
import std::http.Headers
h = Headers[("A", "1"), ("B", "2"), ("a", "3")]
assert Headers.set(h, "a", "9") == Headers[("A", "9"), ("B", "2")]
Headers.add
Section titled “Headers.add”fn add(headers: Headers, name: String, value: String) -> Headers
type function on Headers
The fields with value added to name’s, at the end.
Headers.remove
Section titled “Headers.remove”fn remove(headers: Headers, name: String) -> Headers
type function on Headers
The fields without name.
Headers.write_to
Section titled “Headers.write_to”fn write_to(headers: Headers, w: io.Writer, except: List<String> = []) -> Result<Unit, io.Error>
type function on Headers
Writes the headers in wire format, Name: value lines each ending
in CRLF, sorted by name, leaving out the names in except. A line
break in a value is written as a space and the value is trimmed, so
no value can add a line. It writes as Go’s Header.WriteSubset.
import std::http.Headers
import std::io.Writer
(_, written) = Writer.collect(fn w -> Headers.write_to(Headers[("b", "2"), ("A", "1")], w))
assert Bytes.to_string(written) == Ok("A: 1\r\nB: 2\r\n")
(_, folded) = Writer.collect(fn w -> Headers.write_to(Headers[("X", " a\r\nb ")], w))
assert Bytes.to_string(folded) == Ok("X: a b\r\n")
Headers.inspect
Section titled “Headers.inspect”impl Debug for Headers
fn inspect(value: Headers) -> String
impl Debug.inspect
Headers.equal
Section titled “Headers.equal”impl Equatable for Headers
fn equal(a: Headers, b: Headers) -> Bool
impl Equatable.equal
enum Body
Section titled “enum Body”enum Body Empty Text String Bytes Bytes Json Json Html Html Form Query Multipart List<FormPart> Stream Reader Produce (io.Writer) -> Result<Unit, io.Error> end
A request’s or response’s body.
Variants
-
TextSent with
Content-Type: text/plain; charset=utf-8unless the request sets one. -
JsonEncoded with
Json.encode; sent withContent-Type: application/jsonunless the request sets one. -
HtmlRendered markup; sent with
Content-Type: text/html; charset=utf-8unless the request or response sets one. -
FormURL-encoded; sent with
Content-Type: application/x-www-form-urlencodedunless the request sets one. -
MultipartA
multipart/form-dataform; sent with itsContent-Typeand boundary unless the request sets one. -
StreamA stream, read once: a request’s body as a server receives it.
-
ProduceA response body a function writes as the client reads it, for streaming and server-sent events: what it writes is sent each time the writer passes bytes on, at
Writer.flushor when its buffer fills. A server’s response only; a request refuses it.
Body.reader
Section titled “Body.reader”fn reader(body: Body) -> Reader
type function on Body
A Reader over the body.
Body.read_all
Section titled “Body.read_all”fn read_all(body: Body) -> Result<Bytes, Error>
type function on Body
The whole body, a stream read to its end. It has no default limit:
a request’s body is held whole in memory unless limit_body or the
server’s max_body limits it. Request.form and multipart_form
read with a default limit.
import std::http.Body
assert Body.read_all(Body.Text("hi")) == Ok(String.to_bytes("hi"))
Body.inspect
Section titled “Body.inspect”impl Debug for Body
fn inspect(value: Body) -> String
impl Debug.inspect
enum FormPart
Section titled “enum FormPart”enum FormPart Field { name: String, value: String } File { field: String, filename: String, content_type: String = "application/octet-stream", content: Bytes } Raw { headers: Headers, content: Bytes } end
One part of a Body.Multipart form.
Variants
-
FieldA field and its value: Go’s
Writer.WriteField. -
FileA file: Go’s
Writer.CreateFormFile, with a content type. -
RawA part with headers of its own: Go’s
Writer.CreatePart.
FormPart.encode
Section titled “FormPart.encode”fn encode(parts: List<FormPart>) -> {content_type: String, body: Bytes}
type function on FormPart
parts as a multipart body, and the Content-Type that names its
boundary. The boundary is a digest of the parts, so the same parts
always encode to the same bytes.
import std::http.FormPart
encoded = FormPart.encode([FormPart.Field{name: "a", value: "1"}])
assert String.starts_with(encoded.content_type, "multipart/form-data; boundary=")
FormPart.file_disposition
Section titled “FormPart.file_disposition”fn file_disposition(field: String, filename: String) -> String
type function on FormPart
The Content-Disposition of a file part: Go’s
multipart.FileContentDisposition.
import std::http.FormPart
assert FormPart.file_disposition("doc", "a.txt") == "form-data; name=\"doc\"; filename=\"a.txt\""
FormPart.inspect
Section titled “FormPart.inspect”impl Debug for FormPart
fn inspect(value: FormPart) -> String
impl Debug.inspect
struct FormFile
Section titled “struct FormFile”struct FormFile filename: String headers: Headers = Headers[] size: Int = 0 content: Bytes end
A file a multipart form holds: Go’s multipart.FileHeader.
FormFile.open
Section titled “FormFile.open”fn open(file: FormFile) -> Reader
type function on FormFile
The file’s content as a stream.
FormFile.inspect
Section titled “FormFile.inspect”impl Debug for FormFile
fn inspect(value: FormFile) -> String
impl Debug.inspect
struct MultipartForm
Section titled “struct MultipartForm”struct MultipartForm values: Query = Query[] files: Map<String, List<FormFile>> = {} end
A multipart form: Go’s multipart.Form.
MultipartForm.inspect
Section titled “MultipartForm.inspect”impl Debug for MultipartForm
fn inspect(value: MultipartForm) -> String
impl Debug.inspect
struct Protocol
Section titled “struct Protocol”struct Protocol major: Int = 1 minor: Int = 1 end
An HTTP version.
Protocol.is_at_least
Section titled “Protocol.is_at_least”fn is_at_least(protocol: Protocol, major: Int, minor: Int) -> Bool
type function on Protocol
Whether the version is major.minor or later.
import std::http.Protocol
assert Protocol.is_at_least(Protocol{major: 2, minor: 0}, 1, 1)
assert not Protocol.is_at_least(Protocol{major: 1, minor: 0}, 1, 1)
Protocol.parse
Section titled “Protocol.parse”fn parse(text: String) -> Maybe<Protocol>
type function on Protocol
Reads an HTTP version: HTTP/, a digit, a . and a digit, as in
HTTP/1.1.
import std::http.Protocol
assert Protocol.parse("HTTP/2.0") == Some(Protocol{major: 2, minor: 0})
assert Protocol.parse("HTTP/x") == None
assert Protocol.parse("HTTP/1.-1") == None
Protocol.to_string
Section titled “Protocol.to_string”impl Display for Protocol
fn to_string(protocol: Protocol) -> String
impl Display.to_string
HTTP/1.1.
Protocol.inspect
Section titled “Protocol.inspect”impl Debug for Protocol
fn inspect(value: Protocol) -> String
impl Debug.inspect
Protocol.equal
Section titled “Protocol.equal”impl Equatable for Protocol
fn equal(a: Protocol, b: Protocol) -> Bool
impl Equatable.equal
struct Request
Section titled “struct Request”struct Request method: Method = Method.Get url: Url headers: Headers = Headers[] body: Body = Body.Empty host: Maybe<String> = None content_length: Maybe<Int> = None transfer_encoding: List<String> = [] close: Bool = False trailers: Headers = Headers[] body_limit: Maybe<Int> = None protocol: Protocol = Protocol{} remote_address: String = "" request_uri: String = "" pattern: Maybe<String> = None path_values: Map<String, String> = {} context: Context = Context.root() local_address: String = "" tls: Maybe<tls.ConnectionState> = None trace: Maybe<Tracer> = None incoming: Maybe<http_host.Incoming> = None end
A request to send, or one a server received.
Request.form
Section titled “Request.form”fn form(request: Request) -> Result<Query, Error>
type function on Request
The form’s fields: those of the body (post_form) and then the
URL’s query. It reads the body, which a request can do once, so keep
what it returns.
import std::http.{Method, Request}
import std::http::testing
import std::url.Query
r = testing.form_request(Method.Post, "/?b=2", [("a", "1")])
assert Request.form(r) == Ok(Query[("a", "1"), ("b", "2")])
Request.post_form
Section titled “Request.post_form”fn post_form(request: Request) -> Result<Query, Error>
type function on Request
The fields of the body: a URL-encoded body of a POST, PUT or
PATCH, or a multipart form’s fields.
Empty for any other request. It reads the body, at most 10 MB of a
URL-encoded one or the request’s body_limit, and returns
Error.BodyTooLarge past that.
import std::http.{Body, Method, Request}
import std::http::testing
posted = fn size: Int ->
{
..testing.request(Method.Post, "/"),
headers: Headers[("Content-Type", "application/x-www-form-urlencoded")],
body: Body.Stream(
Reader.from_text("a=${String.repeat("x", NonNegativeInt.try_from(size - 2)!)}")
),
}
end
assert Request.post_form(Request.limit_body(posted(8), 8)) |> Result.is_ok()
assert Request.post_form(Request.limit_body(posted(9), 8)) == Err(Error.BodyTooLarge{limit: 8})
twice = Request.limit_body(Request.limit_body(posted(9), 8), 100)
assert Request.post_form(twice) == Err(Error.BodyTooLarge{limit: 8})
Request.form_value
Section titled “Request.form_value”fn form_value(request: Request, key: String) -> Maybe<String>
type function on Request
The first value of key in the form (form), or None when the
form has none or does not parse.
Request.post_form_value
Section titled “Request.post_form_value”fn post_form_value(request: Request, key: String) -> Maybe<String>
type function on Request
The first value of key in the body’s fields, as Go’s
Request.PostFormValue.
Request.multipart_form
Section titled “Request.multipart_form”fn multipart_form(request: Request) -> Result<MultipartForm, Error>
type function on Request
The multipart form the body holds, as Go’s
Request.ParseMultipartForm. The whole form is read into memory,
so a body past 32 MB, or past the request’s body_limit when it
has one, is Error.BodyTooLarge; parts streams a larger
one. It reads the body.
import std::http.{Body, FormPart, Method, Request}
import std::http::testing
file = fn text: String ->
FormPart.File{field: "doc", filename: "a", content: String.to_bytes(text)}
end
upload = fn size: Int ->
overhead = Bytes.length(FormPart.encode([file("")]).body)
encoded = FormPart.encode([file(String.repeat("x", NonNegativeInt.try_from(size - overhead)!))])
{
..testing.request(Method.Post, "/upload"),
headers: Headers[("Content-Type", encoded.content_type)],
body: Body.Stream(Reader.from_bytes(encoded.body)),
}
end
assert Request.multipart_form(upload(1000)) |> Result.is_ok()
assert Request.multipart_form(Request.limit_body(upload(1000), 1000)) |> Result.is_ok()
assert Request.multipart_form(Request.limit_body(upload(1000), 999))
== Err(Error.BodyTooLarge{limit: 999})
Request.form_file
Section titled “Request.form_file”fn form_file(request: Request, field: String) -> Result<FormFile, Error>
type function on Request
The first file in the multipart form’s field field, as Go’s
Request.FormFile. It reads the body.
import std::http.{Body, FormPart, Method, Request}
import std::http::testing
parts = [
FormPart.Field{name: "note", value: "hi"},
FormPart.File{field: "doc", filename: "a.txt", content: String.to_bytes("abc")},
]
request = {
..testing.request(Method.Post, "/upload"),
headers: Headers[("Content-Type", FormPart.encode(parts).content_type)],
body: Body.Multipart(parts),
}
file = Request.form_file(request, "doc")!
assert file.filename == "a.txt"
assert file.size == 3
assert Request.form_value(request, "note") == Some("hi")
assert Request.form_file(request, "nope") == Err(Error.MissingFile{field: "nope"})
Request.text
Section titled “Request.text”fn text(request: Request) -> Result<String, Error>
type function on Request
The whole body as text. It reads at most 10 MB, or the request’s
body_limit, as post_form does, and returns Error.BodyTooLarge
past that; a body that is not UTF-8 is Error.MalformedBody, which a
handler’s ? answers with a 400. It reads the body, which a request
can do once.
import std::http.{Body, Method, Request}
import std::http::testing
posted = fn body: Body -> {..testing.request(Method.Post, "/notes"), body:}
assert Request.text(posted(Body.Stream(Reader.from_text("hello")))) == Ok("hello")
assert Request.text(Request.limit_body(posted(Body.Text("too long")), 4))
== Err(Error.BodyTooLarge{limit: 4})
assert Request.text(posted(Body.Bytes(Bytes.from_list([255]))))
== Err(Error.MalformedBody{reason: "the body is not UTF-8 text"})
Request.json_as
Section titled “Request.json_as”fn json_as<T>(request: Request) -> Result<T, Error> where T: FromJson
type function on Request
The body read as JSON into a T: Request.text, then
Json.decode_as. Text that is not JSON, or JSON that is not a T, is
Error.MalformedBody, so a handler that returns Result<_, http.Error> answers it with a 400 through ?. It does not check the
Content-Type. Give T with a binding’s annotation or as
Request.json_as<T>(request).
import std::http.{Body, Method, Request, Response, Status}
import std::http::testing
posted = fn text: String -> {..testing.request(Method.Post, "/todos"), body: Body.Text(text)}
read: Result<Map<String, String>, Error> = Request.json_as(posted(`{"title": "milk"}`))
assert read == Ok({"title" => "milk"})
assert Request.json_as<List<Int>>(posted("[1,")) |> Result.is_err()
todo = Request.json_as<{title: String, order: Maybe<Int>}>(posted(`{"title": "milk"}`))
assert todo == Ok({title: "milk", order: None})
create = fn request: Request ->
fields = Request.json_as<Map<String, String>>(request)?
Ok(Response{status: Status.created, body: Body.Text("${Map.get(fields, "title")}")})
end
answer = fn text: String -> ToResponse.to_response(create(posted(text)))
assert answer(`{"title": "milk"}`).status == Status.created
assert answer(`{"title": 7}`).status == Status.bad_request
assert Response.text(answer(`{"title": 7}`))
== Ok("malformed body: title: expected String, got int\n")
Request.cookies
Section titled “Request.cookies”fn cookies(request: Request) -> List<Cookie>
type function on Request
The cookies the request’s Cookie headers send, as Go’s
Request.Cookies; one that does not parse is left out.
import std::http.{Cookie, Method, Request}
import std::http::testing
r = Request.add_cookie(testing.request(Method.Get, "/"), Cookie{name: "a", value: "1"})
assert Request.cookie(r, "a") |> Maybe.map(fn c -> c.value) == Some("1")
spaced = Request.add_cookie(r, Cookie{name: "b", value: "x y"})
assert Headers.get(spaced.headers, "Cookie") == Some("a=1; b=\"x y\"")
Request.cookies_named
Section titled “Request.cookies_named”fn cookies_named(request: Request, name: String) -> List<Cookie>
type function on Request
The cookies named name, as Go’s Request.CookiesNamed.
Request.cookie
Section titled “Request.cookie”fn cookie(request: Request, name: String) -> Maybe<Cookie>
type function on Request
The first cookie named name, as Go’s Request.Cookie.
Request.add_cookie
Section titled “Request.add_cookie”fn add_cookie(request: Request, cookie: Cookie) -> Request
type function on Request
The request with cookie added to its Cookie header. Only its name
and value are sent; a character a value cannot carry is dropped,
and a value with a space or a comma is quoted.
Request.limit_body
Section titled “Request.limit_body”fn limit_body(request: Request, max: NonNegativeInt) -> Request
type function on Request
The request with a body that fails past max bytes, as Go’s
MaxBytesReader: reading it then returns an io.Error, and the
form readers Error.BodyTooLarge. max becomes the request’s
body_limit, which replaces the form defaults, so an upload route
can raise them; a second limit only lowers the first.
Request.user_agent
Section titled “Request.user_agent”fn user_agent(request: Request) -> Maybe<String>
type function on Request
The User-Agent header.
Request.referer
Section titled “Request.referer”fn referer(request: Request) -> Maybe<String>
type function on Request
The Referer header.
Request.basic_auth
Section titled “Request.basic_auth”fn basic_auth(request: Request) -> Maybe<(String, String)>
type function on Request
The user and password of a Basic Authorization header, whose
scheme may be written in any case.
import std::http.Request
import std::url.Url
r = Request.with_basic_auth(Request{url: Url"https://example.com"}, "ann", "pw")
assert Request.basic_auth(r) == Some(("ann", "pw"))
lower = {..r, headers: Headers[("Authorization", "basic YW5uOnB3")]}
assert Request.basic_auth(lower) == Some(("ann", "pw"))
Request.with_basic_auth
Section titled “Request.with_basic_auth”fn with_basic_auth(request: Request, user: String, password: String) -> Request
type function on Request
The request with a Basic Authorization header for user and
password.
Request.extend_read_deadline
Section titled “Request.extend_read_deadline”fn extend_read_deadline(request: Request, by: Duration) -> Result<Unit, Error>
type function on Request
Lets the client take until by from now to send the rest of the
body, past the server’s read_timeout. Go’s
ResponseController.SetReadDeadline. An Err for a request no
server received.
Request.read
Section titled “Request.read”fn read(r: Reader) -> Result<Request, Error>
type function on Request
Reads one request from r as it arrives on the wire, its body read
whole: Go’s ReadRequest. It reads no byte past the request, so the
next one on r is left whole.
import std::http.{Request, Method}
import std::io.Reader
r = Reader.from_text("POST /a?b=1 HTTP/1.1\r\nHost: x\r\nContent-Length: 2\r\n\r\nhi")
request = Request.read(r)!
assert request.method == Method.Post
assert request.url.path == "/a"
assert Body.read_all(request.body) == Ok(String.to_bytes("hi"))
Request.write_to
Section titled “Request.write_to”fn write_to(request: Request, w: Writer, proxy: Bool = False) -> Result<Unit, Error>
type function on Request
Writes the request to w as a client sends it: Go’s Request.Write,
or with proxy its WriteProxy, which names the whole URL.
Request.dump
Section titled “Request.dump”fn dump(request: Request, body: Bool = True) -> Result<String, Error>
type function on Request
The request as text, as a server received it: httputil’s
DumpRequest. Without body, the body is left out. It reads the
body.
import std::http.{Request, Method}
import std::url.Url
dumped = Request.dump(Request{method: Method.Get, url: Url.parse("http://x/a")!})!
assert String.starts_with(dumped, "GET /a HTTP/1.1")
Request.dump_outgoing
Section titled “Request.dump_outgoing”fn dump_outgoing(request: Request, body: Bool = True) -> Result<String, Error>
type function on Request
The request as text, as a client sends it: httputil’s
DumpRequestOut.
Request.parts
Section titled “Request.parts”fn parts(request: Request) -> Result<Iter<Result<Part, Error>>, Error>
type function on Request
The parts of the request’s multipart body, read as the iterator
runs, each in turn: Go’s Request.MultipartReader, for a body too
large to read whole (multipart_form). An Err when the request
is not multipart.
Request.path_value
Section titled “Request.path_value”fn path_value(request: Request, name: String) -> Maybe<String>
type function on Request
The value a router matched for the wildcard name, or None when
the matched pattern has no wildcard of that name.
Request.with_path_value
Section titled “Request.with_path_value”fn with_path_value(request: Request, name: String, value: String) -> Request
type function on Request
The request with the wildcard name matched as value.
Request.inspect
Section titled “Request.inspect”impl Debug for Request
fn inspect(value: Request) -> String
impl Debug.inspect
struct Response
Section titled “struct Response”struct Response status: Status = Status.ok headers: Headers = Headers[] body: Body = Body.Empty trailers: Headers = Headers[] protocol: Protocol = Protocol{} url: Maybe<Url> = None content_length: Maybe<Int> = None transfer_encoding: List<String> = [] close: Bool = False uncompressed: Bool = False tls: Maybe<tls.ConnectionState> = None write_timeout: Maybe<Duration> = None full_duplex: Bool = False upgrade: Maybe<(net.Connection) -> Unit> = None end
A response a client received, or one a handler returns.
Response.read
Section titled “Response.read”fn read(r: Reader, request: Request) -> Result<Response, Error>
type function on Response
Reads one response from r, to a request like request, its body
read whole: Go’s ReadResponse.
Response.write_to
Section titled “Response.write_to”fn write_to(response: Response, w: Writer) -> Result<Unit, Error>
type function on Response
Writes the response to w as a server sends it: Go’s
Response.Write.
import std::http.{Body, Response}
import std::io.Writer
(_, wire) = Writer.collect(fn w -> Response.write_to(Response{body: Body.Text("hi")}, w))
assert String.starts_with(Bytes.to_string(wire)!, "HTTP/1.1 200 OK")
Response.dump
Section titled “Response.dump”fn dump(response: Response, body: Bool = True) -> Result<String, Error>
type function on Response
The response as text: httputil’s DumpResponse. Without body, the
body is left out.
Response.upgrade
Section titled “Response.upgrade”fn upgrade(status: Status = Status.switching_protocols, headers: Headers, on_connection: (net.Connection) -> Unit) -> Response
type function on Response
A response that sends status and headers, then hands the
connection to on_connection, which speaks another protocol over
it, as a WebSocket server does after 101 Switching Protocols. The
connection is closed when on_connection returns. Go’s Hijack.
Response.cookies
Section titled “Response.cookies”fn cookies(response: Response) -> List<Cookie>
type function on Response
The cookies the response’s Set-Cookie headers set, as Go’s
Response.Cookies; one that does not parse is left out.
Response.set_cookie
Section titled “Response.set_cookie”fn set_cookie(response: Response, cookie: Cookie) -> Response
type function on Response
The response with a Set-Cookie header for cookie, as Go’s
SetCookie; a cookie Go cannot write is left out.
import std::http.{Cookie, Response, SameSite}
r = Response.set_cookie(
Response{},
Cookie{name: "id", value: "7", http_only: True, same_site: SameSite.Lax},
)
assert Headers.get(r.headers, "Set-Cookie") == Some("id=7; HttpOnly; SameSite=Lax")
Response.html
Section titled “Response.html”fn html(page: Html) -> Response
type function on Response
A page or a fragment of one: a 200 whose body is page, sent as
text/html; charset=utf-8 with its length.
import std::html.Html
import std::http.Response
import std::io.Writer
page = Html.text("a < b")
(_, wire) = Writer.collect(fn w -> Response.write_to(Response.html(page), w))
sent = Bytes.to_string(wire)!
assert String.contains(sent, "Content-Type: text/html; charset=utf-8")
assert String.contains(sent, "Content-Length: 8")
assert String.ends_with(sent, "a < b")
Response.json
Section titled “Response.json”fn json(value: ToJson, status: Status = Status.ok) -> Response
type function on Response
value as JSON: a response with status, 200 unless given, whose
body is ToJson.to_json(value), sent as application/json. A Json
value is sent as it is, and an anonymous struct as an object of its
fields.
import std::http.{Response, Status}
r = Response.json({"id" => 7, "done" => 0})
assert r.status == Status.ok
assert Headers.get(r.headers, "Content-Type") == Some("application/json")
assert Response.json_as<Map<String, Int>>(r) == Ok({"id" => 7, "done" => 0})
created = Response.json(Json.Obj{"id" => Json.Int(8)}, status: Status.created)
assert created.status == Status.created
assert Response.text(created) == Ok(`{"id":8}`)
missing = Response.json({error: "no todo 99"}, status: Status.not_found)
assert Response.text(missing) == Ok(`{"error":"no todo 99"}`)
Response.error
Section titled “Response.error”fn error(status: Status, message: String) -> Response
type function on Response
A plain-text response with status and message, as Go’s Error
writes it: text/plain; charset=utf-8, X-Content-Type-Options: nosniff, and the message and a newline.
import std::http.{Response, Status}
r = Response.error(Status.forbidden, "no")
assert Response.text(r) == Ok("no\n")
assert Headers.get(r.headers, "x-content-type-options") == Some("nosniff")
Response.not_found
Section titled “Response.not_found”fn not_found() -> Response
type function on Response
A 404 whose plain-text body is 404 page not found.
Response.redirect
Section titled “Response.redirect”fn redirect(request: Request, to: String, status: Status) -> Response
type function on Response
A redirect to to, which may be relative to the request’s path,
with status and a short HTML body for a GET or HEAD.
import std::http.{Method, Response, Status}
import std::http::testing
r = Response.redirect(testing.request(Method.Get, "/a/b"), "c", Status.found)
assert Headers.get(r.headers, "Location") == Some("/a/c")
Response.content
Section titled “Response.content”fn content(request: Request, name: String, modified: Maybe<Instant>, data: Bytes, headers: Headers = Headers[]) -> Response
type function on Response
data as the response to request. Its Content-Type comes from
the extension of name, or from the data itself, unless headers
sets one. A Range gets 206 and the parts asked for, and
the If-* conditional headers are checked against modified and
the ETag in headers, so an If-None-Match that names it is a
304. The response carries headers. It responds as Go’s
ServeContent does.
import std::http.{Method, Response, Status}
import std::http::testing
request = testing.request(Method.Get, "/f")
ranged = {..request, headers: Headers.set(.., "Range", "bytes=1-2")}
r = Response.content(ranged, "f.txt", None, String.to_bytes("hello"))
assert r.status == Status.partial_content
assert Response.text(r) == Ok("el")
head = {..request, method: Method.Head}
assert Response.content(head, "f.txt", None, String.to_bytes("hello")).content_length == Some(5)
tagged = Headers[("ETag", "\"v1\"")]
again = {..request, headers: Headers.set(.., "If-None-Match", "\"v1\"")}
assert Response.content(again, "f.txt", None, String.to_bytes("hello"), headers: tagged).status
== Status.not_modified
Response.with_headers
Section titled “Response.with_headers”fn with_headers(value: ToResponse, headers: Headers) -> Response
type function on Response
value as a response, with each of headers set in
place of any value the response has for that name. Middleware uses
it on whatever its handler returned.
import std::html.Html
import std::http.Response
r = Response.with_headers(Html"<p>hi</p>", Headers[("Cache-Control", "no-store")])
assert Headers.get(r.headers, "Cache-Control") == Some("no-store")
assert Response.text(r) == Ok("<p>hi</p>")
Response.with_default_headers
Section titled “Response.with_default_headers”fn with_default_headers(value: ToResponse, headers: Headers) -> Response
type function on Response
value as a response, with each of headers the
response does not have already: a header the handler set is kept.
import std::http.Response
r = Response.with_default_headers(
Response{headers: Headers[("X-Frame-Options", "SAMEORIGIN")]},
Headers[("X-Frame-Options", "DENY"), ("Referrer-Policy", "no-referrer")],
)
assert Headers.get(r.headers, "X-Frame-Options") == Some("SAMEORIGIN")
assert Headers.get(r.headers, "Referrer-Policy") == Some("no-referrer")
Response.text
Section titled “Response.text”fn text(response: Response) -> Result<String, Error>
type function on Response
The whole body as text.
Response.bytes
Section titled “Response.bytes”fn bytes(response: Response) -> Result<Bytes, Error>
type function on Response
The whole body.
Response.json_as
Section titled “Response.json_as”fn json_as<T>(response: Response) -> Result<T, Error> where T: FromJson
type function on Response
The whole body read as JSON into a T: Response.text, then
Json.decode_as. Text that is not JSON, or JSON that is not a T, is
Error.Protocol. It does not check the Content-Type. Give T with
a binding’s annotation or as Response.json_as<T>(response);
Response.json_as<Json> reads any JSON.
import std::http.{Body, Response}
r = Response{body: Body.Text(`{"id": 7}`)}
assert Response.json_as<Map<String, Int>>(r) == Ok({"id" => 7})
assert Response.json_as<Json>(r) == Ok(Json.Obj{"id" => Json.Int(7)})
assert Response.json_as<List<Int>>(r) |> Result.is_err()
Response.location
Section titled “Response.location”fn location(response: Response) -> Result<Maybe<Url>, Error>
type function on Response
The Location header resolved against the response’s URL.
Response.to_response
Section titled “Response.to_response”impl ToResponse for Response
fn to_response(value: Response) -> Response
Response.inspect
Section titled “Response.inspect”impl Debug for Response
fn inspect(value: Response) -> String
impl Debug.inspect
interface ToResponse
Section titled “interface ToResponse”interface ToResponse fn to_response(value: self) -> Response end
A value a handler may return: every place std::http takes a
handler takes a Handler, a (Request) -> ToResponse, and calls
to_response once on what it returns. A handler with several steps
that can fail returns Result<Response, AppError> and uses ?, and
the program’s error type implements ToResponse to render itself, as
axum’s IntoResponse does.
Response is sent as it is, Html as Response.html makes it (a 200
page), and a Result as its Ok or its Err. String has no
implementation: a handler that returns text says which kind with
Body.Text, Response.error or a content type of its own.
import std::html.Html
import std::http.{self, Body, Method, Response, Route, Router, Status}
import std::http::testing
router = Router.new([
Route.to("GET /plain", fn _ -> Response{body: Body.Text("plain")}),
Route.to("GET /page", fn _ -> Html"<p>page</p>"),
Route.to_with("GET /items/{id}", fn _, p ->
case String.to_int(p.id)
Some(n) -> Ok(Response{body: Body.Text("item ${n}")})
None -> Err(Response.error(Status.bad_request, "not a number"))
end
end),
])!
answer = fn target: String -> Router.serve(router, testing.request(Method.Get, target))
assert Response.text(answer("/plain")) == Ok("plain")
assert Response.text(answer("/page")) == Ok("<p>page</p>")
assert Response.text(answer("/items/7")) == Ok("item 7")
assert answer("/items/x").status == Status.bad_request
ToResponse.to_response
Section titled “ToResponse.to_response”fn to_response(value: self) -> Response
interface ToResponse
type Handler
Section titled “type Handler”typealias Handler (Request) -> ToResponse
A request handler: a function from a Request to any value that
converts to a response (ToResponse). Router.new, serve and the
middleware take one. A named function or a lambda is one as it stands.
enum Error
Section titled “enum Error”Error.to_response
Section titled “Error.to_response”impl ToResponse for Error
fn to_response(error: Error) -> Response
enum Error InvalidUrl { url: String, reason: String } InvalidRequest { reason: String } Dns { host: String, reason: String } Connect { address: String, reason: String } Tls { reason: String } Timeout { during: String } Canceled TooManyRedirects { count: Int } Form { reason: String } MissingFile { field: String } CrossOrigin { reason: String } RedirectRefused { url: String, reason: String } Protocol { reason: String } BodyTooLarge { limit: Int } MalformedBody { reason: String } BodyNotAllowed ContentLength HandlerTimeout Body { error: io.Error } Listen { address: String, reason: String } Pattern { pattern: String, reason: String } Unsupported { reason: String } end
Why a request got no response.
Variants
-
TimeoutThe client’s timeout, a deadline in force, or a transport timeout.
-
FormA form that does not parse, or a request that holds none of the kind asked for.
-
MissingFileRequest.form_filefound no file in the field. -
CrossOriginCrossOrigin.checkrefused a cross-origin request. -
RedirectRefusedA
Redirects.Decidefunction refused the redirect tourl. -
MalformedBodyA request body
Request.textorjson_ascould not read as asked: not UTF-8, not JSON, or JSON of another shape. -
ListenA server could not listen on
address. -
PatternA router pattern that breaks
Route’s rules or that Go’sServeMuxrefuses, or one that conflicts with an earlier pattern. -
UnsupportedThe target has no network.
Error.is_timeout
Section titled “Error.is_timeout”fn is_timeout(error: Error) -> Bool
type function on Error
Whether the error is a timeout, as Go’s Timeout() reports.
Error.to_string
Section titled “Error.to_string”impl Display for Error
fn to_string(error: Error) -> String
impl Display.to_string
Error.inspect
Section titled “Error.inspect”impl Debug for Error
fn inspect(value: Error) -> String
impl Debug.inspect
Error.equal
Section titled “Error.equal”impl Equatable for Error
fn equal(a: Error, b: Error) -> Bool
impl Equatable.equal
enum Redirects
Section titled “enum Redirects”enum Redirects Follow { max: Int = 10 } Never Decide (Request, List<Request>) -> Redirect end
Which redirects a client follows.
Variants
-
FollowFollow up to
maxredirects, as Go does (10). -
NeverReturn the redirect response itself.
-
DecideAsk a function before each redirect, as Go’s
CheckRedirectdoes. It gets the request the redirect would send and the requests already sent, oldest first, and returns whether to send it. There is no limit but the function’s.
Redirects.inspect
Section titled “Redirects.inspect”impl Debug for Redirects
fn inspect(value: Redirects) -> String
impl Debug.inspect
enum Redirect
Section titled “enum Redirect”enum Redirect Follow Stop Refuse String end
What a Redirects.Decide function returns for one redirect.
Variants
-
FollowSend the request.
-
StopReturn the redirect response itself, as Go’s
ErrUseLastResponse. -
RefuseFail the request with
Error.RedirectRefusedandreason.
Redirect.inspect
Section titled “Redirect.inspect”impl Debug for Redirect
fn inspect(value: Redirect) -> String
impl Debug.inspect
enum Proxy
Section titled “enum Proxy”enum Proxy FromEnvironment Direct Fixed Url end
Where a client’s requests go through.
Variants
-
FromEnvironmentHTTP_PROXY,HTTPS_PROXYandNO_PROXY, as Go reads them. -
DirectNo proxy.
-
FixedEvery request through
url.
Proxy.inspect
Section titled “Proxy.inspect”impl Debug for Proxy
fn inspect(value: Proxy) -> String
impl Debug.inspect
struct Transport
Section titled “struct Transport”struct Transport proxy: Proxy = Proxy.FromEnvironment tls_handshake_timeout: Duration = Duration.seconds(10) keep_alives: Bool = True compression: Bool = True max_idle: Int = 100 max_idle_per_host: Int = 2 max_per_host: Maybe<Int> = None idle_timeout: Maybe<Duration> = Some(Duration.seconds(90)) response_header_timeout: Maybe<Duration> = None expect_continue_timeout: Duration = Duration.seconds(1) max_response_header_bytes: Maybe<Int> = None write_buffer_size: Maybe<Int> = None read_buffer_size: Maybe<Int> = None force_http2: Bool = True protocols: Maybe<Protocols> = None http2: Http2Options = Http2Options{} proxy_connect_headers: Headers = Headers[] on_proxy_connect: Maybe<(Url, Response) -> Result<Unit, Error>> = None end
How a client’s connections are made and kept: Go’s Transport options.
A timeout past about 292 years, the longest wait the clock counts, never
fires.
Transport.default
Section titled “Transport.default”once default: Transport struct Transport proxy: Proxy tls_handshake_timeout: Duration keep_alives: Bool compression: Bool max_idle: Int max_idle_per_host: Int max_per_host: Maybe<Int> idle_timeout: Maybe<Duration> response_header_timeout: Maybe<Duration> expect_continue_timeout: Duration max_response_header_bytes: Maybe<Int> write_buffer_size: Maybe<Int> read_buffer_size: Maybe<Int> force_http2: Bool protocols: Maybe<Protocols> http2: Http2Options proxy_connect_headers: Headers on_proxy_connect: Maybe<(Url, Response) -> Result<Unit, Error>> end
The options Go’s DefaultTransport has.
Transport.inspect
Section titled “Transport.inspect”impl Debug for Transport
fn inspect(value: Transport) -> String
impl Debug.inspect
struct Protocols
Section titled “struct Protocols”struct Protocols http1: Bool = True http2: Bool = True unencrypted_http2: Bool = False end
The HTTP protocols a server accepts or a transport speaks: Go’s
Protocols.
Protocols.to_string
Section titled “Protocols.to_string”impl Display for Protocols
fn to_string(protocols: Protocols) -> String
impl Display.to_string
import std::http.Protocols
assert "${Protocols{}}" == "{HTTP1,HTTP2}"
Protocols.inspect
Section titled “Protocols.inspect”impl Debug for Protocols
fn inspect(value: Protocols) -> String
impl Debug.inspect
Protocols.equal
Section titled “Protocols.equal”impl Equatable for Protocols
fn equal(a: Protocols, b: Protocols) -> Bool
impl Equatable.equal
struct Http2Options
Section titled “struct Http2Options”struct Http2Options max_concurrent_streams: Maybe<Int> = None strict_max_concurrent_requests: Bool = False max_decoder_header_table_size: Maybe<Int> = None max_encoder_header_table_size: Maybe<Int> = None max_read_frame_size: Maybe<Int> = None max_receive_buffer_per_connection: Maybe<Int> = None max_receive_buffer_per_stream: Maybe<Int> = None send_ping_timeout: Maybe<Duration> = None ping_timeout: Maybe<Duration> = None write_byte_timeout: Maybe<Duration> = None permit_prohibited_cipher_suites: Bool = False on_error_count: Maybe<(String) -> Unit> = None end
HTTP/2’s limits and timeouts: Go’s HTTP2Config. None and False
are Go’s defaults.
Http2Options.inspect
Section titled “Http2Options.inspect”impl Debug for Http2Options
fn inspect(value: Http2Options) -> String
impl Debug.inspect
struct StreamedResponse
Section titled “struct StreamedResponse”struct StreamedResponse status: Status headers: Headers body: Reader protocol: Protocol url: Maybe<Url> content_length: Maybe<Int> tls: Maybe<tls.ConnectionState> end
A response whose body is still arriving: what http.stream and
Client.stream return. It holds its connection until its body is
closed, so defer StreamedResponse.close(response) follows it (spec §9
Releasing resources). http.fetch’s Response holds its body whole.
StreamedResponse.close
Section titled “StreamedResponse.close”fn close(response: StreamedResponse) -> Unit
type function on StreamedResponse
Closes the body, so its connection is released.
StreamedResponse.release
Section titled “StreamedResponse.release”impl Release for StreamedResponse
fn release(response: StreamedResponse) -> Unit
impl Release.release
StreamedResponse.inspect
Section titled “StreamedResponse.inspect”impl Debug for StreamedResponse
fn inspect(value: StreamedResponse) -> String
impl Debug.inspect
struct ClientOptions
Section titled “struct ClientOptions”struct ClientOptions timeout: Maybe<Duration> = None redirects: Redirects = Redirects.Follow{} transport: Transport = Transport.default round_trip: Maybe<(Request) -> Result<Response, Error>> = None max_body: Maybe<Int> = Some(67_108_864) cookies: Maybe<CookieJar> = None end
A client’s options. A timeout past about 292 years, the longest wait the clock counts, never fires.
ClientOptions.inspect
Section titled “ClientOptions.inspect”impl Debug for ClientOptions
fn inspect(value: ClientOptions) -> String
impl Debug.inspect
struct Client
Section titled “struct Client”struct Client handle: http_host.Client options: ClientOptions end
A client: its options and its connection pool. Make one with
Client.new and keep it; the pool is Go’s, which only std::http can name.
Client.new
Section titled “Client.new”fn new(options: ClientOptions = ClientOptions{}) -> Client
type function on Client
A client with options.
Client.with_tls
Section titled “Client.with_tls”fn with_tls(client: Client, config: tls.ClientConfig) -> Result<Client, tls.Error>
type function on Client
The client checking servers and offering what config says over
TLS, in place of Go’s defaults, with the same options and cookies,
or the tls.Error for a config Go cannot build: roots that hold no
certificate, a roots file that cannot be read, or a certificate or
key that does not parse.
import std::tls.{ClientConfig, Roots}
assert Client.new() |> Client.with_tls(ClientConfig{roots: Roots.Pem("none")}) |> Result.is_err()
assert Client.new() |> Client.with_tls(ClientConfig{}) |> Result.is_ok()
Client.fetch
Section titled “Client.fetch”fn fetch(client: Client, request: Request) -> Result<Response, Error>
type function on Client
Sends request and reads the whole body into Body.Bytes.
Client.stream
Section titled “Client.stream”fn stream(client: Client, request: Request) -> Result<StreamedResponse, Error>
type function on Client
Sends request and returns the response with its body still
arriving, read as it arrives, of any size. Defer
StreamedResponse.close on the next line, so the body is closed
however the function ends. A faked or round-tripped response’s body
is read from memory.
Client.get
Section titled “Client.get”fn get(client: Client, url: Url) -> Result<Response, Error>
type function on Client
A GET of url.
Client.head
Section titled “Client.head”fn head(client: Client, url: Url) -> Result<Response, Error>
type function on Client
A HEAD of url.
Client.post
Section titled “Client.post”fn post(client: Client, url: Url, body: Body) -> Result<Response, Error>
type function on Client
A POST of body to url.
Client.post_form
Section titled “Client.post_form”fn post_form(client: Client, url: Url, form: Query) -> Result<Response, Error>
type function on Client
A POST of form, URL-encoded, to url.
Client.close_idle
Section titled “Client.close_idle”fn close_idle(client: Client) -> Unit
type function on Client
Closes the client’s idle connections.
Client.inspect
Section titled “Client.inspect”impl Debug for Client
fn inspect(value: Client) -> String
impl Debug.inspect
http.default_client
Section titled “http.default_client”fn default_client() -> Client
The client http.fetch and the other module functions use: the default
options over one connection pool the whole program shares, as Go’s
DefaultClient. std::http::testing.run responds in its place.
http.fetch
Section titled “http.fetch”fn fetch(request: Request) -> Result<Response, Error>
Sends request with the default client and reads the whole response.
http.stream
Section titled “http.stream”fn stream(request: Request) -> Result<StreamedResponse, Error>
Sends request with the default client and returns the response with
its body still arriving, as Client.stream does. Defer
StreamedResponse.close on the next line.
response = http.stream(Request{url:})? defer StreamedResponse.close(response)
import std::http.{Body, Request, Response, StreamedResponse}
import std::http::testing
import std::url.Url
fn first_line(url: Url) -> Result<Maybe<String>, Error>
response = stream(Request{url:})?
defer StreamedResponse.close(response)
Reader.read_line(response.body) |> Result.map_err(fn e -> Error.Body{error: e})
end
ran = testing.run(fn _ -> Ok(Response{body: Body.Text("one\ntwo\n")}), fn ->
first_line(Url"https://example.com/log")
end)
assert ran.value == Ok(Some("one"))
http.get
Section titled “http.get”fn get(url: Url) -> Result<Response, Error>
A GET of url with the default client.
http.head
Section titled “http.head”fn head(url: Url) -> Result<Response, Error>
A HEAD of url with the default client.
http.post
Section titled “http.post”fn post(url: Url, body: Body) -> Result<Response, Error>
A POST of body to url with the default client.
http.post_form
Section titled “http.post_form”fn post_form(url: Url, form: Query) -> Result<Response, Error>
A POST of form to url with the default client.
struct Server
Section titled “struct Server”struct Server address: String = ":http" read_timeout: Maybe<Duration> = None read_header_timeout: Maybe<Duration> = None write_timeout: Maybe<Duration> = None idle_timeout: Maybe<Duration> = None max_header_bytes: Int = 1_048_576 max_body: Maybe<NonNegativeInt> = None keep_alives: Bool = True request_timeout: Maybe<Duration> = None shutdown_timeout: Duration = Duration.seconds(5) tls: Maybe<tls.ServerConfig> = None max_header_value_count: Maybe<Int> = None answer_options_star: Bool = True client_priority: Bool = True protocols: Maybe<Protocols> = None http2: Http2Options = Http2Options{} on_connection_state: Maybe<(String, ConnState) -> Unit> = None on_error: Maybe<(String) -> Unit> = None on_shutdown: Maybe<() -> Unit> = None end
How a server listens and responds. A timeout of None is none, and one
past about 292 years, the longest wait the clock counts, never fires.
Server.inspect
Section titled “Server.inspect”impl Debug for Server
fn inspect(value: Server) -> String
impl Debug.inspect
struct Listener
Section titled “struct Listener”struct Listener handle: http_host.Listener server: Server end
A server listening for requests: listen binds it, and serve responds to
what arrives.
Listener.address
Section titled “Listener.address”fn address(listener: Listener) -> String
type function on Listener
The address the server is bound to, with the port it picked when its address asked for port 0.
Listener.shutdown
Section titled “Listener.shutdown”fn shutdown(listener: Listener) -> Unit
type function on Listener
Stops the server as Go’s Server.Shutdown does: it stops accepting,
waits up to the server’s shutdown_timeout for the requests it is
serving, then closes every connection. A second call does nothing.
Listener.close_connections
Section titled “Listener.close_connections”fn close_connections(listener: Listener) -> Unit
type function on Listener
Closes every connection the server holds, idle or busy; the server goes on accepting.
Listener.inspect
Section titled “Listener.inspect”impl Debug for Listener
fn inspect(value: Listener) -> String
impl Debug.inspect
http.listen
Section titled “http.listen”fn listen(server: Server = Server{}) -> Result<Listener, Error>
Binds the server’s address. The server accepts connections from here
on; serve responds to the requests they send.
http.serve
Section titled “http.serve”fn serve(listener: Listener, handler: Handler, supervisor: Supervisor) -> Unit
Serves each request listener receives with handler, each as a task
of supervisor, so its max_running bounds the requests served at
once. Returns when the calling task is stopped, as at shutdown, after
shutting the listener down.
A handler runs under the request’s context: the context in force here,
with the server’s request_timeout as a deadline. The app’s Context
field reads it while the handler runs, and request.context holds it.
The handler’s task is stopped when the client goes away. A handler that
traps sends a 500. Use a supervisor that does not restart its tasks
(Restart.Temporary, the default); a restarted handler sends nothing.
When the program shuts down, at a signal or when main returns, the
server stops accepting at once, as Go’s Server.Shutdown does. The
requests it took run to their end, for up to the server’s
shutdown_timeout and the supervisor’s, and then serve returns.
type Route
Section titled “type Route”type Route<P = Unit> String
opaque — construction surface is private to its defining module
A pattern a Router routes by, as Go’s ServeMux reads it:
[METHOD ][HOST]/PATH, where a path segment {name} matches one
segment, a last {name...} the rest of the path, and {$} only the
end. A pattern with no method matches every method.
P is the route’s path parameters: an anonymous struct with a field
per wildcard, Route<{id: Uuid}> for GET /posts/{id}, or Unit for
a route with none, which is the default: a Route is a Route<Unit>. A
field’s type implements Parse and Display, and a {rest...} field
is a String. A literal with no expected type has
a String field per wildcard, so Route"GET /users/{id}" is a
Route<{id: String}>; a typed one names its fields’ types:
post: Route<{id: Uuid}> = "GET /posts/{id}". Route.to_with hands a
handler the parsed parameters and Route.path_with fills them into a
link. The parameters are a type only: a Route holds its text.
Two rules are stricter than Go’s. The method is one of Method’s
named variants, written in capitals as on the wire (GET, HEAD,
POST, PUT, PATCH, DELETE, CONNECT, OPTIONS, TRACE), so a
misspelled GETX is an error rather than a route no request reaches;
Route.with_method takes any other. A { or } appears only in a
wildcard that is a whole segment, so /token} is an error rather than
a literal segment; a path that needs a brace percent-encodes it
(%7B, %7D).
A Route literal is checked when the program is checked, so a pattern
that breaks these rules, that Go refuses, or whose wildcards are not
P’s fields is a compile error at the literal. A pattern built at run
time goes through Route.parse.
assert "${Route"GET /users/{id}"}" == "GET /users/{id}"
assert Route.parse<Unit>("GET /a/{x}/{x}") |> Result.is_err()
assert Route.parse<{rest: String}>("/files/{rest...}/more") |> Result.is_err()
assert Route.parse<Unit>("GETX /complete-profile/token}") |> Result.is_err()
assert Route.parse<Unit>("/a/%7Bliteral%7D") |> Result.is_ok()
Route.parse
Section titled “Route.parse”fn parse<P>(text: String) -> Result<Route<P>, Error> where P: ParseFields
type function on Route
The route text names, or Error.Pattern with the reason when
it breaks Route’s rules, Go’s ServeMux refuses it, or its
wildcards are not P’s fields. The method, when there is one, is a
standard one in capitals; a near miss names the method it is close
to.
assert Route.parse("POST /orders") == Ok(Route"POST /orders")
assert Err(Error.Pattern{reason:}) = Route.parse<Unit>("GET users")
assert String.contains(reason, "/")
assert Route.parse<Unit>("GETX /complete-profile") == Err(Error.Pattern{
pattern: "GETX /complete-profile",
reason: "unknown method `GETX`; did you mean `GET`?",
})
assert Err(Error.Pattern{reason: lower}) = Route.parse<Unit>("get /orders")
assert lower == "unknown method `get`; did you mean `GET`?"
assert Err(Error.Pattern{reason: webdav}) = Route.parse<Unit>("PROPFIND /files")
assert webdav == "unknown method `PROPFIND`; a route's method is GET, HEAD, POST, PUT, PATCH, DELETE, CONNECT, OPTIONS or TRACE, and `Route.with_method` takes any other"
assert Err(Error.Pattern{reason: closing}) = Route.parse<Unit>("GET /complete-profile/token}")
assert closing == "a `}` outside a wildcard; a wildcard is a whole segment, `{name}`"
assert Err(Error.Pattern{reason: opening}) = Route.parse<Unit>("/files/v{n}")
assert opening == "a `{` outside a wildcard; a wildcard is a whole segment, `{name}`"
assert Route.parse<{id: Int}>("GET /items/{id}") |> Result.is_ok()
assert Err(Error.Pattern{reason: fields}) = Route.parse<{id: Int}>("GET /items/{key}")
assert fields == "the pattern's wildcards are {key}, and the parameters' fields are id"
Route.with_method
Section titled “Route.with_method”fn with_method<P>(method: Method, path: String) -> Result<Route<P>, Error> where P: ParseFields
type function on Route
The route of method on path ([HOST]/PATH), for a method a
Route literal does not take: one Method.Other holds, such as
WebDAV’s PROPFIND. A standard method is written in the literal,
Route"GET /files". The path keeps the literal’s rule for
braces, the method is a token Go accepts, with no space, and the
wildcards are P’s fields, as Route.parse holds them.
import std::http.{Body, Method, Request, Response, Route, Router}
import std::http::testing
propfind = Route.with_method<{name: String}>(Method.Other("PROPFIND"), "/files/{name}")!
assert "${propfind}" == "PROPFIND /files/{name}"
router = Router.new([Route.to_with(propfind, fn _, p -> Response{body: Body.Text(p.name)})])!
answer = Router.serve(router, testing.request(Method.Other("PROPFIND"), "/files/a.txt"))
assert Response.text(answer) == Ok("a.txt")
assert Route.with_method<Unit>(Method.Get, "/a") == Ok(Route"GET /a")
assert Route.with_method<Unit>(Method.Other(""), "/a") |> Result.is_err()
assert Route.with_method<Unit>(Method.Other("PROP FIND"), "/a") |> Result.is_err()
assert Route.with_method<Unit>(Method.Other("PROPFIND"), "/a}") |> Result.is_err()
Route.path
Section titled “Route.path”fn path(route: Route) -> Url
type function on Route
The path a route with no parameters matches, for a link: the
pattern without its method or host, and a {$} dropped. A route
with parameters fills them with Route.path_with.
assert "${Route.path(Route"GET /about")}" == "/about"
assert "${Route.path(Route"GET example.com/docs/{$}")}" == "/docs/"
Route.path_with
Section titled “Route.path_with”fn path_with<P>(route: Route<P>, params: P) -> Url where P: ParseFields
type function on Route
The path the route matches with params in its wildcards, for a
link: each field’s Display text escaped as one path segment, a
{rest...} field’s text escaped segment by segment, and the
pattern’s method and host left out.
users = Route"GET /users/{name}/posts/{rest...}"
link = Route.path_with(users, {name: "ann b", rest: "2024/a?b"})
assert "${link}" == "/users/ann%20b/posts/2024/a%3Fb"
Route.to
Section titled “Route.to”fn to(route: Route, handler: Handler) -> Entry
type function on Route
The router entry that sends a request the route matches to
handler, for a route with no parameters. A route with parameters
hands them to its handler with Route.to_with.
Route.to_with
Section titled “Route.to_with”fn to_with<P>(route: Route<P>, handler: (Request, P) -> ToResponse) -> Entry where P: ParseFields
type function on Route
The router entry that sends a request the route matches to
handler, with its path parameters read into P, each wildcard’s
text by its field’s Parse. A request whose wildcard text does not
parse gets 404, as if no route matched: GET /posts/{id} with an
id: Int does not match /posts/latest.
import std::http.{Body, Method, Response, Route, Router, Status}
import std::http::testing
item: Route<{id: Int}> = "GET /items/{id}"
router = Router.new(
[Route.to_with(item, fn _, p -> Response{body: Body.Text("item ${p.id + 1}")})]
)!
answer = fn target: String -> Router.serve(router, testing.request(Method.Get, target))
assert Response.text(answer("/items/7")) == Ok("item 8")
assert answer("/items/x").status == Status.not_found
Route.check
Section titled “Route.check”impl CheckedLiteral<String, Route<P>> for Route<P>
fn check(statics: List<String>) -> Result<Unit, LiteralError>
impl CheckedLiteral.check
Route.check_type
Section titled “Route.check_type”impl CheckedLiteral<String, Route<P>> for Route<P>
fn check_type(statics: List<String>, arguments: List<String>) -> Result<Unit, LiteralError>
impl CheckedLiteral.check_type
Route.build
Section titled “Route.build”impl CheckedLiteral<String, Route<P>> for Route<P>
fn build(fragments: List<Fragment<String>>) -> Route<P>
impl CheckedLiteral.build
Route.to_string
Section titled “Route.to_string”impl Display for Route<P>
fn to_string(route: Route<P>) -> String
impl Display.to_string
Route.inspect
Section titled “Route.inspect”impl Debug for Route<P>
fn inspect<P>(value: Route<P>) -> String where P: Debug
impl Debug.inspect
Route.equal
Section titled “Route.equal”impl Equatable for Route<P>
fn equal<P>(a: Route<P>, b: Route<P>) -> Bool where P: Equatable
impl Equatable.equal
Route.hash
Section titled “Route.hash”impl Hashable for Route<P>
fn hash<P>(value: Route<P>) -> Int where P: Hashable
impl Hashable.hash
struct Entry
Section titled “struct Entry”struct Entry
opaque — construction surface is private to its defining module
A route and the handler it sends requests to, for Router.new:
Route.to and Route.to_with make one. It leaves out the route’s
parameters type, so routes with different parameters fit one list.
Entry.to_string
Section titled “Entry.to_string”impl Display for Entry
fn to_string(entry: Entry) -> String
impl Display.to_string
Entry.inspect
Section titled “Entry.inspect”impl Debug for Entry
fn inspect(value: Entry) -> String
impl Debug.inspect
struct Router
Section titled “struct Router”struct Router mux: http_host.Mux handlers: List<(Request) -> Maybe<Response>> end
Routes requests to handlers by pattern, with the rules of Go’s
ServeMux: [METHOD ][HOST]/PATH, where a path segment {name}
matches one segment, a last {name...} the rest of the path, and
{$} only the end. The most specific pattern wins; GET also matches
HEAD. A request whose path is not clean, or that lacks a trailing
slash a pattern has, is redirected; one whose path matches only under
another method gets 405 with Allow; anything else gets 404.
import std::http.{Body, Method, Request, Response, Route, Router, Status}
import std::http::testing
router = Router.new([
Route.to_with("GET /users/{id}", fn _, p -> Response{body: Body.Text("user ${p.id}")}),
Route.to("/files/", fn r -> Response{body: Body.Text(r.url.path)}),
Route.to_with("/raw/{path...}", fn r, _ -> Response{
body: Body.Text(Request.path_value(r, "path")!),
}),
])!
user = Router.serve(router, testing.request(Method.Get, "/users/7"))
assert Response.text(user) == Ok("user 7")
assert Response.text(Router.serve(router, testing.request(Method.Get, "/raw/a/b.txt")))
== Ok("a/b.txt")
assert Router.serve(router, testing.request(Method.Post, "/users/7")).status
== Status.method_not_allowed
assert Router.serve(router, testing.request(Method.Get, "/nope")).status == Status.not_found
Router.new
Section titled “Router.new”fn new(routes: List<Entry>) -> Result<Router, Error>
type function on Router
A router over routes, each a route and its handler from
Route.to or Route.to_with, in order. A pattern that conflicts
with an earlier one, matching the same requests with neither more
specific, is Error.Pattern, where Go’s Handle panics. Each
pattern on its own was checked when it became a Route.
import std::http.{Error, Response, Route, Router}
conflict = Router.new(
[Route.to_with("/a/{x}", fn _, _ -> Response{}), Route.to_with("/a/{y}", fn _, _ -> Response{})]
)
assert Result.is_err(conflict)
Router.find
Section titled “Router.find”fn find(router: Router, request: Request) -> Maybe<String>
type function on Router
The pattern that matches request, or None when none does, as
Go’s ServeMux.Handler finds it.
Router.serve
Section titled “Router.serve”fn serve(router: Router, request: Request) -> Response
type function on Router
Serves request with the handler of the pattern that matches it,
with request.pattern and its path values set, or with what the
router sends itself: a redirect, a 405 or a 404. A route whose
parameters do not parse from the request’s path is a 404 too.
Router.handler
Section titled “Router.handler”fn handler(router: Router) -> (Request) -> Response
type function on Router
The router as a handler, for http.serve.
Router.inspect
Section titled “Router.inspect”impl Debug for Router
fn inspect(value: Router) -> String
impl Debug.inspect
http.not_found
Section titled “http.not_found”fn not_found(Request) -> Response
A handler that responds to every request with Response.not_found.
http.redirect_to
Section titled “http.redirect_to”fn redirect_to(to: String, status: Status) -> (Request) -> Response
A handler that redirects every request to to with status
(Response.redirect).
http.strip_prefix
Section titled “http.strip_prefix”fn strip_prefix(handler: Handler, prefix: String) -> (Request) -> Response
Middleware that removes prefix from the request’s path, and from its
escaped form, before handler sees it, and returns 404 for a path
without it.
import std::http.{Body, Method, Request, Response}
import std::http::testing
import std::url.Url
show = http.strip_prefix(fn r -> Response{body: Body.Text(Url.escaped_path(r.url))}, "/static")
assert Response.text(show(testing.request(Method.Get, "/static/a.css"))) == Ok("/a.css")
assert show(testing.request(Method.Get, "/a.css")).status == Status.not_found
assert Response.text(show(testing.request(Method.Get, "/static/a%2Fb.css"))) == Ok("/a%2Fb.css")
http.allow_query_semicolons
Section titled “http.allow_query_semicolons”fn allow_query_semicolons(handler: Handler) -> (Request) -> Response
Middleware that reads a ; in the query as a &, for clients that
still separate fields with ;. Without it, a ; in the query is an
error to Query.parse.
import std::http.{self, Body, Method, Request, Response}
import std::http::testing
import std::url.{Query, Url}
seen = http.allow_query_semicolons(fn r -> Response{
body: Body.Text(Query.encode(Url.query_values(r.url))),
})
response = seen(testing.request(Method.Get, "/?a=1;b=2"))
assert Response.text(response) == Ok("a=1&b=2")
http.timeout
Section titled “http.timeout”fn timeout(handler: Handler, after: Duration, message: String) -> (Request) -> Response
Middleware that returns 503 Service Unavailable with message when
handler has not returned within after, and stops the handler’s
task.
import std::duration.Duration
import std::http.{self, Body, Method, Request, Response, Status}
import std::http::testing
import std::timer
sleepy = fn _: Request ->
timer.sleep(Duration.seconds(5))
Response{body: Body.Text("late")}
end
slow = sleepy |> http.timeout(Duration.milliseconds(20), "too slow")
assert slow(testing.request(Method.Get, "/")).status == Status.service_unavailable
fast = http.timeout(
fn _: Request -> Response{body: Body.Text("ok")},
Duration.milliseconds(20),
"too slow",
)
assert Response.text(fast(testing.request(Method.Get, "/"))) == Ok("ok")
type Origin
Section titled “type Origin”type Origin String
opaque — construction surface is private to its defining module
A web origin, scheme://host[:port], as a browser sends it in an
Origin header: no path, query, fragment or user. Origin"https://app.example.com"
is checked when the program is checked; Origin.parse checks one
read at run time. The scheme and host are kept in lowercase, as a
browser writes them, so an origin compares equal to the header’s text.
import std::http.Origin
assert "${Origin"HTTPS://App.Example.com:8443"}" == "https://app.example.com:8443"
assert Origin.parse("https://app.example.com/") |> Result.is_err()
assert Origin.parse("app.example.com") |> Result.is_err()
Origin.parse
Section titled “Origin.parse”fn parse(text: String) -> Result<Origin, Error>
type function on Origin
The origin text names, or Error.InvalidUrl when it is not
scheme://host[:port].
import std::http.{Error, Origin}
assert Origin.parse("http://localhost:5173") == Ok(Origin"http://localhost:5173")
assert Err(Error.InvalidUrl{url: _, reason:}) = Origin.parse("https://a.example?x=1")
assert String.contains(reason, "scheme://host")
Origin.from_fragments
Section titled “Origin.from_fragments”impl Literal for Origin
fn from_fragments(fragments: List<Fragment<String>>) -> Result<Origin, Error>
Origin.to_string
Section titled “Origin.to_string”impl Display for Origin
fn to_string(origin: Origin) -> String
impl Display.to_string
Origin.inspect
Section titled “Origin.inspect”impl Debug for Origin
fn inspect(value: Origin) -> String
impl Debug.inspect
Origin.equal
Section titled “Origin.equal”impl Equatable for Origin
fn equal(a: Origin, b: Origin) -> Bool
impl Equatable.equal
Origin.hash
Section titled “Origin.hash”impl Hashable for Origin
fn hash(value: Origin) -> Int
impl Hashable.hash
struct CrossOrigin
Section titled “struct CrossOrigin”struct CrossOrigin trusted_origins: List<Origin> = [] bypass_patterns: List<Route> = [] deny: Maybe<Handler> = None end
Which cross-origin requests to let through, for
cross_origin_protection, which guards against cross-site request
forgery. A GET, HEAD or OPTIONS always passes.
CrossOrigin.check
Section titled “CrossOrigin.check”fn check(options: CrossOrigin, request: Request) -> Result<Unit, Error>
type function on CrossOrigin
Whether request passes: a safe method passes; then a
Sec-Fetch-Site of same-origin or none, or else an Origin
whose host is the request’s Host, or none at all (not a browser);
and any request from a trusted origin. An empty header counts as
missing. The bypass patterns are cross_origin_protection’s to
apply. The check is Go’s CrossOriginProtection.Check, with its
reasons.
import std::http.{CrossOrigin, Method, Origin, Request}
import std::http::testing
post = testing.request(Method.Post, "/pay")
from = fn site: String -> {
..post,
headers: Headers[("Sec-Fetch-Site", site), ("Origin", "https://evil.example")],
}
assert CrossOrigin.check(CrossOrigin{}, from("same-origin")) == Ok(Unit)
assert CrossOrigin.check(CrossOrigin{}, from("cross-site")) |> Result.is_err()
trusting = CrossOrigin{trusted_origins: [Origin"https://evil.example"]}
assert CrossOrigin.check(trusting, from("cross-site")) == Ok(Unit)
no_origin = {..post, headers: Headers[("Sec-Fetch-Site", ""), ("Origin", "")]}
assert CrossOrigin.check(CrossOrigin{}, no_origin) == Ok(Unit)
CrossOrigin.inspect
Section titled “CrossOrigin.inspect”impl Debug for CrossOrigin
fn inspect(value: CrossOrigin) -> String
impl Debug.inspect
http.cross_origin_protection
Section titled “http.cross_origin_protection”fn cross_origin_protection(handler: Handler, options: CrossOrigin) -> (Request) -> Response
Middleware that sends a request
CrossOrigin.check refuses to options.deny, or returns 403, and
passes one that matches a bypass pattern unchecked. Each Origin was
checked when it was made, so the middleware itself cannot fail.
import std::http.{self, Body, CrossOrigin, Method, Request, Response, Route, Status}
import std::http::testing
pay = fn _: Request -> Response{body: Body.Text("paid")}
app = pay |> http.cross_origin_protection(CrossOrigin{bypass_patterns: ["POST /hooks/"]})
post = fn path: String -> {
..testing.request(Method.Post, path),
headers: Headers[("Sec-Fetch-Site", "cross-site")],
}
assert app(post("/pay")).status == Status.forbidden
assert app(post("/hooks/stripe")).status == Status.ok
http.limit_body
Section titled “http.limit_body”fn limit_body(handler: Handler, max: NonNegativeInt) -> (Request) -> Response
Middleware that limits each request’s body to max bytes
(Request.limit_body), which lowers the server’s max_body or
replaces the form readers’ defaults.
import std::http.{self, Body, Method, Request, Response}
import std::http::testing
upload = http.limit_body(fn r: Request -> Response{body: Body.Text("${r.body_limit}")}, 1_000)
assert Response.text(upload(testing.request(Method.Post, "/upload"))) == Ok("Some(1000)")
http.wrap_routes
Section titled “http.wrap_routes”fn wrap_routes(routes: List<Entry>, wrap: (Handler) -> Handler) -> List<Entry>
routes with each handler wrapped by wrap, for applying middleware
to a group of routes, such as every /admin route, before they join
the others in one Router.
import std::http.{self, Body, Method, Request, Response, Route, Router, Status}
import std::http::testing
require_token = fn handler: Handler ->
fn request: Request ->
if Headers.get(request.headers, "Authorization") == Some("Bearer s3cret") then
ToResponse.to_response(handler(request))
else
Response.error(Status.unauthorized, "unauthorized")
end
end
end
home = fn _: Request -> Response{body: Body.Text("home")}
users = fn _: Request -> Response{body: Body.Text("users")}
admin = [Route.to("GET /admin/users", users)]
routes = [Route.to("GET /", home)] + http.wrap_routes(admin, require_token)
router = Router.new(routes)!
assert Router.serve(router, testing.request(Method.Get, "/")).status == Status.ok
assert Router.serve(router, testing.request(Method.Get, "/admin/users")).status
== Status.unauthorized
struct Cors
Section titled “struct Cors”struct Cors origins: List<Origin> = [] any_origin: Bool = False methods: List<Method> = [Method.Get, Method.Head, Method.Post] allowed_headers: List<String> = [] exposed_headers: List<String> = [] credentials: Bool = False max_age: Maybe<Duration> = None end
Which cross-origin requests cors lets a browser make, and what it
tells the browser about them. The defaults let no origin in.
Cors.inspect
Section titled “Cors.inspect”impl Debug for Cors
fn inspect(value: Cors) -> String
impl Debug.inspect
http.cors
Section titled “http.cors”fn cors(handler: Handler, options: Cors) -> (Request) -> Response
Middleware that handles CORS for the origins options allows, so a
page on another origin, such as a frontend on its own host, can call
the handler from a browser.
A preflight, an OPTIONS request with Origin and
Access-Control-Request-Method, gets 204 No Content here and
never reaches the handler. Any other request reaches it, and its
response gets Access-Control-Allow-Origin with the request’s origin
when that origin is allowed. A request from an origin that is not
allowed gets no CORS headers, so the browser keeps the response from
the page; the handler still runs, as it would for a form posted from
that origin, so pair cors with cross_origin_protection or
credentials checks for requests that change state. Every response
gets Vary: Origin, so a cache does not hand one origin’s response to
another.
import std::http.{self, Body, Cors, Method, Origin, Request, Response, Status}
import std::http::testing
api = fn _: Request -> Response{body: Body.Text("data")}
app =
api
|> http.cors(Cors{
origins: [Origin"https://app.example.com"],
methods: [Method.Get, Method.Post, Method.Delete],
allowed_headers: ["Content-Type", "Authorization"],
})
from = fn method: Method, origin: String -> {
..testing.request(method, "/api/items"),
headers: Headers[("Origin", origin)],
}
ok = app(from(Method.Get, "https://app.example.com"))
assert Headers.get(ok.headers, "Access-Control-Allow-Origin") == Some("https://app.example.com")
assert Headers.get(ok.headers, "Vary") == Some("Origin")
assert Response.text(ok) == Ok("data")
refused = app(from(Method.Get, "https://evil.example"))
assert Headers.get(refused.headers, "Access-Control-Allow-Origin") == None
assert Response.text(refused) == Ok("data")
asking = from(Method.Options, "https://app.example.com")
preflight = app({..asking, headers: Headers.set(.., "Access-Control-Request-Method", "DELETE")})
assert preflight.status == Status.no_content
assert Headers.get(preflight.headers, "Access-Control-Allow-Methods") == Some("GET, POST, DELETE")
assert Headers.get(preflight.headers, "Access-Control-Allow-Headers")
== Some("Content-Type, Authorization")
http.log_requests
Section titled “http.log_requests”fn log_requests(handler: Handler, logger: Logger) -> (Request) -> Response
Middleware that writes one Info record to logger for each
request, after the handler returns: request with the method, the
path, the response’s status, duration_ms, the time the handler
took, and bytes when the body’s length is known without reading it
(a streamed body’s is not). A request that carries X-Request-Id
adds it as request_id, so put request_id after log_requests in a
pipe, outside it, to log the id it sets.
import std::http.{self, Body, Method, Request, Response, Status}
import std::http::testing as http_testing
import std::log
import std::log::testing as log_testing
hello = fn _: Request -> Response{status: Status.created, body: Body.Text("hello")}
got = log_testing.run(fn logger ->
app = hello |> http.log_requests(logger) |> http.request_id()
request = http_testing.request(Method.Post, "/items?x=1")
app({..request, headers: Headers[("X-Request-Id", "req-7")]})
end)
record = List.first(got.records)!
assert record.message == "request"
assert List.contains(record.fields, log.string("method", "POST"))
assert List.contains(record.fields, log.string("path", "/items"))
assert List.contains(record.fields, log.int("status", 201))
assert List.contains(record.fields, log.int("bytes", 5))
assert List.contains(record.fields, log.string("request_id", "req-7"))
struct SecurityHeaders
Section titled “struct SecurityHeaders”struct SecurityHeaders nosniff: Bool = True referrer_policy: Maybe<String> = Some("strict-origin-when-cross-origin") frame_options: Maybe<String> = Some("DENY") strict_transport_security: Maybe<String> = None content_security_policy: Maybe<String> = None end
The headers security_headers adds to each response that does not
set them itself. A None leaves that header out.
SecurityHeaders.inspect
Section titled “SecurityHeaders.inspect”impl Debug for SecurityHeaders
fn inspect(value: SecurityHeaders) -> String
impl Debug.inspect
http.security_headers
Section titled “http.security_headers”fn security_headers(handler: Handler, options: SecurityHeaders = SecurityHeaders{}) -> (Request) -> Response
Middleware that adds the headers options names to each response, as
defaults: a header the handler set is kept. With no options it sends
X-Content-Type-Options: nosniff, Referrer-Policy: strict-origin-when-cross-origin and X-Frame-Options: DENY.
import std::http.{self, Body, Method, Request, Response, SecurityHeaders}
import std::http::testing
page = fn r: Request ->
if r.url.path == "/embed" then
Response{headers: Headers[("X-Frame-Options", "SAMEORIGIN")]}
else
Response{body: Body.Text("page")}
end
end
app = page |> http.security_headers()
plain = app(testing.request(Method.Get, "/"))
assert Headers.get(plain.headers, "X-Content-Type-Options") == Some("nosniff")
assert Headers.get(plain.headers, "Referrer-Policy") == Some("strict-origin-when-cross-origin")
assert Headers.get(plain.headers, "X-Frame-Options") == Some("DENY")
assert Headers.get(plain.headers, "Strict-Transport-Security") == None
assert Headers.get(app(testing.request(Method.Get, "/embed")).headers, "X-Frame-Options")
== Some("SAMEORIGIN")
strict =
page
|> http.security_headers(SecurityHeaders{
strict_transport_security: Some("max-age=63072000"),
content_security_policy: Some("default-src 'self'"),
})
sent = strict(testing.request(Method.Get, "/"))
assert Headers.get(sent.headers, "Strict-Transport-Security") == Some("max-age=63072000")
assert Headers.get(sent.headers, "Content-Security-Policy") == Some("default-src 'self'")
http.request_id
Section titled “http.request_id”fn request_id(handler: Handler, header: String = "X-Request-Id", trust_incoming: Bool = True) -> (Request) -> Response
Middleware that gives each request an id in header, X-Request-Id
unless set, and sends it back on the response. It keeps an id the
request came with when trust_incoming holds and the id is 1 to 128
letters, digits and -_.:+/=; otherwise it makes a random UUID. The
handler reads the id from the request’s headers, and log_requests
logs it when it runs inside request_id, before it in a pipe.
import std::http.{self, Body, Method, Request, Response}
import std::http::testing
echo = fn r: Request -> Response{body: Body.Text(Headers.get(r.headers, "X-Request-Id")!)}
app = echo |> http.request_id()
made = app(testing.request(Method.Get, "/"))
id = Headers.get(made.headers, "X-Request-Id")!
assert String.length(id) == 36
assert Response.text(made) == Ok(id)
given = fn id: String -> {
..testing.request(Method.Get, "/"),
headers: Headers[("X-Request-Id", id)],
}
assert Headers.get(app(given("abc-123")).headers, "X-Request-Id") == Some("abc-123")
assert Headers.get(app(given("bad id\n")).headers, "X-Request-Id") != Some("bad id\n")
untrusting = echo |> http.request_id(trust_incoming: False)
assert Headers.get(untrusting(given("abc-123")).headers, "X-Request-Id") != Some("abc-123")
struct Compress
Section titled “struct Compress”struct Compress min_size: Int = 1024 level: Int = 6 end
How compress compresses.
Compress.inspect
Section titled “Compress.inspect”impl Debug for Compress
fn inspect(value: Compress) -> String
impl Debug.inspect
http.compress
Section titled “http.compress”fn compress(handler: Handler, options: Compress = Compress{}) -> (Request) -> Response
Middleware that compresses each response body with gzip when the
request’s Accept-Encoding takes it (a coding it gives q=0 is
refused), and adds Vary: Accept-Encoding to every response so a
cache keeps the two forms apart. A compressed response gets
Content-Encoding: gzip, loses its Content-Length, and has a strong
ETag made weak (W/"..."), since its bytes are not the ones the tag
names; If-None-Match still matches it.
A response is sent as it is when it already has a Content-Encoding
(a precompressed file serve_embedded sends), has no body (1xx, 204,
304, a HEAD), is a range (206), says Cache-Control: no-transform,
has a body known to be shorter than options.min_size, or has a
content type that is compressed already: images other than SVG, audio,
video, archives such as zip and gzip, and woff fonts. A body of
bytes with no Content-Type gets the one its bytes are sniffed as
first; a streamed body with none is sent as it is.
A Body.Stream is compressed as it is read, and a Body.Produce as
it writes, each Writer.flush passing what it wrote so far to the
client, so server-sent events still arrive one by one. Go’s standard
library has no brotli encoder, so compress writes only gzip; serve
.br files precompressed (serve_embedded).
import std::http.{self, Body, Method, Request, Response, Status}
import std::http::testing
page = String.repeat("<p>hello</p>", 200)
app = (fn _: Request -> Response{body: Body.Text(page)}) |> http.compress()
asking = fn accept: String ->
r = testing.request(Method.Get, "/")
{..r, headers: Headers[("Accept-Encoding", accept)]}
end
zipped = app(asking("gzip, br"))
assert Headers.get(zipped.headers, "Content-Encoding") == Some("gzip")
assert Headers.get(zipped.headers, "Content-Type") == Some("text/plain; charset=utf-8")
assert Headers.get(zipped.headers, "Vary") == Some("Accept-Encoding")
assert Bytes.length(Response.bytes(zipped)!) < 100
assert testing.decompressed(zipped) == Ok(String.to_bytes(page))
plain = app(asking("gzip;q=0, identity"))
assert Headers.get(plain.headers, "Content-Encoding") == None
assert Headers.get(plain.headers, "Vary") == Some("Accept-Encoding")
assert Response.text(plain) == Ok(page)
small = (fn _: Request -> Response{body: Body.Text("hi")}) |> http.compress()
assert Headers.get(small(asking("gzip")).headers, "Content-Encoding") == None
http.basic_auth
Section titled “http.basic_auth”fn basic_auth(handler: Handler, realm: String, check: (String, String) -> Bool) -> (Request) -> Response
Middleware that lets a request through to handler only with a
Basic Authorization header whose user and password check
accepts. Any other request gets 401 Unauthorized with
WWW-Authenticate: Basic realm="<realm>", charset="UTF-8", which has
a browser ask for them. The handler reads the user with
Request.basic_auth. Send it only over HTTPS: the password crosses in
every request, encoded but not encrypted.
Write check with hash.equal_in_constant_time, never ==, which
returns at the first byte that differs and so tells an attacker by its
timing how much of a guess was right. Comparing SHA-256 digests keeps
the lengths equal, so the time depends on neither, and checking both
before combining them keeps a right user from showing either.
import std::hash
import std::http.{self, Body, Method, Request, Response, Status}
import std::http::testing
same = fn given: String, expected: String ->
hash.equal_in_constant_time(
hash.sha256(String.to_bytes(given)),
hash.sha256(String.to_bytes(expected)),
)
end
admin_only = fn user: String, password: String ->
user_ok = same(user, "admin")
password_ok = same(password, "s3cret")
user_ok and password_ok
end
hello = fn r: Request -> Response{body: Body.Text("hello ${Request.basic_auth(r)!.first}")}
app = hello |> http.basic_auth("admin", admin_only)
visit = testing.request(Method.Get, "/admin")
refused = app(visit)
assert refused.status == Status.unauthorized
assert Headers.get(refused.headers, "WWW-Authenticate")
== Some("Basic realm=\"admin\", charset=\"UTF-8\"")
assert app(Request.with_basic_auth(visit, "admin", "guess")).status == Status.unauthorized
assert Response.text(app(Request.with_basic_auth(visit, "admin", "s3cret"))) == Ok("hello admin")
http.method_override
Section titled “http.method_override”fn method_override(handler: Handler) -> (Request) -> Response
Middleware that lets an HTML form, which can send only GET and
POST, stand for a PUT, PATCH or DELETE: a POST whose
URL-encoded body has a _method field naming one of those three, in
any case, reaches handler as that method, so a router’s
DELETE /posts/{id} route takes it. Any other request, and any other
_method, passes as it came. The form is read up to the request’s
body_limit, or 10 MB, and the handler can read it again; past the
limit the request gets 413.
Wrap the router, so the method is changed before it routes, and put
limit_body outside it (after it in a pipe) for its limit to hold
here. The X-HTTP-Method-Override header is not read: a page on
another origin could set it on a request a browser lets through.
import std::http.{self, Body, Method, Request, Response, Route, Router}
import std::http::testing
router = Router.new([
Route.to("POST /posts", fn _ -> Response{body: Body.Text("created")}),
Route.to_with("PATCH /posts/{id}", fn r, _ -> Response{
body: Body.Text("titled ${Request.form_value(r, "title")!}"),
}),
Route.to_with("DELETE /posts/{id}", fn _, _ -> Response{body: Body.Text("deleted")}),
])!
app = Router.handler(router) |> http.method_override()
form = fn target: String, fields: List<(String, String)> ->
testing.form_request(Method.Post, target, fields)
end
assert Response.text(app(form("/posts/7", [("_method", "delete")]))) == Ok("deleted")
assert Response.text(app(form("/posts/7", [("_method", "PATCH"), ("title", "Hi")])))
== Ok("titled Hi")
assert Response.text(app(form("/posts", [("_method", "CONNECT")]))) == Ok("created")
http.serve_file
Section titled “http.serve_file”fn serve_file(request: Request, file: String) -> Response
The file at path as the response to request, with ranges and
conditional requests (Response.content). A directory
is redirected to its path with a trailing slash, then served with its
index.html or a listing of its entries; a request for .../index.html
is redirected to ./.
When nothing is at file, the request’s path ends in no / and file
does not end in .html, the page file.html is served in its place, as
static hosts do: /about gets about.html, which is the
file Next’s and SvelteKit’s static exports write for each route. The
order is the file, then a directory, then the page. A request for
/about.html is served that file as named, not redirected. Anything
else missing is a 404, and a file that cannot be read a 403 or 500.
Files come through std::fs, so std::fs::testing.run and fs.within apply.
import std::fs::testing as fs_testing
import std::fs::testing.Sandbox
import std::http.{Method, Response, Status}
import std::http::testing as http_testing
get = fn target: String, file: String -> serve_file(http_testing.request(Method.Get, target), file)
site = {"site/about.html" => "<p>about</p>", "site/blog/index.html" => "<p>blog</p>"}
ran = fs_testing.run(Sandbox{files: site}, fn ->
(
get("/about", "site/about"),
get("/about.html", "site/about.html"),
get("/blog", "site/blog"),
get("/missing", "site/missing"),
)
end)
(about, named, blog, missing) = ran.value
assert Response.text(about) == Ok("<p>about</p>")
assert Headers.get(about.headers, "Content-Type") == Some("text/html; charset=utf-8")
assert Response.text(named) == Ok("<p>about</p>")
assert blog.status == Status.moved_permanently
assert missing.status == Status.not_found
http.file_server
Section titled “http.file_server”fn file_server(root: String, single_page: Bool = False) -> (Request) -> Response
A handler that serves each request the file under root its
cleaned path names (serve_file).
A path that names no file or directory is tried with .html appended,
so /about gets about.html (serve_file).
With single_page, a request for a page route that names no file,
directory or .html page gets root’s index.html,
status 200, so a single-page app whose client-side router owns
/settings loads at that URL (is_page_route). A file that exists is
served whatever its name, and a request for a missing asset is still a
404.
import std::fs::testing as fs_testing
import std::fs::testing.Sandbox
import std::http.{Method, Response, Status}
import std::http::testing as http_testing
site = file_server("site", single_page: True)
page = http_testing.request(Method.Get, "/settings")
page = {..page, headers: Headers.set(.., "Accept", "text/html")}
ran = fs_testing.run(Sandbox{files: {"site/index.html" => "<div id=root></div>"}}, fn ->
(site(page), site(http_testing.request(Method.Get, "/app.js")))
end)
(shell, script) = ran.value
assert Response.text(shell) == Ok("<div id=root></div>")
assert script.status == Status.not_found
http.serve_embedded
Section titled “http.serve_embedded”fn serve_embedded(request: Request, files: Files, file: String, immutable: List<String> = []) -> Response
serve_file from files a program embeds (std::embed): the file at
file in files as the response to request, with its Content-Type
from its name, ranges and conditional requests. A directory is
redirected to its path with a trailing slash, then served with its
index.html; one with no index.html is a 404, since an embedded
tree is not listed. A request for .../index.html is redirected to
./. When nothing is at file, the request’s path ends in no / and
file does not end in .html, the page file.html is served in its
place, as serve_file serves it: the file, then a directory, then the
page. Anything else missing is a 404.
The file’s SHA-256, which the compiler took when it read the file, is
its strong ETag, so a request whose If-None-Match names it is a 304
with no body. A file whose path in files matches one of the
immutable patterns (std::path’s matches: assets/** for every
file under Vite’s assets, *-*.js for hashed scripts at the root) is
sent with Cache-Control: public, max-age=31536000, immutable. Match
only files that have their contents’ hash in their names, as a bundler
writes them, since a browser keeps such a file for a year without
asking again. A pattern with no wildcard (*, ? or [) names a
file or a directory, and a directory covers every file under it, as in
an embed pattern: assets is assets/**. Any other
file is sent with Cache-Control: no-cache, which has a browser ask
each time and get the 304 while the file is unchanged.
A file that has a precompressed sibling, file.br or file.gz as
Vite’s and webpack’s compression plugins write them, is sent as that
sibling when the request’s Accept-Encoding takes its coding (br
first), with Content-Encoding, the original name’s Content-Type,
and the sibling’s own ETag. Every response for such a file carries
Vary: Accept-Encoding. Nothing is compressed while the program runs.
import std::http.{Method, Response, Status}
import std::http::testing
files = Files.from_bytes([
("index.html", String.to_bytes("<p>home</p>")),
("assets/app-3f9a1b2c.js", String.to_bytes("go()")),
("assets/app-3f9a1b2c.js.gz", String.to_bytes("zipped")),
])
get = testing.request(Method.Get, "/assets/app-3f9a1b2c.js")
js = serve_embedded(get, files, "assets/app-3f9a1b2c.js", immutable: ["assets/**"])
assert Headers.get(js.headers, "Cache-Control") == Some("public, max-age=31536000, immutable")
assert Headers.get(js.headers, "Content-Type") == Some("text/javascript; charset=utf-8")
assert Headers.get(js.headers, "Vary") == Some("Accept-Encoding")
assert Response.text(js) == Ok("go()")
gzip = {..get, headers: Headers.set(.., "Accept-Encoding", "gzip, deflate")}
zipped = serve_embedded(gzip, files, "assets/app-3f9a1b2c.js")
assert Headers.get(zipped.headers, "Content-Encoding") == Some("gzip")
assert Headers.get(zipped.headers, "Content-Type") == Some("text/javascript; charset=utf-8")
assert Response.text(zipped) == Ok("zipped")
home = serve_embedded(testing.request(Method.Get, "/"), files, ".")
etag = Headers.get(home.headers, "ETag")!
assert Headers.get(home.headers, "Cache-Control") == Some("no-cache")
again = testing.request(Method.Get, "/")
again = {..again, headers: Headers.set(.., "If-None-Match", etag)}
assert serve_embedded(again, files, ".").status == Status.not_modified
pages = Files.from_bytes([
("about.html", String.to_bytes("<p>about</p>")),
("about.html.br", String.to_bytes("squeezed")),
])
about = serve_embedded(testing.request(Method.Get, "/about"), pages, "about")
assert Response.text(about) == Ok("<p>about</p>")
assert Headers.get(about.headers, "Content-Type") == Some("text/html; charset=utf-8")
assert Headers.get(about.headers, "Vary") == Some("Accept-Encoding")
brotli = testing.request(Method.Get, "/about")
brotli = {..brotli, headers: Headers.set(.., "Accept-Encoding", "br")}
squeezed = serve_embedded(brotli, pages, "about")
assert Headers.get(squeezed.headers, "Content-Encoding") == Some("br")
assert Response.text(squeezed) == Ok("squeezed")
slashed = serve_embedded(testing.request(Method.Get, "/about/"), pages, "about")
assert slashed.status == Status.not_found
http.file_server_embedded
Section titled “http.file_server_embedded”fn file_server_embedded(files: Files, single_page: Bool = False, immutable: List<String> = []) -> (Request) -> Response
file_server over files a program embeds (std::embed): a handler that
serves each request the file its cleaned path names in files
(serve_embedded, which immutable is passed to). A path is cleaned
before it is looked up, so no request reaches outside the tree. Serve
a folder’s files at the root with Files.sub:
embed site `static` fn static_files() -> (Request) -> Response http.file_server_embedded(Files.sub(site, "static")!) end
A path that names no file or directory is tried with .html appended,
so a static export with a page per route, about.html for /about,
is served as written. With single_page, a request for a page route
that names no file, directory or .html page gets the root
index.html, status 200, as file_server serves it. A Vite build’s
dist is served so:
embed web `web/dist` fn frontend() -> (Request) -> Response http.file_server_embedded( Files.sub(web, "web/dist")!, single_page: True, immutable: ["assets/**"], ) end
import std::http.{Method, Response, Status}
import std::http::testing
app = file_server_embedded(
Files.from_bytes([
("index.html", String.to_bytes("<div id=root></div>")),
("assets/app-3f9a1b2c.js", String.to_bytes("go()")),
]),
single_page: True,
immutable: ["assets/**"],
)
visit = fn target: String ->
r = testing.request(Method.Get, target)
{..r, headers: Headers.set(.., "Accept", "text/html,*/*;q=0.8")}
end
assert Response.text(app(visit("/settings/profile"))) == Ok("<div id=root></div>")
exported = file_server_embedded(
Files.from_bytes([
("index.html", String.to_bytes("<p>home</p>")),
("about.html", String.to_bytes("<p>about</p>")),
]),
single_page: True,
)
assert Response.text(exported(visit("/about"))) == Ok("<p>about</p>")
assert Response.text(exported(visit("/contact"))) == Ok("<p>home</p>")
assert Response.text(app(visit("/users/jane.doe"))) == Ok("<div id=root></div>")
missing = testing.request(Method.Get, "/assets/gone-0a1b2c3d.js")
missing = {..missing, headers: Headers.set(.., "Accept", "*/*")}
assert app(missing).status == Status.not_found
http.is_page_route
Section titled “http.is_page_route”fn is_page_route(request: Request) -> Bool
Whether request asks for a page a single-page app’s client-side
router handles, which file_server and file_server_embedded respond to
with index.html under single_page when no file matches the path: a
GET or HEAD from a client that takes HTML, whose Accept names
text/html. A browser sends that only when it navigates to a page,
never for a script, stylesheet, image or fetch, so the path may hold
a dot (/users/jane.doe) and a missing /assets/app.js stays a 404.
import std::http.Method
import std::http::testing
asked = fn method: Method, target: String, accept: String ->
r = testing.request(method, target)
{..r, headers: Headers.set(.., "Accept", accept)}
end
html = "text/html,application/xhtml+xml,*/*;q=0.8"
assert is_page_route(asked(Method.Get, "/settings/profile", html))
assert is_page_route(asked(Method.Get, "/users/jane.doe", html))
refute is_page_route(asked(Method.Get, "/assets/app.js", "*/*"))
refute is_page_route(asked(Method.Post, "/settings", html))
refute is_page_route(asked(Method.Get, "/api/users", "application/json"))
refute is_page_route(asked(Method.Get, "/api/users", "*/*"))
http.detect_content_type
Section titled “http.detect_content_type”fn detect_content_type(data: Bytes) -> String
The media type of data, guessed from at most its first 512 bytes by
the WHATWG MIME sniffing rules, as Go’s DetectContentType guesses it:
text/plain; charset=utf-8 for text, application/octet-stream when
nothing matches.
assert http.detect_content_type(String.to_bytes("<html>")) == "text/html; charset=utf-8"
http.format_time
Section titled “http.format_time”fn format_time(at: Instant) -> String
at as HTTP headers write dates, in GMT:
Mon, 02 Jan 2006 15:04:05 GMT.
import std::instant.Instant
assert http.format_time(Instant.from_seconds(0)) == "Thu, 01 Jan 1970 00:00:00 GMT"
http.parse_time
Section titled “http.parse_time”fn parse_time(text: String) -> Result<Instant, Error>
A date in any of the three formats HTTP allows: the one format_time
writes, RFC 850’s and ANSI C’s asctime, of any year, such as the
Fri, 31 Dec 9999 23:59:59 GMT servers send for “never”. Text in none
of them is Error.Protocol.
enum SameSite
Section titled “enum SameSite”enum SameSite Unset Default Lax Strict None end
A cookie’s SameSite attribute.
Variants
-
UnsetNo attribute.
-
DefaultSameSitewith no value. -
NoneSameSite=None, which browsers accept only withsecure.
SameSite.inspect
Section titled “SameSite.inspect”impl Debug for SameSite
fn inspect(value: SameSite) -> String
impl Debug.inspect
SameSite.equal
Section titled “SameSite.equal”impl Equatable for SameSite
fn equal(a: SameSite, b: SameSite) -> Bool
impl Equatable.equal
enum MaxAge
Section titled “enum MaxAge”enum MaxAge Unset DeleteNow Seconds Int end
A cookie’s Max-Age, in place of Go’s 0 and negative codes.
Variants
-
UnsetNo
Max-Ageattribute. -
DeleteNowMax-Age=0: delete the cookie now.
MaxAge.inspect
Section titled “MaxAge.inspect”impl Debug for MaxAge
fn inspect(value: MaxAge) -> String
impl Debug.inspect
MaxAge.equal
Section titled “MaxAge.equal”impl Equatable for MaxAge
fn equal(a: MaxAge, b: MaxAge) -> Bool
impl Equatable.equal
struct Cookie
Section titled “struct Cookie”struct Cookie name: String value: String quoted: Bool = False path: Maybe<String> = None domain: Maybe<String> = None expires: Maybe<Instant> = None raw_expires: Maybe<String> = None max_age: MaxAge = MaxAge.Unset secure: Bool = False http_only: Bool = False same_site: SameSite = SameSite.Unset partitioned: Bool = False raw: Maybe<String> = None unparsed: List<String> = [] end
An HTTP cookie: what a Set-Cookie header sets or a Cookie header
sends. raw_expires, raw and unparsed are set by parsing only. A
parsed expiry of any year (the year 9999 is common for “never”) is
expires; one Go cannot parse leaves expires None and is kept in
raw_expires.
Cookie.parse_header
Section titled “Cookie.parse_header”fn parse_header(text: String) -> Result<List<Cookie>, Error>
type function on Cookie
The cookies of a Cookie header’s value, as Go’s ParseCookie.
import std::http.Cookie
names = Cookie.parse_header("a=1; b=2")! |> Iter.map(fn c -> c.name) |> Iter.to_list()
assert names == ["a", "b"]
Cookie.parse_set_cookie
Section titled “Cookie.parse_set_cookie”fn parse_set_cookie(text: String) -> Result<Cookie, Error>
type function on Cookie
The cookie of a Set-Cookie header’s value, as Go’s
ParseSetCookie.
import std::http.{Cookie, MaxAge}
c = Cookie.parse_set_cookie("id=7; Path=/; Max-Age=60; Secure")!
assert c.path == Some("/")
assert c.max_age == MaxAge.Seconds(60)
assert c.secure
Cookie.validate
Section titled “Cookie.validate”fn validate(cookie: Cookie) -> Result<Unit, Error>
type function on Cookie
Ok when the cookie can be written in a Set-Cookie header: its
name is a token, and its value, path, domain and expiry hold only
what the header allows, and a partitioned cookie is secure.
Otherwise Error.Protocol says what is wrong.
Cookie.to_string
Section titled “Cookie.to_string”impl Display for Cookie
fn to_string(cookie: Cookie) -> String
impl Display.to_string
Cookie.inspect
Section titled “Cookie.inspect”impl Debug for Cookie
fn inspect(value: Cookie) -> String
impl Debug.inspect
Cookie.equal
Section titled “Cookie.equal”impl Equatable for Cookie
fn equal(a: Cookie, b: Cookie) -> Bool
impl Equatable.equal
struct CookieJar
Section titled “struct CookieJar”struct CookieJar handle: http_host.Jar end
Where a client keeps cookies: Go’s net/http/cookiejar, with no public
suffix list. Give it to a client with ClientOptions.cookies.
CookieJar.new
Section titled “CookieJar.new”fn new() -> CookieJar
type function on CookieJar
An empty jar.
CookieJar.cookies
Section titled “CookieJar.cookies”fn cookies(jar: CookieJar, url: Url) -> List<Cookie>
type function on CookieJar
The cookies the jar would send with a request to url.
import std::http.{Cookie, CookieJar}
import std::url.Url
jar = CookieJar.new()
CookieJar.set_cookies(jar, Url"https://example.com/", [Cookie{name: "a", value: "1"}])
sent =
CookieJar.cookies(jar, Url"https://example.com/x") |> Iter.map(fn c -> c.name) |> Iter.to_list()
assert sent == ["a"]
CookieJar.set_cookies
Section titled “CookieJar.set_cookies”fn set_cookies(jar: CookieJar, url: Url, cookies: List<Cookie>) -> Unit
type function on CookieJar
Stores cookies, as received in a response from url.
CookieJar.inspect
Section titled “CookieJar.inspect”impl Debug for CookieJar
fn inspect(value: CookieJar) -> String
impl Debug.inspect
enum ConnState
Section titled “enum ConnState”enum ConnState New Active Idle Hijacked Closed end
What a server’s connection is doing: Go’s ConnState.
ConnState.to_string
Section titled “ConnState.to_string”impl Display for ConnState
fn to_string(state: ConnState) -> String
impl Display.to_string
import std::http.ConnState
assert "${ConnState.Idle}" == "idle"
ConnState.inspect
Section titled “ConnState.inspect”impl Debug for ConnState
fn inspect(value: ConnState) -> String
impl Debug.inspect
ConnState.equal
Section titled “ConnState.equal”impl Equatable for ConnState
fn equal(a: ConnState, b: ConnState) -> Bool
impl Equatable.equal
http.serve_here
Section titled “http.serve_here”fn serve_here(listener: Listener, handler: Handler) -> Unit
Serves each request listener receives with handler, each as a task
of a concurrent block of its own, and returns once the listener shuts
down and every request it took is served. For a server with no
supervisor, as in a test; a program’s server uses serve and a
supervisor, whose max_running bounds the requests in flight.
struct ProxyRequest
Section titled “struct ProxyRequest”struct ProxyRequest incoming: Request outgoing: Request end
The request a reverse proxy received and the request it will send, for
its rewrite function: Go’s ProxyRequest.
ProxyRequest.set_url
Section titled “ProxyRequest.set_url”fn set_url(proxy: ProxyRequest, target: Url) -> ProxyRequest
type function on ProxyRequest
Sends the outgoing request to target: its scheme and host, its
path joined before the request’s, its query before the request’s.
The Host sent is the target’s. Go’s SetURL.
ProxyRequest.set_x_forwarded
Section titled “ProxyRequest.set_x_forwarded”fn set_x_forwarded(proxy: ProxyRequest) -> ProxyRequest
type function on ProxyRequest
Sets X-Forwarded-For to the client’s address (added to what an
earlier proxy set), X-Forwarded-Host to the host it asked for and
X-Forwarded-Proto to http or https. Go’s SetXForwarded.
ProxyRequest.inspect
Section titled “ProxyRequest.inspect”impl Debug for ProxyRequest
fn inspect(value: ProxyRequest) -> String
impl Debug.inspect
struct ReverseProxy
Section titled “struct ReverseProxy”struct ReverseProxy rewrite: (ProxyRequest) -> ProxyRequest client: Client = default_client() modify_response: Maybe<(Response) -> Result<Response, Error>> = None on_error: Maybe<(Request, Error) -> Response> = None flush_interval: Maybe<Duration> = None on_error_log: Maybe<(String) -> Unit> = None end
How a reverse proxy forwards: Go’s ReverseProxy. rewrite turns each
request it receives into the one it sends.
ReverseProxy.to
Section titled “ReverseProxy.to”fn to(target: Url) -> ReverseProxy
type function on ReverseProxy
A proxy to one host: each request goes to target, its path joined
after the target’s, with X-Forwarded-* set. Go’s
NewSingleHostReverseProxy.
ReverseProxy.inspect
Section titled “ReverseProxy.inspect”impl Debug for ReverseProxy
fn inspect(value: ReverseProxy) -> String
impl Debug.inspect
http.reverse_proxy
Section titled “http.reverse_proxy”fn reverse_proxy(options: ReverseProxy) -> (Request) -> Response
A handler that forwards each request as options says and responds
with the response, its connection headers removed: Go’s
ReverseProxy.ServeHTTP. The response streams to the client as it
arrives, flushed as flush_interval says.
struct Tracer
Section titled “struct Tracer”struct Tracer handle: http_host.Handle end
Records what Go’s client reports while it sends the requests that name
it in Request.trace: Go’s httptrace.ClientTrace, as data rather than
callbacks.
Tracer.new
Section titled “Tracer.new”fn new() -> Tracer
type function on Tracer
A tracer that has recorded nothing. A request names it in its
trace field.
Tracer.events
Section titled “Tracer.events”fn events(tracer: Tracer) -> List<TraceEvent>
type function on Tracer
What happened so far, in order.
Tracer.inspect
Section titled “Tracer.inspect”impl Debug for Tracer
fn inspect(value: Tracer) -> String
impl Debug.inspect
enum TraceEvent
Section titled “enum TraceEvent”enum TraceEvent GetConnection { address: String } GotConnection { reused: Bool, was_idle: Bool, idle_time: Duration } PutIdleConnection { error: Maybe<String> } FirstResponseByte Continue Informational { status: Status, headers: Headers } DnsStart { host: String } DnsDone { addresses: List<String>, error: Maybe<String>, coalesced: Bool } ConnectStart { network: String, address: String } ConnectDone { network: String, address: String, error: Maybe<String> } TlsStart TlsDone { state: tls.ConnectionState, error: Maybe<String> } WroteHeader { name: String, values: List<String> } WroteHeaders WaitContinue WroteRequest { error: Maybe<String> } end
One thing a client did while it sent a request: Go’s ClientTrace
hooks, each with its info’s fields.
Variants
-
GetConnectionIt looked for a connection to
address(host:port). -
GotConnectionIt got one: reused from an earlier request, idle for
idle_time. -
PutIdleConnectionIt returned the connection to the idle pool, or failed to.
-
ContinueThe server sent
100 Continue. -
InformationalThe server sent a 1xx status before the final one.
-
WroteHeaderIt wrote one header field.
-
WaitContinueIt waits for
100 Continuebefore sending the body.
TraceEvent.inspect
Section titled “TraceEvent.inspect”impl Debug for TraceEvent
fn inspect(value: TraceEvent) -> String
impl Debug.inspect
http.chunked_reader
Section titled “http.chunked_reader”fn chunked_reader(r: Reader) -> Reader
A reader of the chunked transfer coding over r, which ends at the
last, empty chunk: httputil’s NewChunkedReader.
import std::http
import std::io.Reader
r = http.chunked_reader(Reader.from_text("2\r\nhi\r\n0\r\n\r\n"))
assert Reader.read_all_text(r) == Ok("hi")
http.chunked_writer
Section titled “http.chunked_writer”fn chunked_writer(w: Writer) -> Writer
A writer that sends what it is given to w in the chunked transfer
coding; closing it writes the last, empty chunk and leaves w open:
httputil’s NewChunkedWriter.
struct Part
Section titled “struct Part”struct Part headers: Headers body: Reader handle: http_host.Handle end
One part of a multipart body, read as it arrives: Go’s
multipart.Part. Reading the next part ends this one.
Part.form_name
Section titled “Part.form_name”fn form_name(part: Part) -> Maybe<String>
type function on Part
The name of its form-data Content-Disposition, if any.
Part.file_name
Section titled “Part.file_name”fn file_name(part: Part) -> Maybe<String>
type function on Part
The filename of its Content-Disposition, if any.
Part.inspect
Section titled “Part.inspect”impl Debug for Part
fn inspect(value: Part) -> String
impl Debug.inspect
http.multipart_parts
Section titled “http.multipart_parts”fn multipart_parts(r: Reader, boundary: String) -> Iter<Result<Part, Error>>
The parts of the multipart body r holds, separated by boundary, each
read as the iteration reaches it: Go’s multipart.NewReader and its
NextPart, which decodes quoted-printable parts. An Err ends it.
import std::http
import std::http.Part
import std::io.Reader
body = "--b\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\none\r\n--b--\r\n"
names =
http.multipart_parts(Reader.from_text(body), "b")
|> Iter.map(fn p -> p |> Result.map(Part.form_name))
|> Iter.to_list()
assert names == [Ok(Some("a"))]
http.multipart_raw_parts
Section titled “http.multipart_raw_parts”fn multipart_raw_parts(r: Reader, boundary: String) -> Iter<Result<Part, Error>>
multipart_parts with each part as it was sent, not decoded: Go’s
NextRawPart.
http.read_multipart_form
Section titled “http.read_multipart_form”fn read_multipart_form(r: Reader, boundary: String, max: Int = 33_554_432) -> Result<MultipartForm, Error>
The multipart form r holds, read whole: Go’s Reader.ReadForm. A
form larger than max bytes is Error.BodyTooLarge; no more than one
byte past max is read.
http.write_multipart
Section titled “http.write_multipart”fn write_multipart(w: Writer, boundary: String, parts: List<FormPart>) -> Result<Unit, Error>
Writes parts to w as a multipart body separated by boundary, each
as it comes, then the closing boundary: Go’s multipart.Writer. The
body’s Content-Type is multipart/form-data; boundary= and the
boundary.