1
Fork 0
hare-http/net/http/do.ha
2023-02-10 10:52:15 +01:00

52 lines
1.3 KiB
Hare

use bufio;
use fmt;
use io;
use net::dial;
use net::uri;
use net;
use os;
// Performs an HTTP [[request]] with the given [[client]]. The request is
// performed synchronously; this function blocks until the server has returned
// the response status and all HTTP headers associated with the response.
export fn do(client: *client, req: *request) (response | error) = {
assert(req.target.scheme == "http"); // TODO: https
const conn = dial::dial_uri("tcp", req.target)?;
let buf: [os::BUFSIZ]u8 = [0...];
let file = bufio::buffered(conn, [], buf);
bufio::setflush(&file, []);
fmt::fprintf(&file, "{} ", req.method)?;
// TODO: Support other request-targets than origin-form
const target = uri_origin_form(req.target);
uri::fmt(&file, &target)?;
fmt::fprintf(&file, " HTTP/1.1\r\n")?;
// TODO: Handle Content-Length and Transfer-Encoding chunked/gzip
// properly
write_header(&file, &req.header)?;
fmt::fprintf(&file, "\r\n")?;
bufio::flush(&file)?;
match (req.body) {
case void =>
yield;
case let body: io::handle =>
// Copy to conn directly so we can use sendfile(2) if
// appropriate
io::copy(conn, body)?;
};
// Switch buffer to read mode
file = bufio::buffered(conn, buf, []);
// TODO: Parse resposne
return response {
body = conn,
...
};
};