| 1 | 1 | ▶ | use v5.40; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 2 | 1 | ▶ | use experimental 'signatures'; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 3 | 1 | ▶ | use FindBin (); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | 1 | ▶ | use lib "$FindBin::Bin/lib"; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 5 | 1 | ▶ | use PAGI::Nano; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 6 | 1 | ▶ | use Example::Middleware::ApiKey; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 7 | |||
| 8 | # Write your own middleware and wire it two ways. A middleware is any object that | ||
| 9 | # subclasses PAGI::Middleware and implements wrap($app) (see ./lib/Example/ | ||
| 10 | # Middleware/). They compose as an onion: app-wide outermost, route innermost. | ||
| 11 | # | ||
| 12 | # - RequestTimer (app-wide): injects an X-Response-Time-Ms header on every | ||
| 13 | # response by wrapping the send channel. enable resolves a bare name under | ||
| 14 | # PAGI::Middleware::, so a leading ^ escapes the prefix for our own class. | ||
| 15 | # - ApiKey (route-scoped): rejects requests without the right X-Api-Key with a | ||
| 16 | # 401 before the handler runs. It takes a configured key, so it is | ||
| 17 | # pre-instantiated (route-scoped middleware take no constructor args). | ||
| 18 | # | ||
| 19 | # pagi-server app.pl | ||
| 20 | # curl -i http://127.0.0.1:5000/public # 200, X-Response-Time-Ms header | ||
| 21 | # curl -i http://127.0.0.1:5000/private # 401 | ||
| 22 | # curl -i -H 'X-Api-Key: s3cr3t' http://127.0.0.1:5000/private # 200 | ||
| 23 | |||
| 24 | 1 | ▶ | my $app = app { |
|
Subroutine
__ANON__: called CC=1 SCAR=0.0
| |||
| 25 | 1 | enable '^Example::Middleware::RequestTimer'; # app-wide; ^ escapes the default prefix | |
| 26 | |||
| 27 | 1 | ▶ | get '/public' => sub ($c) { { open => 1 } }; |
|
Subroutine
__ANON__: called CC=1 SCAR=0.0
| |||
| 28 | |||
| 29 | 1 | ▶ | get '/private' => [ Example::Middleware::ApiKey->new(key => 's3cr3t') ] => sub ($c) { |
|
Subroutine
__ANON__: called CC=1 SCAR=0.0
| |||
| 30 | 1 | { secret => 'the answer is 42' }; | |
| 31 | 1 | }; | |
| 32 | 1 | }; | |
| 33 | |||
| 34 | 1 | $app; | |