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 HttpRequest has a method; a url, which on the server is the path and the query string, "/search?q=bee", not a whole URL; its headers, as a Table of [name, value] rows; and the body.
  • The handler answers with an HttpResponse(status, headers, body), the headers again a Table. A status of 0 is sent as 200.
  • 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)
}