The standard librarySlide 65 of 86
65serveThe 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. If the port is taken, the program stops with an error.
- An
HttpRequesthas amethod; aurl, which on the server is the path and the query string,"/search?q=bee", not a whole URL; itsheaders, as aTableof[name, value]rows; and thebody. - The handler answers with an
HttpResponse(status, headers, body), 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.
The tour is built this way: 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)
}