## Access request information get '/agent' => sub ($c) { my $host = $c->req->url->to_abs->host; my $ua = $c->req->headers->user_agent; $c->render(text =>"Request by $ua reached $host."); };
## Echo the request body and send custom header with response post '/echo' => sub ($c) { $c->res->headers->header('X-Bender' => 'Bite my shiny metal ass!'); $c->render(data => $c->req->body); };
app->start;
如, 这里获取访问的主机, 以及 user agent.
JSON
可查看 Mojo::JSON 来获取更多信息, 可用 Mojo::Message 和 stash value json 访问.
1 2 3 4 5 6 7 8 9 10
use Mojolicious::Lite -signatures;
## Modify the received JSON document and return it put '/reverse' => sub ($c) { my $hash = $c->req->json; $hash->{message} = reverse $hash->{message}; $c->render(json => $hash); };
app->start;
同样可以在命令行获取, 用 Mojolicious::Command::get:
1
$ ./myapp.pl get -M PUT -c '{"message":"Hello Mojo!"}' /reverse
内置的 exception 和 not-found pages
应对 404, 500 等. 其会提供一些有用的信息:
1 2 3 4 5 6 7 8 9 10 11
use Mojolicious::Lite -signatures;
## Not found (404) get '/missing' => sub ($c) { $c->render(template =>'does_not_exist'); };
## Exception (500) get '/dies' => sub{ die'Intentional error' };
app->start;
同样可以用 Mojolicious::Command::get 在命令行测试:
1
$ ./myapp.pl get /dies '##error'
路由名 Route names
似乎可以用 link_to 来添加超链接.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
use Mojolicious::Lite -signatures;
## Render the template "index.html.ep" get '/' => sub ($c) { $c->render; } => 'index';
## Render the template "hello.html.ep" get '/hello';
## Return configured foo value, or default if no configuration file get '/foo' => sub ($c) { my $foo = $c->app->config('foo'); $c->render(json => {foo => $foo}); };
## Global logic shared by all routes under sub ($c) { return1if $c->req->headers->header('X-Bender'); $c->render(text =>"You're not Bender."); returnundef; };
## Admin section group {
## Local logic shared only by routes in this group under '/admin' => sub ($c) { return1if $c->req->headers->header('X-Awesome'); $c->render(text =>"You're not awesome enough."); returnundef; };
## GET /admin/dashboard get '/dashboard' => {text =>'Nothing to see here yet.'}; };
## GET /welcome get '/welcome' => {text =>'Hi Bender.'};
## Load message into memory my $hello = app->home->child('cache', 'hello.txt')->slurp;
## Display message get '/' => sub ($c) { $c->render(text => $hello); };
状态 Conditions
Conditions 如 agent 和 host, 允许更强大的路由结构:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
use Mojolicious::Lite -signatures;
## Firefox get '/foo' => (agent => qr/Firefox/) => sub ($c) { $c->render(text =>'Congratulations, you are using a cool browser.'); };
## Internet Explorer get '/foo' => (agent => qr/Internet Explorer/) => sub ($c) { $c->render(text =>'Dude, you really need to upgrade to Firefox.'); };
## http://mojolicious.org/bar get '/bar' => (host =>'mojolicious.org') => sub ($c) { $c->render(text =>'Hello Mojolicious.'); };