Current section

Files

Jump to
mist src mist@encoder.erl
Raw

src/mist@encoder.erl

-module(mist@encoder).
-compile(no_auto_import).
-export([to_bit_builder/1, status_to_bit_string/1, encode_headers/1]).
-spec to_bit_builder(
gleam@http@response:response(gleam@bit_builder:bit_builder())
) -> gleam@bit_builder:bit_builder().
to_bit_builder(Resp) ->
Body_size = gleam@bit_builder:byte_size(erlang:element(4, Resp)),
Headers = begin
_pipe = gleam@map:from_list(
[{<<"content-type"/utf8>>, <<"text/plain; charset=utf-8"/utf8>>},
{<<"content-length"/utf8>>, gleam@int:to_string(Body_size)},
{<<"connection"/utf8>>, <<"keep-alive"/utf8>>}]
),
gleam@list:fold(
erlang:element(3, Resp),
_pipe,
fun(Defaults, Tup) ->
{Key, Value} = Tup,
gleam@map:insert(Defaults, Key, Value)
end
)
end,
Body_builder = case Body_size of
0 ->
gleam@bit_builder:new();
_@1 ->
_pipe@1 = gleam@bit_builder:new(),
_pipe@2 = gleam@bit_builder:append_builder(
_pipe@1,
erlang:element(4, Resp)
),
gleam@bit_builder:append(_pipe@2, <<"\r\n"/utf8>>)
end,
Status_string = begin
_pipe@3 = erlang:element(2, Resp),
_pipe@4 = gleam@int:to_string(_pipe@3),
_pipe@5 = gleam@bit_builder:from_string(_pipe@4),
_pipe@6 = gleam@bit_builder:append(_pipe@5, <<" "/utf8>>),
gleam@bit_builder:append(
_pipe@6,
status_to_bit_string(erlang:element(2, Resp))
)
end,
_pipe@7 = gleam@bit_builder:new(),
_pipe@8 = gleam@bit_builder:append(_pipe@7, <<"HTTP/1.1 "/utf8>>),
_pipe@9 = gleam@bit_builder:append_builder(_pipe@8, Status_string),
_pipe@10 = gleam@bit_builder:append(_pipe@9, <<"\r\n"/utf8>>),
_pipe@11 = gleam@bit_builder:append_builder(
_pipe@10,
encode_headers(Headers)
),
_pipe@12 = gleam@bit_builder:append(_pipe@11, <<"\r\n"/utf8>>),
gleam@bit_builder:append_builder(_pipe@12, Body_builder).
-spec status_to_bit_string(integer()) -> bitstring().
status_to_bit_string(Status) ->
case Status of
101 ->
<<"Switching Protocols"/utf8>>;
200 ->
<<"Ok"/utf8>>;
201 ->
<<"Created"/utf8>>;
202 ->
<<"Accepted"/utf8>>;
204 ->
<<"No Content"/utf8>>;
301 ->
<<"Moved Permanently"/utf8>>;
400 ->
<<"Bad Request"/utf8>>;
401 ->
<<"Unauthorized"/utf8>>;
403 ->
<<"Forbidden"/utf8>>;
404 ->
<<"Not Found"/utf8>>;
405 ->
<<"Method Not Allowed"/utf8>>;
500 ->
<<"Internal Server Error"/utf8>>;
502 ->
<<"Bad Gateway"/utf8>>;
503 ->
<<"Service Unavailable"/utf8>>;
504 ->
<<"Gateway Timeout"/utf8>>
end.
-spec encode_headers(gleam@map:map_(binary(), binary())) -> gleam@bit_builder:bit_builder().
encode_headers(Headers) ->
gleam@map:fold(
Headers,
gleam@bit_builder:new(),
fun(Builder, Header, Value) ->
_pipe = Builder,
_pipe@1 = gleam@bit_builder:append_string(_pipe, Header),
_pipe@2 = gleam@bit_builder:append(_pipe@1, <<": "/utf8>>),
_pipe@3 = gleam@bit_builder:append_string(_pipe@2, Value),
gleam@bit_builder:append(_pipe@3, <<"\r\n"/utf8>>)
end
).