1
Fork 0
hare-http/cmd/http/main.ha
2023-10-07 12:57:35 +02:00

61 lines
1.3 KiB
Hare

use getopt;
use io;
use log;
use net::dial;
use net::http;
use net::uri;
use os;
use strings;
export fn main() void = {
const client = http::newclient("Hare net::http test client");
defer http::client_finish(&client);
const cmd = getopt::parse(os::args,
"HTTP client",
('H', "Name:value", "Sets an HTTP header"),
"url");
defer getopt::finish(&cmd);
let head = http::client_default_header(&client);
for (let i = 0z; i < len(cmd.opts); i += 1) {
const (opt, val) = cmd.opts[i];
switch (opt) {
case 'H' =>
const (name, val) = strings::cut(val, ":");
http::header_add(head, name, val);
case => abort();
};
};
const target = cmd.args[0];
const target = match (uri::parse(target)) {
case let u: uri::uri =>
yield u;
case uri::invalid =>
log::fatal("Invalid URI");
};
defer uri::finish(&target);
const resp = match (http::get(&client, &target)) {
case let err: http::error =>
log::fatal("HTTP error:", http::strerror(err));
case let resp: http::response =>
yield resp;
};
defer http::response_finish(&resp);
log::printfln("HTTP/{}.{}: {} {}",
resp.version.0, resp.version.1,
resp.status, resp.reason);
for (let i = 0z; i < len(resp.header); i += 1) {
const (name, val) = resp.header[i];
log::printfln("{}: {}", name, val);
};
const body = resp.body as *io::stream;
io::copy(os::stdout, body)!;
io::close(body)!;
};