nhttp_lib

Hex.pmCI

Pure functional HTTP/1.1, HTTP/2, and HTTP/3 codec for Erlang/OTP 27+.

Getting started

%% rebar.config
{deps, [nhttp_lib]}.

Parsing

Data = <<"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n">>,
Opts = #{scheme => http, peer => {{127,0,0,1}, 54321}},
case nhttp_h1:parse_request(Data, Opts) of
    {ok, #{method := Method, path := Path} = _Request, _Consumed} ->
        {Method, Path};
    {more, _MinBytes} ->
        need_more_data;
    {error, Reason} ->
        {error, Reason}
end.

The request map is the canonical t:nhttp_lib:request/0 shape: method, path, scheme, authority, and headers are always populated; peer, protocol, and version are filled by the parser. Use nhttp_headers:get/2 to look up header values.

Encoding

Response = #{
    status => 200,
    headers => [{<<"content-type">>, <<"text/plain">>}],
    body => <<"Hello, World!">>
},
IoData = nhttp_h1:encode_response(Response).

encode_request/1 and encode_response/1 return an iolist() directly. For chunked / streaming bodies, omit body from the map and emit the header block with encode_response_head/3, body chunks with encode_chunk/1, and a trailing encode_last_chunk/0.

Features

Documentation

nhttp_lib on HexDocs

License

Apache License 2.0