Mojolicious初学(七)
一、HTTP方法
前面我们已经提到了,HTTP方法有很多,包括GET、POST、PUT等,我们看一下这些方法如何在mojolicious使用:
use Mojolicious::Lite -signatures; # GET /hello get '/hello' => sub ($c) { #这是常用的GET方法 $c->render(text => 'Hello World!'); }; # PUT /hello put '/hello' => sub ($c) { #这是PUT方法,使用较少 my $size = length $c->req->body; $c->render(text => "You uploaded $size bytes to /hello."); }; # GET|POST|PATCH /bye any ['GET', 'POST', 'PATCH'] => '/bye' => sub ($c) { #这是在同一个url下可以同时使用GET、POST、PATCH方法 $c->render(text => 'Bye World!'); }; # * /whatever any '/whatever' => sub ($c) { #在any没有[]中括号的情况下,表示url可以使用所有HTTP方法。 my $method = $c->req->method; $c->render(text => "You called /whatever with $method."); }; app->start;
二、optional placeholder可选占位符
也可以叫做“带默认参数值”的占位符。当我们的url在占位符位置为空时,占位符的值为默认值:
use Mojolicious::Lite -signatures; # /hello # /hello/Sara get '/hello/:name' => {name => 'Sebastian', day => 'Monday'} => sub ($c) { #此处第一个=>后的花括号内便是默认值的写法。 $c->render(template => 'groovy', format => 'txt'); }; app->start; __DATA__ @@ groovy.txt.ep My name is <%= $name %> and it is <%= $day %>.
三、Restrictive placeholders严格占位符
严格占位符,代表着浏览器发送的url,占位符位置的值必须是route中给定的值,才算符合的情况,可以进行sub子方法内的操作:
use Mojolicious::Lite -signatures; # /test # /123 any '/:foo' => [foo => ['test', '123']] => sub ($c) { # 这里,需要关注[]中括号内的内容,foo占位符的值必须为test、123其中之一, # mojolicious后台才会返回"Our :foo placeholder matched $foo" my $foo = $c->param('foo'); $c->render(text => "Our :foo placeholder matched $foo"); }; app->start;
中括号[]中的值,我们也可以用Perl强大的正则表达式表示,但是要注意^、$、()、(?:)这四种格式不能使用:
use Mojolicious::Lite -signatures; # /1 # /123 any '/:bar' => [bar => qr/\d+/] => sub ($c) { #此处表达式表示只能使用数字填充占位符区域。 my $bar = $c->param('bar'); $c->render(text => "Our :bar placeholder matched $bar"); }; app->start;