How to add and remove routes dynamically in Mojolicious?

喜夏-厌秋 提交于 2019-12-10 10:56:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!