Incremental HTTP/1.1 request parsing in pure MoonBit, adapted from uWebSockets HttpParser
///|
test "retain a parsed request and decode its query" {
let parser = @http_parser.Parser::new()
let requests : Array[@http_parser.Request] = []
ignore(
parser.feed(
b"GET /?hello=a%20b+c&debug HTTP/1.1\r\nHost: h\r\n\r\n",
on_request=request => {
requests.push(request)
@http_parser.Continue
},
on_body=(_, _) => @http_parser.Continue,
),
)
parser.finish()
assert_eq(requests[0].get_header(b"host"), Some(b"h"[:]))
assert_eq(
requests[0].get_query_value(b"hello"),
Some(@http_parser.Value(b"a b c")),
)
assert_eq(requests[0].get_query_value(b"debug"), Some(@http_parser.Valueless))
}///|
test "a request callback can hand off the untouched suffix" {
let parser = @http_parser.Parser::new()
let input : Bytes = b"GET / HTTP/1.1\r\nHost: h\r\n\r\nnext protocol"
let result = parser.feed(input, on_request=_ => @http_parser.Stop, on_body=(
_,
_,
) => @http_parser.Continue)
assert_eq(input[result.consumed():], b"next protocol"[:])
}pub(all) suberror ParseError {
InvalidRequestLine
InvalidHeaderName
InvalidHeaderValue
MissingHost
DuplicateHost
InvalidHost
ConflictingBodyFraming
InvalidContentLength
InvalidTransferEncoding
HeaderTooLarge
TooManyHeaders
InvalidChunkedEncoding
UnexpectedEof
InvalidLimits
ReentrantCall
} derive(Eq, Debug)pub struct Parser {
// private fields
}fn Parser::feed(self : Parser, input : BytesView, on_request~ : (Request) -> Control, on_body~ : (BytesView, UInt64) -> Control) -> FeedResult raise ParseErrorfn Parser::new(max_header_bytes? : Int, max_headers? : Int, algorithm? : Algorithm) -> Parser raise ParseErrorpub struct Request {
// private fields
}Install
Download zipIncremental HTTP/1.1 request parsing in pure MoonBit, adapted from uWebSockets HttpParser