在Erlang httpd中访问POST请求的主体

时间:2016-08-01 09:21:52

标签: erlang

我收到一个带有表示JSON对象的字符串的POST请求。

_Env列表如下所示:

[
  {server_software,"inets/6.3"},
  {server_name,"XTR20160414"},
  {gateway_interface,"CGI/1.1"},
  {server_protocol,"HTTP/1.1"},
  {server_port,9000},
  {request_method,"POST"},
  {remote_addr,"127.0.0.1"},
  {peer_cert,undefined},
  {script_name,"/api/server:auth"},
  {http_host,"localhost:9000"},
  {http_accept,"application/json"},
  {http_content_type,"application/json"},
  {http_content_length,"34"},
  {http_connection,"close"},
  {content_length,34}
]

启动服务器的代码是:

start() ->
    mnesia:start(),
    inets:start(httpd, [
        {modules, [
            mod_alias,
            mod_auth,
            mod_esi,
            mod_actions,
            mod_cgi,
            mod_dir,
            mod_get,
            mod_head,
            mod_log,
            mod_disk_log
        ]},
        {port, 9000},
        {server_name, "pokerspace"},
        {server_root, "misc/log"},
        {document_root, "misc/www"},
        {erl_script_alias, {"/api", [server]}},
        {error_log, "error.log"},
        {security_log, "security.log"},
        {transfer_log, "transfer.log"},
        {mime_types, [
            {"json", "application/json"},
            {"html", "text/html"},
            {"css", "text/css"},
            {"js", "application/x-javascript"}
        ]}
    ]).

然后我向这个网址发出POST请求,里面有一些数据:

http://localhost:9000/api/server:auth

使用以下代码处理此请求:

auth(SessionID, _Env, _Input) ->
    mod_esi:deliver(SessionID, [
        text_header(),
        "authenticated"
    ]).

我看到content_length是34,看起来是正确的数字,所以数据似乎正在进入。

现在,如何提取已发布的数据以便用它进行处理?

1 个答案:

答案 0 :(得分:1)

POST主体作为mod_esi docs中提到的第三个参数传递给回调函数。

这将返回与自身连接的传入主体:

auth(SessionID, _Env, Input) ->
    mod_esi:deliver(SessionID, [
        Input, Input
    ]).

演示:

$ curl -XPOST -d "hi" http://localhost:9000/api/server:auth
hihi