openroad
A cowboy middleware, that is an OTP application, to make sending responses more convenient.
Build
$ rebar3 compileUsage
Rebar Config
Add openroad to your rebar.config dependency list.
{deps, [openroad]}.Make sure the openroad application is started before using.
If you want to do templating you'll need to configure erlydtl.
{erlydtl_opts, [{doc_root, "src/views"}]}.This tells erlydtl which directory your view templates are in.
You'll also have to configure the erlydtl rebar3_plugin to compile the views into erlang modules.
{plugins, [
{rebar3_erlydtl_plugin, ".*", {git, "https://github.com/tsloughter/rebar3_erlydtl_plugin.git", {branch, "master"}}}
]}.
{provider_hooks, [
{pre, [{compile, {erlydtl, compile}}]}
]}.Cowboy
openroad provides a single module to be used: openroad_response.
openroad_response is a cowboy middleware. Insert it at the end of the middleware list.
start(_StartType, _StartArgs) ->
Dispatch = cowboy_router:compile([{'_', [{<<"/">>, hello_handler, #{}}]}]),
{ok, _} = cowboy:start_clear(my_http_listener,
[{port, 8080}],
#{env => #{dispatch => Dispatch},
middlewares => [cowboy_router,
cowboy_handler,
openroad_response]}
),
openroad_example_sup:start_link().Handler
Then you can set up your handler like so:
-module(hello_handler).
-export([init/2]).
init(Req, Env) ->
{ok, Req#{resp => {text, <<"Hello, World!">>}}, Env}.Routes
openroad supports text, json, html, and template as responses.
Text
This will automatically set the content-type header to "text/plain; charset=utf-8".
{ok, Req#{resp => {text, <<"Hello, World!">>}}, Env}Json
This will automatically set the content-type header to "application/json; charset=utf-8".
{ok, Req#{resp => {json, #{<<"hello">> => <<"world">>}}}, Env}.Html
This will automatically set the content-type header to "text/html; charset=utf-8".
Setup the views as instructed above, then simply use the view module name in the response.
{ok, Req#{resp => {html, {hello_view_dtl, #{message => <<"Hello, World!">>}}}}, Env}.If you want to build a composite view simply make a list of views.
{ok, Req#{resp => {html, [{header_view_dtl, #{}},
{body_view_dtl, #{message => <<"Hello, World!">>}},
{footer_view_dtl, #{}}]}}, Env}.Template
openroad provides a way to do templating that isn't strictly html. In contrast to html responses, generic template views do not automatically set the content-type header.
{ok, Req#{resp => {template, {hello_view_dtl, #{message => <<"Hello, World!">>}, <<"text/xml">>}}}, Env}.Contributing
Send patches to:
~fancycade/public-inbox@lists.sr.htIf you are new to email based git workflows please refer to this tutorial.
License
Apache v2