What is the difference between two routes in Mojolicious?

120 views Asked by At

I just create two routes:

$r->any  ( '/api/v:api', [ api => qr/\d+/ ], { api => 1 } )->partial( 1 );
$r->under( '/api/v:api', [ api => qr/\d+/ ], { api => 1 } );

It seems both work same.

What is the difference under hood between them?

UPD
I have noticed that for first case (->any) link to static files are moved to /api/v1. This is noticeable when exception happen. mojo/debug template tries to load static files from /api/v1/... path and not /.... Why?

1

There are 1 answers

2
user3606329 On

The under is called before anything else. You can place authentication code inside it.

use strict;
use warnings;
use Mojolicious::Lite;

under sub {
    my $self = shift;
    my $api_key = $self->req->url->to_abs->username;
    my $api_secret = $self->req->url->to_abs->password;

    if($api_key ne "Admin" && $api_secret ne "Password123") {
        $self->res->headers->www_authenticate('Basic');
        $self->render(text => 'Error: API-Credentials are wrong', status => 401);
        # No routes will be executed
        return undef;
    }

    # Authentication with success, execute other routes
    return 1;
}

# Only executed if the url is http://Admin:[email protected]:3000
any '/' => sub  { 
    my $self = shift; 
    my $date = Mojo::Date->new; 
    $self->render(text => $date, status => 200);
}; 

It's very important that you have to place under above the routines you want to protect.