Created
October 20, 2021 16:08
-
-
Save jberger/7288ac23b2d44c05f6d7d2b24a6c7a52 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Mojolicious::Plugin::RequestNegotiation; | |
use Mojo::Base 'Mojolicious::Plugin'; | |
use Carp (); | |
sub register { | |
my ($plugin, $app, $conf) = @_; | |
$app->helper(sent => \&_sent); | |
$app->helper(when_sent => \&_when_sent); | |
} | |
sub _sent { | |
my $c = shift; | |
my $got = $c->req->headers->content_type; | |
my @exts = @{$c->app->types->detect($got, 1)}; | |
return \@exts unless @_; | |
# Find best representation | |
for my $ext (@exts) { $ext eq $_ and return $ext for @_ } | |
return @exts ? undef : shift; | |
} | |
sub _when_sent { | |
my ($c, $actions) = (shift, ref $_[0] ? $_[0] : {@_}); | |
for my $type (@{_sent($c)}, 'any') { | |
if (my $action = $actions->{$type}) { | |
return $c->$action(); | |
} | |
} | |
Carp::croak 'No handler was found, perhaps you want to include "any"?'; | |
} | |
1; | |
=head1 NAME | |
Mojolicious::Plugin::RequestNegotiation - Like content negotiation but for the request | |
=head1 SYNOPSIS | |
=head1 DESCRIPTION | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment