1
Fork 0
hare-playground/vendor/hare-http/cmd/http/main.ha

76 lines
1.6 KiB
Hare
Raw Normal View History

2024-06-01 14:46:01 +00:00
use getopt;
use io;
use log;
use net::dial;
use net::http;
use net::uri;
use os;
use strings;
const usage: [_]getopt::help = [
"HTTP client",
('H', "Name:value", "Sets an HTTP header"),
('X', "method", "Sets the HTTP method verb"),
"url"
];
export fn main() void = {
const client = http::newclient("Hare net::http test client");
defer http::client_finish(&client);
const cmd = getopt::parse(os::args, usage...);
defer getopt::finish(&cmd);
if (len(cmd.args) != 1) {
getopt::printusage(os::stderr, "http", usage)!;
os::exit(os::status::FAILURE);
};
const targ = match (uri::parse(cmd.args[0])) {
case let u: uri::uri =>
yield u;
case uri::invalid =>
log::fatal("Invalid URI");
};
defer uri::finish(&targ);
let req = http::new_request(&client, "GET", &targ)!;
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(&req.header, name, val);
case 'X' =>
req.method = val;
case => abort();
};
};
const resp = match (http::do(&client, &req)) {
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 = match (resp.body) {
case let st: *io::stream =>
yield st;
case null =>
return;
};
io::copy(os::stdout, body)!;
io::close(body)!;
};