Browse Source

n4u_xhr (cowboy 1.0.1)

221V 3 years ago
parent
commit
899c0a83a7
1 changed files with 32 additions and 0 deletions
  1. 32 0
      src/protocols/n4u_xhr.erl

+ 32 - 0
src/protocols/n4u_xhr.erl

@@ -0,0 +1,32 @@
+-module(n4u_xhr).
+-behaviour(cowboy_http_handler).
+
+-include_lib("n4u/include/n4u.hrl").
+
+
+% stream bridge to XHR
+
+% cowboy websocket backend
+-export([init/3, handle/2, info/3, terminate/3]).
+
+
+% XHR
+init(T, R, O)              -> xhr(n4u_proto:init(T, R, [{formatter, json}|O], xhr)).
+
+handle(R, S)               -> body(cowboy_req:body(R), S).
+info(M, R, S)              -> xhr(n4u_proto:info(M, R, S)).
+terminate(_, R, S)         -> n4u_proto:terminate(R, S).
+
+body({ok, D, R2}, S)       -> xhr(n4u_proto:stream({type(D), D}, R2, S));
+body(R, S)                 -> {ok, R, S}.
+
+type(<<"N4U,", _/binary>>) -> text;
+type(<<"PING">>)           -> text;
+type(_)                    -> binary.
+
+xhr({ok, R, S})            -> {ok, R, S};
+xhr({shutdown, R, S})      -> {shutdown, R, S};
+xhr({reply, D, R, S})      -> {ok, reply(D, R, 200), S}.
+
+reply(D, R, Code)          -> {ok, R2} = cowboy_req:reply(Code, [], D, R), R2.
+