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

61 lines
1.3 KiB
Hare
Raw Normal View History

2023-10-07 10:57:35 +00:00
use getopt;
2023-02-10 09:13:30 +00:00
use io;
use log;
2023-02-10 09:13:30 +00:00
use net::dial;
2023-02-09 19:54:21 +00:00
use net::http;
use net::uri;
use os;
2023-10-07 10:57:35 +00:00
use strings;
2023-02-09 19:54:21 +00:00
export fn main() void = {
const client = http::newclient("Hare net::http test client");
2023-02-09 22:23:05 +00:00
defer http::client_finish(&client);
2023-10-07 10:57:35 +00:00
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)) {
2023-02-10 09:13:30 +00:00
case let u: uri::uri =>
yield u;
case uri::invalid =>
log::fatal("Invalid URI");
2023-02-10 09:13:30 +00:00
};
defer uri::finish(&target);
2023-02-10 13:18:01 +00:00
const resp = match (http::get(&client, &target)) {
2023-02-10 09:13:30 +00:00
case let err: http::error =>
log::fatal("HTTP error:", http::strerror(err));
2023-02-10 09:13:30 +00:00
case let resp: http::response =>
yield resp;
};
2023-02-10 13:18:01 +00:00
defer http::response_finish(&resp);
2023-02-10 09:13:30 +00:00
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;
2023-02-10 09:13:30 +00:00
io::copy(os::stdout, body)!;
io::close(body)!;
2023-02-09 19:54:21 +00:00
};