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__