Search code examples
perlroutesmojolicious

Expecting arguments in Mojolicious routes


I have two routes in Mojolicious app as follows:

my $route = $r->any('/api')->to('API#');

$route->get('/get_data')->to('#process_forms');
$route->get('/get_data/?file=:file&name=:name')->to('#submit_forms');

if I go to /api/get_data I get redirected to process_forms function. I want the app to take me to submit_forms function if I pass additional arguments to that same route. for example, url /api/get_data/?file=myfile&name=myname should call submit_forms function, but that's not the case here. In both scenarios, process_forms is called. What option Mojolicious routing provides to help me with this?


Solution

  • Mojo's router connects URL and HTTP request methods to controllers. The GET and POST parameters are not used in routing. This makes sense, because a URL is typically supposed to target a resource by itself.

    You have a path /get_data you need to send that to one controller. From there you want it sounds like you want to do is to go to another controller if you have GET parameters (passed in the URL). You can do this, but it's not normally what you want.

    Just putting a conditional in a controller,

    What you normally want when handling get parameters is simply to put them inside a block in the controller, IE,

    my $query = $c->req->query_params
    my $file = $query->param('foo');
    my $name = $query->param('name');
    
    if ( defined $file && defined $name) {
      # we have file and name
    }
    else {
      # or we do not
    }
    

    Redispatch

    But you can always redispatch to a different controller (manually)

    MyApp::Controller::submit_forms($self);
    

    Or, through Mojo,

    $self->routes->continue("#submit_forms")
    

    As a last idea, you can also make it that the route doesn't match if the post variables aren't there. But, I've never needed to do this.