Current section
Files
Jump to
Current section
Files
src/nerf@websocket.erl
-module(nerf@websocket).
-compile(no_auto_import).
-export([connect/4, send/2, 'receive'/2, close/1]).
-export_type([connection/0, frame/0, connect_error/0]).
-opaque connection() :: {connection,
nerf@gun:stream_reference(),
nerf@gun:connection_pid()}.
-type frame() :: close | {text, binary()} | {binary, bitstring()}.
-type connect_error() :: {connection_refused,
integer(),
list({binary(), binary()})} |
{connection_failed, gleam@dynamic:dynamic()}.
-spec connect(binary(), binary(), integer(), list({binary(), binary()})) -> {ok,
connection()} |
{error, connect_error()}.
connect(Hostname, Path, Port, Headers) ->
case begin
_pipe = nerf@gun:open(Hostname, Port),
gleam@result:map_error(_pipe, fun(A) -> {connection_failed, A} end)
end of
{error, _try} -> {error, _try};
{ok, Pid} ->
case begin
_pipe@1 = nerf@gun:await_up(Pid),
gleam@result:map_error(
_pipe@1,
fun(A) -> {connection_failed, A} end
)
end of
{error, _try@1} -> {error, _try@1};
{ok, _@1} ->
Ref = nerf@gun:ws_upgrade(Pid, Path, Headers),
Conn = {connection, Ref, Pid},
case begin
_pipe@2 = nerf_ffi:ws_await_upgrade(Conn, 1000),
gleam@result:map_error(
_pipe@2,
fun(A) -> {connection_failed, A} end
)
end of
{error, _try@2} -> {error, _try@2};
{ok, _@2} ->
{ok, Conn}
end
end
end.
-spec send(connection(), binary()) -> nil.
send(Conn, Message) ->
nerf@gun:ws_send(erlang:element(3, Conn), {text, Message}).
-spec 'receive'(connection(), integer()) -> {ok, frame()} | {error, nil}.
'receive'(A, B) ->
nerf_ffi:ws_receive(A, B).
-spec close(connection()) -> nil.
close(Conn) ->
nerf@gun:ws_send(erlang:element(3, Conn), close).