如何在Dancer2中跳过序列化程序?

时间:2018-04-10 12:16:42

标签: perl dancer

我的应用程序配置为发送JSON响应。我需要添加一个RSS(或其他任何)端点。没有无操作的序列化程序,尽管编写一个很简单:

{ # do not use this lol
    package Dancer2::Serializer::ThisIsNotAnOkayThingToDo_Raw;
    use Moo;
    with 'Dancer2::Core::Role::Serializer';
    sub serialize { $_[1] }
    sub deserialize { $_[1] }
    1;
}

get '/mything/rss' => sub {
  my $rss = new XML::RSS (version => '2.0');
  $rss->channel(title => "Wharrgarbl");
  $rss->add_item(title => "Potato");
  send_as(ThisIsNotAnOkayThingToDo_Raw => $rss->as_string, {content_type => 'application/rss+xml; charset=UTF-8'});
}

然而,这失败了,声称未定义__PACKAGE__::send_as(但在服务器上运行perldoc Dancer2::Manual确实说send_as应该在那里。)

# __PACKAGE__ is me redacting the sensitive out of the error message
Undefined subroutine &__PACKAGE__::send_as called at...

该文档还声称send_as使用send_file,因此我试图删除中间人:

get '/mything/rss' => sub {
  my $rss = new XML::RSS (version => '2.0');
  $rss->channel(title => "Wharrgarbl");
  $rss->add_item(title => "Potato");
  my $xml = $rss->as_string;
  send_file(\$xml, content_type => 'application/rss+xml; charset=UTF-8');
}

然而,这通过序列化器:

hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this) at .../site/lib/JSON.pm line 154.

做什么?

2 个答案:

答案 0 :(得分:-1)

get '/mything/rss' => sub {
  # Calculate the result
  my $rss = ...;
  # Mark the request as successful
  status 200;
  # Be polite and set the content type
  content_type 'application/rss+xml; charset=UTF-8';
  # Jam the result straight into the response object
  response->{content} = $rss;
  # Tell Dancer internals that the response has already been encoded 
  # (this is pretty much guaranteed to break in the future, regrettably)
  response->{is_encoded} = 1;
  # and return.
  return response;
}

答案 1 :(得分:-1)

使用send_as

  

允许当前路由处理程序返回特定内容类型   客户端使用指定的序列化程序或html。

您可以使用它来指定自己的序列化程序或只使用默认的html  序列化程序,但更改rss的内容类型

use Dancer2;
set serializer => 'JSON';

get '/mything/rss' => sub {
  # Get your rss string 
  # ...
  my $xml = '<rss>content</rss>';
  send_as html => $xml , { content_type => 'application/rss+xml; charset=UTF-8' };
}

dance;