Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cowboy multiple METHOD handler

Trying to setup restful API via Cowboy the main thing that I nedd to use one handler for all methods

here is router ::

 start(_Type, _Args) ->
    Dispatch = cowboy_router:compile([
        {'_', [
            {"/api", handler, []},
            {"/api/:id", handler, []}
        ]}
    ]),
    {ok, _} = cowboy:start_clear(http, 100, [{port, 8080}], #{
        env => #{dispatch => Dispatch}
    }),
    api_sup:start_link().

and here is the handler code::

-module(handler).
-export([init/3, handle/2]).

init(_Transport, Req, []) ->
    {ok, Req, undefined}.

handle(Req, Opts) -> 
  case cowboy_req:method(Req) of
    <<"POST">> -> 
      Body = cowboy_req:has_body(Req),
      Request = postMethod(<<"POST">>, Body, Req),
        {ok, Request, Opts};
    <<"GET">> -> 
      #{id := Id} = cowboy_req:match_qs([{id, [], undefined}], Req),
      Request = getMethod(<<"GET">>, Id, Req),
        {ok, Request, Opts};
    <<"PUT">> -> 
      Body = cowboy_req:has_body(Req),
      Request = putMethod(<<"PUT">>, Body, Req),
        {ok, Request, Opts};
    <<"DELETE">> -> 
      #{id := Id} = cowboy_req:match_qs([{id, [], undefined}], Req),
      Request = deleteMethod(<<"DELETE">>, Id, Req),
        {ok, Request, Opts}
  end.

  postMethod(<<"POST">>, _Body, Req) -> 
    cowboy_req:reply(200, #{<<"content-type">> => <<"application/json; charset=utf-8">>}, <<"{\"status\": \"POST\"}">>, Req).
  getMethod(<<"GET">>, _Id, Req) -> 
      cowboy_req:reply(200, #{<<"content-type">> => <<"application/json; charset=utf-8">>}, <<"{\"status\": \"GET\"}">>, Req).
  putMethod(<<"PUT">>, _Body, Req) -> 
      cowboy_req:reply(200, #{<<"content-type">> => <<"application/json; charset=utf-8">>}, <<"{\"status\": \"PUT\"}">>, Req).
  deleteMethod(<<"DELETE">>, _Id, Req) -> 
      cowboy_req:reply(200, #{<<"content-type">> => <<"application/json; charset=utf-8">>}, <<"{\"status\": \"DELETE\"}">>, Req).

I am getting the error : cowboy 500 error

like image 868
Eugen Dubrovin Avatar asked Apr 22 '26 01:04

Eugen Dubrovin


2 Answers

Found the answer. here is the code which works fine (using master verison of Cowboy)

-module(handler).

-export([init/2]).
-export([content_types_provided/2]).
-export([content_types_accepted/2]).
-export([allowed_methods/2]).
-export([router/2]).

init(Req, Opts) ->
    {cowboy_rest, Req, Opts}.

allowed_methods(Req, State) ->
    {[<<"GET">>, <<"POST">>, <<"PUT">>, <<"DELETE">>], Req, State}.

content_types_provided(Req, State) ->
    {[{<<"application/json">>, router}], Req, State}.

content_types_accepted(Req, State) ->
    {[{<<"application/json">>, router}], Req, State}.

router(Req, Opts) -> 
  case cowboy_req:method(Req) of
    <<"POST">> -> 
        {<<"{\"status\": \"POST\"}">>, Req, State};
    <<"GET">> -> 
      {<<"{\"status\": \"GET\"}">>, Req, State};
    <<"PUT">> -> 
      {<<"{\"status\": \"PUT\"}">>, Req, State};
    <<"DELETE">> -> 
      {<<"{\"status\": \"DELETE\"}">>, Req, State}
  end.
like image 94
Eugen Dubrovin Avatar answered Apr 23 '26 18:04

Eugen Dubrovin


I came to a slightly different approach. Instead of going for case I use functions, pattern-match the method in request and then catch-all with code 405 Method Unsupported.

-module(handler).

-export([init/2]).

init(Req0, State) ->
  Req = case api:validate_headers(api_key, Req0) of
    ok -> handle(Req0, State);
    {error, Error} -> api:reply_failure(403, Error, Req0)
  end,
  {ok, Req, State}.

handle(Req0=#{method := <<"GET">>}, _) ->
  Data = "...", % Some data goes here
  api:reply_success([{<<"data">>, Data}], Req0);

handle(Req0=#{method := <<"POST">>}, _) ->
  Data = "...", % Some data goes here
  api:reply_success([{<<"data">>, Data}], Req0);

handle(Req=#{method := <<"OPTIONS">>}, _) ->
  api:reply_options(Req);

handle(Req, _) ->
  cowboy_req:reply(405, Req).
like image 27
Aleksey Gureiev Avatar answered Apr 23 '26 18:04

Aleksey Gureiev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!