| 1 | package PAGI::App::NotFound; | ||
| 2 | $PAGI::App::NotFound::VERSION = '0.002001'; | ||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use Future::AsyncAwait; | ||
| 6 | use PAGI::Response; | ||
| 7 | |||
| 8 | =head1 NAME | ||
| 9 | |||
| 10 | PAGI::App::NotFound - Customizable 404 response | ||
| 11 | |||
| 12 | =head1 SYNOPSIS | ||
| 13 | |||
| 14 | # A fixed 404 is just a response value (preferred): | ||
| 15 | use PAGI::Response; | ||
| 16 | $router->mount('/missing' => PAGI::Response->text('Not Found')->status(404)); | ||
| 17 | |||
| 18 | # PAGI::App::NotFound is for a computed body or custom defaults | ||
| 19 | # (e.g. a Cascade fallback): | ||
| 20 | use PAGI::App::NotFound; | ||
| 21 | my $app = PAGI::App::NotFound->new( | ||
| 22 | status => 404, | ||
| 23 | content_type => 'text/html', | ||
| 24 | body => sub { my ($scope) = @_; render_404($scope) }, | ||
| 25 | )->to_app; | ||
| 26 | |||
| 27 | =cut | ||
| 28 | |||
| 29 | sub new { | ||
| 30 | my ($class, %args) = @_; | ||
| 31 | |||
| 32 | return bless { | ||
| 33 | body => $args{body} // 'Not Found', | ||
| 34 | content_type => $args{content_type} // 'text/plain', | ||
| 35 | status => $args{status} // 404, | ||
| 36 | }, $class; | ||
| 37 | } | ||
| 38 | |||
| 39 | sub to_app { | ||
| 40 | my ($self) = @_; | ||
| 41 | |||
| 42 | my $body = $self->{body}; | ||
| 43 | my $content_type = $self->{content_type}; | ||
| 44 | my $status = $self->{status}; | ||
| 45 | |||
| 46 | return async sub { | ||
| 47 | my ($scope, $receive, $send) = @_; | ||
| 48 | my $b = ref $body eq 'CODE' ? $body->($scope) : $body; | ||
| 49 | |||
| 50 | await PAGI::Response->new($scope) | ||
| 51 | ->status($status) | ||
| 52 | ->content_type($content_type) | ||
| 53 | ->send_raw($b) | ||
| 54 | ->respond($send); | ||
| 55 | }; | ||
| 56 | } | ||
| 57 | |||
| 58 | 1; | ||
| 59 | |||
| 60 | __END__ |