The standard librarySlide 67 of 86
67openThe standard library
Responses as they arrive
httpRequest answers only when the whole body has arrived. A body sent a piece at a time, such as a language model's answer, a log being followed or server-sent events, is read as it comes instead:
hive.net.httpOpen(request)sends the request and answers as soon as the status and headers are in, with aResult<HttpStream, HttpError>. AnHttpStreamhas thestatusandheadersof anHttpResponse, and a body still arriving. A 404 is stillOk, and its body is read the same way.httpReceiveLine(stream)answers with the next line of the body, without its newline, as soon as it has arrived;httpReceive(stream, bytes)answers with whatever is there, at most that many bytes. Both block only the calling thread.httpClose(stream)drops the connection. That is how a server learns nobody is reading, and how a client stops a model mid-answer. It may be called from another thread while a receive waits, and that receive answersClosed.
The errors are a hive.net.HttpStreamError: Closed once the body has ended or the stream was closed, Receive when the connection breaks part-way. Only connecting has a time limit, because a model server answers only after its model has loaded, so a program with other work to do reads on a thread of its own.
The example's server is a stand-in, so the program needs nothing installed. httpServe answers with a whole body, so the stand-in writes the HTTP itself, over a socket.
A model's answer, word by word
type Chunk {
content: Str
done: Bool
}
// A stand-in for a model's server: one JSON line per word, a moment apart.
proc model(conn: hive.net.SocketConnection): void {
for ; true; {
if hive.net.socketReceiveLine(conn) is Result.Ok(line) && line != "" {
continue
}
break
}
hive.net.socketSend(conn, "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n")
for each word in ["Light", " scatters,", " and", " blue", " scatters", " most."] {
hive.task.sleep(50)
hive.net.socketSend(conn, encode(Chunk(word, false), hive.json.codec()) + "\n")
}
hive.net.socketSend(conn, encode(Chunk("", true), hive.json.codec()) + "\n")
}
proc main(): void {
async hive.net.socketServe(9025, model)
hive.task.sleep(200)
asked := hive.net.HttpRequest("GET", "http://127.0.0.1:9025/", [], "")
if hive.net.httpOpen(asked) is Result.Ok(stream) {
mut going := true
for ; going; {
going = false
if hive.net.httpReceiveLine(stream) is Result.Ok(line) {
if Chunk.decode(line, hive.json.codec()) is Result.Ok(piece) {
// hive.term.print ends no line: the words join up as they arrive.
hive.term.print(piece.content)
going = piece.done == false
}
}
}
hive.term.println("")
hive.net.httpClose(stream)
}
}