Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

change serializer in Dancer2 according to request param

by perl_help27 (Novice)
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

        Hi,

        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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1212738]
Front-paged by Discipulus
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2018-07-22 09:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?















    Results (453 votes). Check out past polls.

    Notices?