Skip to content

Instantly share code, notes, and snippets.

@jberger
Created October 20, 2021 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jberger/7288ac23b2d44c05f6d7d2b24a6c7a52 to your computer and use it in GitHub Desktop.
Save jberger/7288ac23b2d44c05f6d7d2b24a6c7a52 to your computer and use it in GitHub Desktop.
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