Http module

parser_init

procedure · 1 overloadSource

Prepares p to read requests or responses. Any state the parser had is released first, so it is safe to call on a parser that was used. limits caps line, head and body sizes (the defaults are in Limits); a message over a limit is refused with the error kind that maps to the matching status. For a response parser, set p.response_to to the request's method before the response head arrives.

ExampleOpen in playground ↗
limits := Limits.{ max_body_size = 4 };

parser: Parser;
parser_init(*parser, .REQUEST, limits);
defer parser_free(*parser);

text := "POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 10\r\n\r\n0123456789";
data: [] u8 = .{ text.count, text.data };

failed := false;
while true {
    used, event := parse(*parser, data);
    data = advance(data, used);

    if event.kind == .ERROR failed = true;
    if event.kind == .ERROR || event.kind == .END || event.kind == .NEED_MORE break;
}

assert(failed);
assert(parser.error.kind == .BODY_TOO_LARGE);
parser_init :: (p: *Parser, kind: Parser_Kind, limits := Limits.{})

Prepares p to read requests or responses. Any state the parser had is released first, so it is safe to call on a parser that was used. limits caps line, head and body sizes (the defaults are in Limits); a message over a limit is refused with the error kind that maps to the matching status. For a response parser, set p.response_to to the request's method before the response head arrives.

Parameters

p: *Parser
the parser to set up. Whatever it held before is freed.
kind: Parser_Kind
whether it reads requests or responses.
limits := Limits.{}
size limits for lines, heads, headers and bodies, and a few strictness switches.
ExampleOpen in playground ↗
limits := Limits.{ max_body_size = 4 };

parser: Parser;
parser_init(*parser, .REQUEST, limits);
defer parser_free(*parser);

text := "POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 10\r\n\r\n0123456789";
data: [] u8 = .{ text.count, text.data };

failed := false;
while true {
    used, event := parse(*parser, data);
    data = advance(data, used);

    if event.kind == .ERROR failed = true;
    if event.kind == .ERROR || event.kind == .END || event.kind == .NEED_MORE break;
}

assert(failed);
assert(parser.error.kind == .BODY_TOO_LARGE);

See also