n4u_xhr.erl 906 B

1234567891011121314151617181920212223242526272829303132
  1. -module(n4u_xhr).
  2. -behaviour(cowboy_handler).
  3. -include_lib("n4u/include/n4u.hrl").
  4. % stream bridge to XHR
  5. % cowboy websocket backend
  6. -export([init/2, handle/2, info/3, terminate/3]).
  7. % XHR
  8. init(R, O) -> xhr(n4u_proto:init([], R, [{formatter, json}|O], xhr)).
  9. handle(R, S) -> body(cowboy_req:body(R), S).
  10. info(M, R, S) -> xhr(n4u_proto:info(M, R, S)).
  11. terminate(_, R, S) -> n4u_proto:terminate(R, S).
  12. body({ok, D, R2}, S) -> xhr(n4u_proto:stream({type(D), D}, R2, S));
  13. body(R, S) -> {ok, R, S}.
  14. type(<<"N4U,", _/binary>>) -> text;
  15. type(<<"PING">>) -> text;
  16. type(_) -> binary.
  17. xhr({ok, R, S}) -> {ok, R, S};
  18. xhr({shutdown, R, S}) -> {shutdown, R, S};
  19. xhr({reply, D, R, S}) -> {ok, reply(D, R, 200), S}.
  20. reply(D, R, Code) -> cowboy_req:reply(Code, [], D, R). % R2.