1
Fork 0
hare-http/net/http/header.ha

53 lines
1.5 KiB
Hare
Raw Normal View History

2023-02-09 19:54:21 +00:00
use fmt;
2023-02-09 22:23:05 +00:00
use io;
use strings;
2023-02-09 19:54:21 +00:00
// List of HTTP headers.
export type header = [](str, str);
2023-02-09 22:23:05 +00:00
// Adds a given HTTP header, which may be added more than once. The value is
// duplicated, but the name is borrowed from the caller. The name should be
// canonicalized by the caller.
2023-02-09 19:54:21 +00:00
export fn add_header(head: *header, name: str, val: str) void = {
2023-02-09 22:23:05 +00:00
append(head, (name, strings::dup(val)));
2023-02-09 19:54:21 +00:00
};
// Sets the value of a given HTTP header, removing any previous values. The
2023-02-09 22:23:05 +00:00
// value is duplicated, but the name is borrowed from the caller. The name
// should be canonicalized by the caller.
2023-02-09 19:54:21 +00:00
export fn set_header(head: *header, name: str, val: str) void = {
del_header(head, name);
add_header(head, name, val);
};
// Removes an HTTP header from a list of [[header]]. If multiple headers match
// the given name, all matching headers are removed.
export fn del_header(head: *header, name: str) void = {
for (let i = 0z; i < len(head); i += 1) {
if (head[i].0 == name) {
2023-02-09 22:23:05 +00:00
free(head[i].1);
2023-02-09 19:54:21 +00:00
delete(head[i]);
i -= 1;
};
};
};
// Writes a list of HTTP headers to the provided I/O handle in the HTTP wire
// format.
export fn write_header(sink: io::handle, head: *header) (size | io::error) = {
let z = 0z;
for (let i = 0z; i < len(head); i += 1) {
const (name, val) = head[i];
z += fmt::fprintf(sink, "{}: {}\r\n", name, val)?;
};
return z;
};
2023-02-10 09:13:30 +00:00
// Frees state associated with an HTTP [[header]].
export fn header_free(head: *header) void = {
for (let i = 0z; i < len(head); i += 1) {
free(head[i].1);
};
free(*head);
};