Http
Http holds an HTTP client and server. A request reads the whole response, and a server calls a handler for each request on a goroutine of its own.
Http is a client and a server in four functions. Http.request sends one request and reads the whole response, and Http.get and Http.post are Http.request with the method filled in. Http.serve answers requests on a Net.Listener by calling a handler, a function from an Http.Request to an Http.Reply. Everything else is plain data: the client gets an Http.Response record back, and a handler returns a record.
Details
- A response of any status is
Ok: a 404 or a 500 comes back with itsstatus, and the program checks it.Errmeans no response arrived: a malformed URL, no connection, the timeout, or the context. - No redirect is followed. A 3xx comes back as it is, with its
Locationheader. - A body is read whole, by the client and by the server, and is held once, as received, in
bytes. Http.text decodes it. - Headers hold one string per name, and a repeated header is joined with
,. Two names that differ only in case name one header: the client isErron them, and a reply with them panics in the handler's goroutine. - A client call without
timeoutorctxhas no deadline and waits as long as the server takes. Http.serve runs until itsctxis done, so run it on a goroutine to talk to it from the same program.
Basic examples
Start a server on a free local port with Http.serve, and ask it for a page with Http.get:
func hello(req: Http.Request): Http.Reply {
Http.Reply{ status: 200, headers: Map{}, body: "hello from ${req.path}" }
}
let listener = try Net.listen("127.0.0.1:0")
let stop = Context.new()
defer { stop.cancel() }
go { _ = Http.serve(listener, hello, stop) }
let res = try Http.get("http://${listener.address()}/docs")
println(res.status)
println(res.text())200
hello from /docsThe other examples on this page ask a server like that one, at base. It answers /hello with text, /user with JSON, /old with a redirect to /hello, /slow after a second, /lang with the Accept-Language header it got, /echo with the method and body it got, and any other path with a 404.
Send a body with Http.post, or any method with Http.request:
println((try Http.post("${base}/echo", "buy milk")).text())
println((try Http.request("PUT", "${base}/echo", body: "call Ann")).text())POST buy milk
PUT call AnnScope
A handler gets path decoded and query raw, as sent. Read the query with Url.parseQuery:
func greet(req: Http.Request): Http.Reply {
let query = Url.parseQuery(req.query)
if query is Err { return Http.Reply{ status: 400, headers: Map{}, body: query.error.message } }
let name = query.value["name"]?.first() ?? "stranger"
let body = "path ${req.path}\nquery ${req.query}\nname ${name}"
Http.Reply{ status: 200, headers: Map{}, body }
}
let listener = try Net.listen("127.0.0.1:0")
go { _ = Http.serve(listener, greet) }
println((try Http.get("http://${listener.address()}/my%20docs?name=Ann%20Lee")).text())path /my docs
query name=Ann%20Lee
name Ann LeeA redirect comes back as it is. Ask for its Location to follow it:
let moved = try Http.get("${base}/old")
println("${moved.status} ${moved.headers["Location"]}")
let page = try Http.get("${base}${moved.headers["Location"]}")
println(page.text())301 /hello
helloNo server at the address is Err, since no response arrived:
let listener = try Net.listen("127.0.0.1:0")
let url = "http://${listener.address()}/"
listener.close()
println(Http.get(url) is Err)trueNamed arguments
Every client function takes headers, which go out with the request:
println((try Http.get("${base}/lang")).text())
println((try Http.get("${base}/lang", headers: Map{ "Accept-Language": "fr" })).text())any
frtimeout bounds one call, from connecting to the end of the body:
println(Http.get("${base}/slow", timeout: 50ms))Err{ error: Error{ message: "timeout" } }ctx bounds a call too, and one context can bound several calls, or stop a server:
let ctx = Context.new(timeout: 50ms)
println(Http.get("${base}/slow", ctx: ctx))
println(Http.get("${base}/hello", ctx: ctx))Err{ error: Error{ message: "timeout" } }
Err{ error: Error{ message: "timeout" } }Functions by job
Client
- Http.get: a GET request, and the whole response
- Http.post: a POST request with a body
- Http.request: a request with any method, body, and headers
Server
- Http.serve: answer every request on a listener with a handler, each on a goroutine of its own
Types
- Http.Response: what the client gets back: status, headers, and the body
- Http.Request: what a handler gets: method, path, query, headers, body, and the client's address
- Http.Reply: what a handler returns: status, headers, and a body of text or
Bytes
Applications
Fetch JSON, turn a bad status into an Err, and add context to every failure:
func fetchName(base: string, path: string): Result[string, Error] {
let res = try (Http.get("${base}${path}") | Result.wrapErr("get ${path}"))
if res.status != 200 {
return Result.fail("get ${path}: status ${res.status}")
}
let user = try (Json.parse(res.text()) | Result.wrapErr("parse ${path}"))
let name = if user is Map { user["name"] } else { null }
Result.ok(if name is string { name } else { "unknown" })
}
println(fetchName(base, "/user"))
println(fetchName(base, "/nobody"))Ok{ value: "Ann" }
Err{ error: Error{ message: "get /nobody: status 404" } }Check several pages, with a short timeout for each:
for path in ["/hello", "/slow", "/gone"] {
let res = Http.get("${base}${path}", timeout: 100ms)
let state = if res is Err { res.error.message } else { "${res.value.status}" }
println("${path}: ${state}")
}/hello: 200
/slow: timeout
/gone: 404A server and a client in one program, stopped by a context once the work is done:
func shout(req: Http.Request): Http.Reply {
Http.Reply{ status: 200, headers: Map{}, body: req.text().toUpper() }
}
let listener = try Net.listen("127.0.0.1:0")
let url = "http://${listener.address()}/"
let stop = Context.new()
let served: Channel[Result[void, Error]] = Channel.new(1)
go { served.send(Http.serve(listener, shout, stop)) }
for word in ["ant", "http"] {
println((try Http.post(url, word)).text())
}
stop.cancel()
println(served.receive())ANT
HTTP
Ok{ value: void }Properties and relations
Http.get and Http.post are Http.request with the method filled in:
assert(try Http.get("${base}/echo") == try Http.request("GET", "${base}/echo"))
let posted = try Http.post("${base}/echo", "hi")
assert(posted == try Http.request("POST", "${base}/echo", body: "hi"))The body arrives as received in bytes, and text() decodes it:
let res = try Http.post("${base}/echo", "naïve")
assert(res.text() == "POST naïve")
assert(res.bytes == res.text().toBytes())Possible issues
try stops only on Err, and a 404 or a 500 is Ok, so a program that reads the body without checking status reads the error page:
let res = try Http.get("${base}/user/42")
println(res.text())no /user/42A reply status outside 200 to 599, such as an interim 100, panics in the handler's goroutine. Like any panic in a handler, it is reported as a goroutine's panic is, and the client gets status 500 with an empty body:
func early(req: Http.Request): Http.Reply {
Http.Reply{ status: 100, headers: Map{}, body: "wait" }
}
let listener = try Net.listen("127.0.0.1:0")
go { _ = Http.serve(listener, early) }
let res = try Http.get("http://${listener.address()}/")
println(res.status)
println(res.text().isEmpty())500
trueA timeout must be positive and of a fixed length. Weeks, months, and years are Err before anything is sent:
println(Http.get("http://127.0.0.1:1/", timeout: 0s))
println(Http.get("http://127.0.0.1:1/", timeout: Time.duration(weeks: 1)))Err{ error: Error{ message: "get \"http://127.0.0.1:1/\": the timeout is zero or negative" } }
Err{ error: Error{ message: "get \"http://127.0.0.1:1/\": the timeout has years, months or weeks, which have no fixed length" } }A script ends when its last line runs, and a server on a goroutine ends with it. A script that only serves calls Http.serve on its main path, with Os.interrupt as ctx to stop on Ctrl-C.
See also
Http.get · Http.post · Http.request · Http.serve · Http.Response · Http.Request · Http.Reply · Net.listen · Net.address · Context · Url · Json.parse
