The standard librarySlide 65 of 85
65requestThe standard library
HTTP requests and query strings
hive.net.httpRequest(request) sends an HttpRequest(method, url, headers, body) and answers with a Result<HttpResponse, hive.net.HttpError>. Any answer at all is Ok — a 404 and a 500 included, with their status — and an HttpError, carrying the url and a message, is for getting no answer: a bad URL, a refused connection, or nothing within 30 seconds.
urlEncode(text) percent-encodes every byte but letters, digits and - . _ ~, so what comes back is safe in a path and a query alike. queryParamsCodec() is a codec for the query string itself, without its ?: encode writes a type's fields as key=value pairs, and T.decode reads them back.
-- URL as <key>;names a parameter, and a vector is its key repeated:tag=web&tag=cli. AT[3]needs its key exactly three times.+and%20are both a space, a leading?is accepted, and a key the type does not declare is ignored.- A field that is absent is an error unless it has a
Default, and a key given twice for anything but a vector is an error. ABoolis writtentrueorfalse; a bare key is not one. - A query string is flat, so only a type without variants whose fields are values, or vectors of values, travels as one — anything else is a compile error at the call.
A request
proc main(): void {
request := hive.net.HttpRequest("GET", "https://example.com/", [], "")
answer := hive.net.httpRequest(request)
if answer is Result.Ok(response) {
echo "status {response.status}, {len(response.body)} characters"
} else if answer is Result.Error(why) {
echo "no answer from {why.url}: {why.message}"
}
}Query strings
type Search {
term: Str -- URL as q;
page: Int -- Default as 1;
tags: Str[dyn] -- URL as tag;
}
proc main(): void {
echo hive.net.urlEncode("rust & go")
params := encode(Search("rust & go", 2, ["web", "cli"]), hive.net.queryParamsCodec())
echo "https://example.com/search?{params}"
if Search.decode("q=hive+lang&tag=web", hive.net.queryParamsCodec()) is Result.Ok(s) {
echo "{s.term}, page {s.page}"
}
}You can edit this program and run it here.Tab indents, Escape leaves the program, and Ctrl+Enter runs it.