1
Fork 0
hare-http/net/http/response.ha
Drew DeVault ca93a48b12 Implement HTTP response parsing and reader
TODO: Handle Transfer-Encoding and Content-Length properly
2023-02-10 14:09:28 +01:00

56 lines
1.1 KiB
Hare

use io;
use os;
// Stores state related to an HTTP response.
export type response = struct {
// HTTP protocol version (major, minor)
version: (uint, uint),
// The HTTP status for this request as an integer.
status: uint,
// The HTTP status reason phrase.
reason: str,
// The HTTP headers provided by the server.
header: header,
// The response body, if any.
body: nullable *reader,
};
// Frees state associated with an HTTP [[response]].
export fn response_finish(resp: *response) void = {
header_free(&resp.header);
free(resp.reason);
};
export type reader = struct {
vtable: io::stream,
conn: io::handle,
buffer: [os::BUFSIZ]u8,
pending: size,
};
const reader_vtable = io::vtable {
reader = &reader_read,
...
};
fn reader_read(s: *io::stream, buf: []u8) (size | io::EOF | io::error) = {
let rd = s: *reader;
if (rd.pending == 0) {
match (io::read(rd.conn, rd.buffer)?) {
case let n: size =>
rd.pending = n;
case io::EOF =>
return io::EOF;
};
};
let n = len(buf);
if (n > rd.pending) {
n = rd.pending;
};
buf[..n] = rd.buffer[..n];
rd.buffer[..len(rd.buffer) - n] = rd.buffer[n..];
rd.pending -= n;
return n;
};