handlers.tex 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. \section{Handlers}
  2. HTML and JavaScript Web Server HTTP handlers share the same system
  3. of context initialization.
  4. \vspace{1\baselineskip}
  5. \begin{lstlisting}
  6. init_context(Req) -> #cx{
  7. actions=[], module=index, path=[],
  8. req=Req, params=[], session=undefined,
  9. handlers= [ {'query', wf:config('query', n2o_query)},
  10. {session, wf:config(session, n2o_session)},
  11. {route, wf:config(route, n2o_route)} ]}.
  12. \end{lstlisting}
  13. \vspace{1\baselineskip}
  14. Chain of three N2O handlers that are always called
  15. on each HTTP request. You can redefine any of them or plug your own
  16. additional handler in the chain to transform web server requests.
  17. \vspace{1\baselineskip}
  18. \begin{lstlisting}[caption=wf:fold/3]
  19. fold(Fun,Handlers,Ctx) ->
  20. lists:foldl(fun({_,Module},Ctx1) ->
  21. {ok,_,NewCtx} = Module:Fun([],Ctx1),
  22. NewCtx end,Ctx,Handlers).
  23. \end{lstlisting}
  24. \vspace{1\baselineskip}
  25. \subsection{Query}
  26. Query Handler parses URL query and HTTP form information from HTTP request.
  27. \subsection{Session}
  28. Session Handler manages key-value in-memory database ETS table.
  29. \newpage
  30. \subsection{Router}
  31. You can specify routing table with application config:
  32. \vspace{1\baselineskip}
  33. \begin{lstlisting}
  34. {n2o, [{route,n2o_route}]}
  35. \end{lstlisting}
  36. \vspace{1\baselineskip}
  37. Remember that routing handler should be kept very simple because it
  38. influences overall initial page load latency and HTTP capacity.
  39. \vspace{1\baselineskip}
  40. \begin{lstlisting}
  41. -module(n2o_route).
  42. -include_lib("n2o/include/wf.hrl").
  43. -export(?ROUTING_API).
  44. finish(S, Cx) -> {ok, S, Cx}.
  45. init(S, Cx) -> P = wf:path(Cx#context.req),
  46. M = prefix(Path),
  47. {ok, S, Cx#cx{path=P,module=M}}.
  48. prefix(<<"/ws/",P/binary>>) -> route(P);
  49. prefix(<<"/",P/binary>>) -> route(P);
  50. prefix(P) -> route(P).
  51. route(<<>>) -> index;
  52. route(<<"index">>) -> index;
  53. route(<<"login">>) -> login;
  54. route(<<"favicon.ico">>) -> index;
  55. route(_) -> index.
  56. \end{lstlisting}