牛仔HTTP POST处理程序

时间:2013-12-03 09:55:48

标签: erlang cowboy

我开始学习Erlang了。我想编写简单的基于牛仔的HTTP服务器,它可以接收通过HTTP POST发送的文件。所以我创建了简单的处理程序:

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

init({tcp, http}, Req, _Opts) ->
  {ok, Req, undefined_state}.

handle(Req, State) ->
  Body = <<"<h1>Test</h1>">>,
  {ok, Req2} = cowboy_req:reply(200, [], Body, Req),
  {ok, Req2, State}.

terminate(_Reason, _Req, _State) ->
  ok.

此代码可以处理GET请求。但是我如何处理HTTP POST请求呢?

4 个答案:

答案 0 :(得分:7)

您的代码使用任何HTTP方法处理请求。如果要处理特定的HTTP请求方法,则必须在回调句柄/ 2中测试方法名称。在这里你可以看到一个简单的例子:

handle(Req, State) ->
    {Method, Req2} = cowboy_req:method(Req),
    case Method of
        <<"POST">> ->
            Body = <<"<h1>This is a response for POST</h1>">>;
        <<"GET">> ->
            Body = <<"<h1>This is a response for GET</h1>">>;
        _ ->
            Body = <<"<h1>This is a response for other methods</h1>">>
    end,
    {ok, Req3} = cowboy_req:reply(200, [], Body, Req2),
    {ok, Req3, State}.

要获取POST请求的内容,您可以使用函数cowboy_req:body_qs / 2。在牛仔中还有其他用于处理HTTP请求体的函数。查看文档并选择方便的方式。

答案 1 :(得分:0)

您可以使用'cowboy_rest',例如:https://github.com/extend/cowboy/blob/master/examples/rest_pastebin/src/toppage_handler.erl

它为您提供了一种更有条理的方式来处理请求。

更多信息:http://ninenines.eu/docs/en/cowboy/HEAD/manual/cowboy_rest/

答案 2 :(得分:0)

您可以使用cowboy_rest,实现content_types_accepted / 2回调方法,如下所示:

 content_types_accepted(Req, State) ->
       case cowboy_req:method(Req) of
         {<<"POST">>, _ } ->
           Accepted = {[{<<"application/x-www-form-urlencoded">>, put_file}], Req, State};
         {<<"PUT">>, _ } ->
           Accepted = {[{<<"application/x-www-form-urlencoded">>, post_file}], Req, State}
       end,
 Accepted.

我认为这样你可以为不同的HTTP动词/方法提供单独的处理程序。这也为你提供了更清晰的代码:)

各种处理程序:

put_file(Req, State) ->

  {true, Req, State}.

post_file(Req, State) ->

  {true, Req, State}.

答案 3 :(得分:0)

这是一个将该方法附加到您的处理程序的牛仔中间件:

即。您的handler将成为handler_post

-module(middleware).

-export([execute/2]).

execute(Req0, Env0) ->
    {Method0, Req} = cowboy_req:method(Req0),
    Method1 = string:lowercase(Method0),
    Handler0 = proplists:get_value(handler, Env0),
    Handler = list_to_atom(atom_to_list(Handler0) ++ "_" ++ binary_to_list(Method1)),
    Env = [{handler, Handler} | proplists:delete(handler, Env0)],
    {ok, Req, Env}.
相关问题