问题
I am trying to put together a maintenance page in my Mojolicious app which all of my users will be shown whenever a file or DB entry is present on the server.
I know I can check for this file or entry on startup and if its there add in my 'catch all' route. However I'm not sure how to do this dynamically? I don't want to have to restart the backend whenever I want to go into maintenance.
Is there a way to add and remove routes from a hook? for example use the before dispatch hook to monitor for the file/db entry and if it exists modify the routes?
I tried this but I didn't seem to be able to access the routes from the hooked function, only in the startup function.
Thank you.
回答1:
The router is dynamic until the first request has been served, after that, the router cannot change routes (source). That said, can you not declare the route generally and just prohibit any access until that condition exists?
#!/usr/bin/env perl
use Mojolicious::Lite;
any '/' => sub { shift->render( text => 'Hello World' ) };
under sub {
unless (-e 'myfile') {
shift->render_not_found;
return 0;
}
return 1;
};
any '/protected' => sub { shift->render( text => 'I am safe' ) };
app->start;
来源:https://stackoverflow.com/questions/22291509/how-to-add-and-remove-routes-dynamically-in-mojolicious