The standard librarySlide 66 of 86
66requestThe 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 from the server is Ok, a 404 or a 500 included, with its status. An HttpError, carrying the url and a message, means no answer came: a bad URL, a refused connection, or nothing within 30 seconds.
urlEncode(text) percent-encodes every byte except letters, digits and - . _ ~, so the result is safe in a path and in a query. 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. A vector is its key repeated,tag=web&tag=cli, and aT[3]needs its key exactly three times.+and%20both decode to a space, a leading?is accepted, and a key the type does not declare is ignored.- An absent field is an error unless it has a
Default, and a key given twice is an error unless its field is a vector. 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, can travel 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.
Output
Run a program to see what it prints here.