Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

change serializer in Dancer2 according to request param

by perl_help27 (Acolyte)
on Apr 12, 2018 at 15:56 UTC ( #1212738=perlquestion: print w/replies, xml ) Need Help??
perl_help27 has asked for the wisdom of the Perl Monks concerning the following question:

Hello again, I am trying to switch between json and xml serializers in my Dancer2 app. Like change my serializer dynamically in my app. This is my code:

hook before => sub { set serializer => ( request->params->{format} eq 'xml' ? 'XML' : ' +JSON'); };

However, the first request always operates based on the old serializer so I have to call the request twice in a row to get the response using the correct serializer. If you can please help me with that. Thanks

Replies are listed 'Best First'.
Re: change serializer in Dancer2 according to request param
by Anonymous Monk on Apr 12, 2018 at 16:56 UTC
    ?Try use Mutable, in hook set req header based on param?
      Can you please provide me with a small example? Thank you


        No. Serializer is too much magic for me, cant hunt all the docs to figure it out, so why bother

        #!/usr/bin/perl -- use strict; use warnings; use Dancer2; sub con_serv { my( $type, $ref ) = @_; content_type('text/x-json'); require JSON::MaybeXS; return JSON::MaybeXS::encode_json($ref); } get '/always/json' => sub { con_serv( 'json', { get => '/always/json' + } ); }; get '/:type' => sub { con_serv( request->params->{type} , { get + => '/:type' } ); }; get '/' => sub { ' <html> <pre> <a href="/">/</a> <a href="/always/json">/always/json</a> <a href="/json">/json</a> ' }; dance; __END__

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1212738]
Front-paged by Discipulus
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2018-11-20 19:49 GMT
Find Nodes?
    Voting Booth?
    My code is most likely broken because:

    Results (231 votes). Check out past polls.