【问题标题】:How do I skip the serializer in Dancer2?如何跳过 Dancer2 中的序列化程序?
【发布时间】:2023-04-10 22:38:01
【问题描述】:

我的应用程序配置为发送 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.

做什么?

【问题讨论】:

    标签: perl dancer


    【解决方案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;
    }
    

    【讨论】:

    • 这个答案其实是Erik Jan Vos找到的,请把宝贵的网络业力发给他
    • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值
    【解决方案2】:

    使用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;
    

    【讨论】:

    • send_as 实际上是我在问题中尝试的第一件事。
    • 您可以让示例代码在您的应用程序之外运行吗?给定的示例应该是一个完整的 dancer2 应用程序。为了检查问题是否与您的 Dancer2 安装或您的应用程序中的某些问题有关
    猜你喜欢
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 2016-10-18
    • 2012-03-09
    相关资源
    最近更新 更多