Http.Response
type Http.Response = { status: int, headers: Map[string, string], bytes: Bytes }Http.Response is the response to a client request. Its body is held once, as received, in bytes; Http.text decodes it. The headers hold one string per name, a repeated header joined with ", ", in order of name, each name in canonical form, as Go's CanonicalHeaderKey gives it: "content-type" is read as headers["Content-Type"].
Details
- Every status is a response: a 404 or a 500 comes back as
Okwith thatstatus. The call isErronly when no response arrives. - No redirect is followed. A 3xx comes back as it is, with its
Locationheader. - The whole body is read before the call returns.
headersis in order of name, and each name is in canonical form, as Go'sCanonicalHeaderKeygives it: a header sent ascontent-typeis read asheaders["Content-Type"].- The body is held once, in
bytes. Http.text decodes it on every call, so a program that needs the text twice binds it once.
Basic examples
Get a page from a local server with Http.get and read its status and its body as text:
func handle(req: Http.Request): Http.Reply {
Http.Reply{ status: 200, headers: Map{ "Content-Type": "text/plain" }, body: "hello" }
}
let server = try Net.listen("127.0.0.1:0")
go { _ = Http.serve(server, handle) }
let res = try Http.get("http://${Net.address(server)}/hello")
println(res.status)
println(res.text())200
helloThe examples below ask a server like this one, at url, which answers /hello with text, /user with JSON, /blob with three bytes that are not UTF-8, /old with a redirect to /hello, and any other path with a 404.
Look up a header by name:
let res = try Http.get("${url}/hello")
println(res.headers["Content-Type"])
println(res.headers["X-Missing"] ?? "none")text/plain
nonebytes holds the body as it arrived:
let res = try Http.get("${url}/hello")
println(res.bytes)
println(res.bytes.length())Bytes(68 65 6c 6c 6f)
5Scope
A 404 is a response like any other, with its status and its body:
let res = try Http.get("${url}/nope")
println(res.status)
println(res.text())404
no /nopeA redirect is not followed. The response is the redirect itself, and Location names the next page:
let res = try Http.get("${url}/old")
println(res.status)
println(res.headers["Location"])
println(res.text().isEmpty())301
/hello
trueA HEAD request gets the headers and an empty body:
let res = try Http.request("HEAD", "${url}/hello")
println(res.headers["Content-Length"])
println(res.text().isEmpty())
println(res.bytes.length())5
true
0A body that is not UTF-8 is exact in bytes. In text(), the bad byte becomes U+FFFD:
let res = try Http.get("${url}/blob")
println(res.bytes)
println(res.text() == "\u{FFFD}\u{0}h")Bytes(ff 00 68)
trueA header sent twice is one entry, its values joined with ", ". This server writes its response by hand over Net to send Vary twice:
let server = try Net.listen("127.0.0.1:0")
go {
let conn = Result.unwrap(Net.accept(server))
defer { conn.close() }
while true {
let line = Result.unwrap(conn.readLine())
if line == null || line.trim().isEmpty() { break }
}
let reply = "HTTP/1.1 200 OK\r\nVary: Accept\r\nVary: Cookie\r\nContent-Length: 2\r\n\r\nok"
Result.unwrap(conn.writeText(reply))
}
let res = try Http.get("http://${Net.address(server)}/")
println(res.headers["Vary"])Accept, CookieHttp.Response is a record type, so a literal builds one, for example to test a function that takes a response without a server:
func describe(res: Http.Response): string {
if res.status >= 400 { return "error ${res.status}: ${res.text()}" }
"${res.bytes.length()} bytes of ${res.headers["Content-Type"] ?? "unknown type"}"
}
let ok = Http.Response{
status: 200,
headers: Map{ "Content-Type": "text/html" },
bytes: "<p>hi</p>".toBytes(),
}
let missing = Http.Response{ status: 404, headers: Map{}, bytes: "gone".toBytes() }
println(describe(ok))
println(describe(missing))9 bytes of text/html
error 404: goneApplications
Turn a status that is not 2xx into an Err, so try stops on it:
func fetchText(address: string): Result[string, Error] {
let res = try Http.get(address)
if res.status < 200 || res.status > 299 {
return Result.fail("GET ${address}: status ${res.status}")
}
Result.ok(res.text())
}
println(fetchText("${url}/hello"))
println(fetchText("${url}/nope") is Err)Ok{ value: "hello" }
trueParse a JSON body with Json.parse:
let res = try Http.get("${url}/user")
let user = try Json.parse(res.text())
if user is Map {
println(user["name"])
}AnnFollow a redirect by asking for the page that Location names:
func getFollowing(base: string, path: string): Result[Http.Response, Error] {
let res = try Http.get("${base}${path}")
let location = res.headers["Location"]
if res.status < 300 || res.status > 399 || location == null {
return Result.ok(res)
}
Http.get("${base}${location}")
}
let res = try getFollowing(url, "/old")
println(res.status)
println(res.text())200
helloCheck a download against a known digest, computed over bytes, the body as it was sent:
let res = try Http.get("${url}/blob")
let digest = Crypto.sha256(res.bytes) | Encoding.toHex()
println(digest == "12368291592ee4f015324a36b16c50a003ebe99204d222046f617b271515d290")trueProperties and relations
text() is bytes decoded as text:
for path in ["/hello", "/user", "/blob", "/nope"] {
let res = try Http.get("${url}${path}")
assert(res.text() == String.fromBytesLossy(res.bytes))
}Possible issues
try does not stop on an error status, since every response is Ok. Check status:
let res = try Http.get("${url}/nope")
println("still here, status ${res.status}")still here, status 404text() loses bytes that are not UTF-8, so turning it back into Bytes does not give the body that was sent. Use bytes for binary data:
let res = try Http.get("${url}/blob")
println(res.text().toBytes() == res.bytes)
println(res.text().toBytes())false
Bytes(ef bf bd 00 68)See also
Http.get · Http.post · Http.request · Http.Request · Http.Reply · Http.serve · String.fromBytesLossy · Json.parse
