The standard librarySlide 64 of 85
64serveThe standard library
HTTP servers
hive.net.httpServe(port, handler) serves HTTP on every interface, calling handler — a proc(HttpRequest): HttpResponse — once per request, each on a thread of its own. It never returns, so a program that serves two things starts one of them with async, and one whose port is taken stops with an error.
- An
HttpRequesthas amethod, aurl— on the server, the path and the query string,"/search?q=bee", rather than a whole URL — itsheadersas aTableof[name, value]rows, and thebody. - An
HttpResponse(status, headers, body)is what the handler answers with, the headers again aTable. A status of0is sent as200. - A handler is an ordinary
proc, so a test calls it directly, with no server running.
This very page is one of these: the tour is a Hive program, and the slide you are reading was a hive.net.HttpResponse a moment ago.
A server
proc handle(request: hive.net.HttpRequest): hive.net.HttpResponse {
headers := [["Content-Type", "text/plain"]]
return hive.net.HttpResponse(200, headers, "hello, {request.url}!\n")
}
proc main(): void {
hive.net.httpServe(8080, handle)
}