Search code examples
perlmojolicious

How to run Mojolicious appication under '/api' path( How to ignore some prefix in path )?


I have application it works fine. But now we decide to move it under /api path. So I use detour

my $r = $self->routes;

# Application is always under /api/v1, /api/v2 etc. path
$r =  $r->any( '/api/:api', [ api => qr/v\d+/ ] )->detour( 'MyApp' );

$r->get( '/users/me' )->to( 'user#show_me' );

But after this nothing works. Request to site.domain/api/v1 cause application to fall into endless loop.

There is also Mojolicious::Plugin::Mount but it only useful to mount another one application under specified route.

This guide also does not resolve problem.


Solution

  • This line should be fixed:

    # Application is always under /api/v1, /api/v2 etc. path
    $r =  $r->any( '/api/:api', [ api => qr/v\d+/ ] )->partial( 1 )
    

    Update
    As it was documented:

    Route has no specific end, remaining characters will be captured in path.

    If you run myapp.pl routes -v you will see:

    /api/:api        .D..  *        apiapi       ^\/api/((?^:v\d+))
       +/users/me    ....  GET      usersme      ^\/users\/me/?(?:\.([^/]+))?$
    

    When request come it will be checked against this regex:

    ^\/api/((?^:v\d+))\/users\/me/?(?:\.([^/]+))?$
    

    Where only /users/me will be captured in the path