Reputation: 207
Is there a simple way of setting up a single dispatch route in Cowboy that allows multiple handlers such as: /base/add_something /base/remove_something
and have each of those actions services by a single handler that can differentiate them? All of the examples seem to map 1 handler to 1 dispatch, I would like to consolidate functionality if possible.
Upvotes: 2
Views: 617
Reputation: 2020
You can also try to use cowboy_rest like so:
content_types_accepted(Req, State) ->
case cowboy_req:method(Req) of
{<<"POST">>, _ } ->
Accepted = {[{<<"application/json">>, post_json}], Req, State};
{<<"PUT">>, _ } ->
Accepted = {[{<<"application/json">>, put_json}], Req, State}
end,
Accepted.
Upvotes: 1
Reputation: 1818
You can do this:
Dispatch:
...
Dispatch = cowboy_router:compile(
[{'_', [{"/base/:action",
[{type,
function,
is_in_list([<<"add_something">>,
<<"remove_something">>])}],
app_handler, []}]}]),
...
is_in_list(L) ->
fun(Value) -> lists:member(Value, L) end.
...
In app_handler.erl:
...
-record(state, {action :: binary()}).
...
rest_init(Req, Opts) ->
{Action, Req2} = cowboy_req:binding(action, Req),
{ok, Req2, #state{action=Action}}.
...
allowed_methods(Req, #state{action=<<"add_something">>}=State) ->
{[<<"POST">>], Req, State};
allowed_methods(Req, #state{action=<<"remove_something">>}=State) ->
{[<<"DELETE">>], Req, State}.
...
and so on.
Upvotes: 5