NAME

PAGI::Middleware::ContentNegotiation - HTTP content negotiation middleware

SYNOPSIS

use PAGI::Middleware::Builder;

my $app = builder {
    enable 'ContentNegotiation',
        supported_types => ['application/json', 'text/html', 'text/plain'],
        default_type => 'application/json';
    $my_app;
};

# In your app:
async sub app {
    my ($scope, $receive, $send) = @_;

    my $preferred = $scope->{'pagi.preferred_content_type'};
    if ($preferred eq 'application/json') {
        # Return JSON
    } else {
        # Return HTML
    }
}

DESCRIPTION

PAGI::Middleware::ContentNegotiation parses the Accept header and determines the best content type to return. It adds the preferred type to the scope for the application to use.

CONFIGURATION

  • supported_types (required)

    Array of MIME types the application supports.

  • default_type (optional)

    Default type when no Accept header or no match. Defaults to first supported type.

  • strict (default: 0)

    If true, return 406 Not Acceptable when no supported type matches.

SCOPE EXTENSIONS

This middleware adds the following to $scope:

  • pagi.preferred_content_type

    The best matching MIME type from the supported types.

  • pagi.accepted_types

    Array of parsed Accept header entries, sorted by quality value.

ACCEPT HEADER PARSING

The Accept header is parsed according to RFC 7231:

Accept: text/html, application/json;q=0.9, */*;q=0.1

Higher quality values (q) indicate higher preference. The default is q=1.0.

SEE ALSO

PAGI::Middleware - Base class for middleware