催化剂请求对象json输入

时间:2013-10-16 21:19:54

标签: json catalyst

示例代码:

sub record_put :Private {
    my ( $self, $c, @args ) = @_;

    $c->log->info( join ', ', %{ $c->request->headers } ) ;
    $c->log->info( $c->request->body ) ;

    $c->response->body( $c->request->body ) ;
}

这是日志数据:

[info] user-agent, Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/28.0.1500.71 Chrome/28.0.1500.71 Safari/537.36, connection, keep-alive, accept, application/json, text/javascript, */*; q=0.01, accept-language, en-US,en;q=0.8, x-requested-with, XMLHttpRequest, origin, http://localhost:3000, accept-encoding, gzip,deflate,sdch, content-length, 125, host, localhost:3000, ::std_case, HASH(0xaec0ba0), content-type, application/json, referer, http://localhost:3000/test
[info] /tmp/PM2C6FXpcC

以下是Catalyst::Request文档中的一小段文字:

$req->body

Returns the message body of the request, as returned by HTTP::Body: a string, unless Content-Type is application/x-www-form-urlencoded, text/xml, or multipart/form-data, in which case a File::Temp object is returned.

File::Temp联机帮助页无效。即使'对象'重载其字符串化,我也看不到如何提取内容。

2 个答案:

答案 0 :(得分:1)

以下是我使用的内容:

  my $rbody = $c->req->body;
  if ($rbody) {
    # Post requests are stored on the filesystem under certain obscure conditions,                                                                           
    # in which case $rbody is a filehandle pointing to the temporary file      
    if (ref $rbody) {           # a filehandle                                 
      $content = join "", readline($rbody);
      close $rbody;
      unlink "$rbody";  # filehandle stringifies to name of temp file          
    } else {                    # a string                                     
      $content = $rbody;
    }
  }

body方法返回的内容代表一个临时文件,可以像文件句柄或字符串一样对待。如果你把它当成文件句柄,它会从临时文件中读取;如果像字符串一样使用,则其值是临时文件的名称。我使用了很少见的内置函数readline,它与更常见的<…>运算符相同。

我不希望else路径被采用,但是它是防御性的,因为你永远不会知道。

新增2014-06-09:你需要明确关闭;否则代码有文件描述符泄漏。 Catalyst开发者声称应该自动清理句柄,但事实并非如此。

答案 1 :(得分:0)

如果你只是想解析JSON,那么最新的稳定Catalyst有一个方法'body_data'可以为你做这个(参见:http://www.catalystframework.org/calendar/2013/6