This is only the first of the Mojolicious::Guides. Other guides delve deeper into topics like growing a Mojolicious::Lite prototype into a well-structured Mojolicious application, routing, rendering and more. It is highly encouraged that readers continue on to the remaining guides after reading this one.
#!/usr/bin/env perl use Mojolicious::Lite; get '/' => sub { my $c = shift; $c->render(text => 'Hello World!'); }; app->start;
With Mojolicious::Command::Author::generate::lite_app there is also a helper command to generate a small example application.
$ mojo generate lite_app myapp.pl
$ ./myapp.pl daemon Server available at http://127.0.0.1:3000 $ ./myapp.pl daemon -l http://*:8080 Server available at http://127.0.0.1:8080 $ ./myapp.pl cgi ...CGI output... $ ./myapp.pl get / Hello World! $ ./myapp.pl ...List of available commands (or automatically detected environment)...
A call to ``start'' in Mojolicious ("app->start"), which starts the command system, should be the last expression in your application, because its return value can be significant.
# Use @ARGV to pick a command app->start; # Start the "daemon" command app->start('daemon', '-l', 'http://*:8080');
$ morbo ./myapp.pl Server available at http://127.0.0.1:3000
For more information about how to deploy your application see also ``DEPLOYMENT'' in Mojolicious::Guides::Cookbook.
use Mojolicious::Lite; # Route leading to an action that renders some text get '/foo' => sub { my $c = shift; $c->render(text => 'Hello World!'); }; app->start;
Response content is often generated by actions with ``render'' in Mojolicious::Controller, but more about that later.
use Mojolicious::Lite; # /foo?user=sri get '/foo' => sub { my $c = shift; my $user = $c->param('user'); $c->render(text => "Hello $user."); }; app->start;
use Mojolicious::Lite; # Route leading to an action that renders a template get '/foo' => sub { my $c = shift; $c->stash(one => 23); $c->render(template => 'magic', two => 24); }; app->start; __DATA__ @@ magic.html.ep The magic numbers are <%= $one %> and <%= $two %>.
For more information about templates see also ``Embedded Perl'' in Mojolicious::Guides::Rendering.
use Mojolicious::Lite; # Access request information get '/agent' => sub { my $c = shift; 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 { my $c = shift; $c->res->headers->header('X-Bender' => 'Bite my shiny metal ass!'); $c->render(data => $c->req->body); }; app->start;
You can test the more advanced examples right from the command line with Mojolicious::Command::get.
$ ./myapp.pl get -v -M POST -c 'test' /echo
use Mojolicious::Lite; # Modify the received JSON document and return it put '/reverse' => sub { my $c = shift; my $hash = $c->req->json; $hash->{message} = reverse $hash->{message}; $c->render(json => $hash); }; app->start;
You can send JSON documents from the command line with Mojolicious::Command::get.
$ ./myapp.pl get -M PUT -c '{"message":"Hello Mojo!"}' /reverse
use Mojolicious::Lite; # Not found (404) get '/missing' => sub { shift->render(template => 'does_not_exist') }; # Exception (500) get '/dies' => sub { die 'Intentional error' }; app->start;
You can even use CSS selectors with Mojolicious::Command::get to extract only the information you're actually interested in.
$ ./myapp.pl get /dies '#error'
And don't worry about revealing too much information on these pages, they are only available during development, and will be replaced automatically with pages that don't reveal any sensitive information in a production environment.
use Mojolicious::Lite; # Render the template "index.html.ep" get '/' => sub { my $c = shift; $c->render; } => 'index'; # Render the template "hello.html.ep" get '/hello'; app->start; __DATA__ @@ index.html.ep <%= link_to Hello => 'hello' %>. <%= link_to Reload => 'index' %>. @@ hello.html.ep Hello World!
Nameless routes get an automatically generated one assigned that is simply equal to the route itself without non-word characters.
use Mojolicious::Lite; get '/with_layout'; app->start; __DATA__ @@ with_layout.html.ep % title 'Green'; % layout 'green'; Hello World! @@ layouts/green.html.ep <!DOCTYPE html> <html> <head><title><%= title %></title></head> <body><%= content %></body> </html>
The stash or helpers like ``title'' in Mojolicious::Plugin::DefaultHelpers can be used to pass additional data to the layout.
use Mojolicious::Lite; get '/with_block' => 'block'; app->start; __DATA__ @@ block.html.ep % my $link = begin % my ($url, $name) = @_; Try <%= link_to $url => begin %><%= $name %><% end %>. % end <!DOCTYPE html> <html> <head><title>Sebastians frameworks</title></head> <body> %= $link->('http://mojolicious.org', 'Mojolicious') %= $link->('http://catalystframework.org', 'Catalyst') </body> </html>
use Mojolicious::Lite; # A helper to identify visitors helper whois => sub { my $c = shift; my $agent = $c->req->headers->user_agent || 'Anonymous'; my $ip = $c->tx->remote_address; return "$agent ($ip)"; }; # Use helper in action and template get '/secret' => sub { my $c = shift; my $user = $c->whois; $c->app->log->debug("Request from $user"); }; app->start; __DATA__ @@ secret.html.ep We know who you are <%= whois %>.
A list of all built-in ones can be found in Mojolicious::Plugin::DefaultHelpers and Mojolicious::Plugin::TagHelpers.
use Mojolicious::Lite; # /foo/test # /foo/test123 get '/foo/:bar' => sub { my $c = shift; my $bar = $c->stash('bar'); $c->render(text => "Our :bar placeholder matched $bar"); }; # /testsomething/foo # /test123something/foo get '/<:bar>something/foo' => sub { my $c = shift; my $bar = $c->param('bar'); $c->render(text => "Our :bar placeholder matched $bar"); }; app->start;
To separate them from the surrounding text, you can surround your placeholders with "<" and ">", which also makes the colon prefix optional.
use Mojolicious::Lite; # /hello/test # /hello/test.html get '/hello/#you' => 'groovy'; app->start; __DATA__ @@ groovy.html.ep Your name is <%= $you %>.
use Mojolicious::Lite; # /hello/test # /hello/test123 # /hello/test.123/test/123 get '/hello/*you' => 'groovy'; app->start; __DATA__ @@ groovy.html.ep Your name is <%= $you %>.
use Mojolicious::Lite; # GET /hello get '/hello' => sub { my $c = shift; $c->render(text => 'Hello World!'); }; # PUT /hello put '/hello' => sub { my $c = shift; 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 { my $c = shift; $c->render(text => 'Bye World!'); }; # * /whatever any '/whatever' => sub { my $c = shift; my $method = $c->req->method; $c->render(text => "You called /whatever with $method."); }; app->start;
use Mojolicious::Lite; # /hello # /hello/Sara get '/hello/:name' => {name => 'Sebastian', day => 'Monday'} => sub { my $c = shift; $c->render(template => 'groovy', format => 'txt'); }; app->start; __DATA__ @@ groovy.txt.ep My name is <%= $name %> and it is <%= $day %>.
Default values that don't belong to a placeholder simply get merged into the stash all the time.
use Mojolicious::Lite; # /test # /123 any '/:foo' => [foo => ['test', '123']] => sub { my $c = shift; my $foo = $c->param('foo'); $c->render(text => "Our :foo placeholder matched $foo"); }; app->start;
All placeholders get compiled to a regular expression internally, this process can also be customized. Just make sure not to use "^" and "$", or capturing groups "(...)", non-capturing groups "(?:...)" are fine though.
use Mojolicious::Lite; # /1 # /123 any '/:bar' => [bar => qr/\d+/] => sub { my $c = shift; my $bar = $c->param('bar'); $c->render(text => "Our :bar placeholder matched $bar"); }; app->start;
You can take a closer look at all the generated regular expressions with the command Mojolicious::Command::routes.
$ ./myapp.pl routes -v
use Mojolicious::Lite; # Authenticate based on name parameter under sub { my $c = shift; # Authenticated my $name = $c->param('name') || ''; return 1 if $name eq 'Bender'; # Not authenticated $c->render(template => 'denied'); return undef; }; # Only reached when authenticated get '/' => 'index'; app->start; __DATA__ @@ denied.html.ep You are not Bender, permission denied. @@ index.html.ep Hi Bender.
Prefixing multiple routes is another good use for it.
use Mojolicious::Lite; # /foo under '/foo'; # /foo/bar get '/bar' => {text => 'foo bar'}; # /foo/baz get '/baz' => {text => 'foo baz'}; # / (reset) under '/' => {msg => 'whatever'}; # /bar get '/bar' => {inline => '<%= $msg %> works'}; app->start;
You can also group related routes with ``group'' in Mojolicious::Lite, which allows nesting of routes generated with ``under'' in Mojolicious::Lite.
use Mojolicious::Lite; # Global logic shared by all routes under sub { my $c = shift; return 1 if $c->req->headers->header('X-Bender'); $c->render(text => "You're not Bender."); return undef; }; # Admin section group { # Local logic shared only by routes in this group under '/admin' => sub { my $c = shift; return 1 if $c->req->headers->header('X-Awesome'); $c->render(text => "You're not awesome enough."); return undef; }; # GET /admin/dashboard get '/dashboard' => {text => 'Nothing to see here yet.'}; }; # GET /welcome get '/welcome' => {text => 'Hi Bender.'}; app->start;
use Mojolicious::Lite; # /detection # /detection.html # /detection.txt get '/detection' => sub { my $c = shift; $c->render(template => 'detected'); }; app->start; __DATA__ @@ detected.html.ep <!DOCTYPE html> <html> <head><title>Detected</title></head> <body>HTML was detected.</body> </html> @@ detected.txt.ep TXT was detected.
The default format is "html", and restrictive placeholders can be used to limit possible values.
use Mojolicious::Lite; # /hello.json # /hello.txt get '/hello' => [format => ['json', 'txt']] => sub { my $c = shift; return $c->render(json => {hello => 'world'}) if $c->stash('format') eq 'json'; $c->render(text => 'hello world'); }; app->start;
Or you can just disable format detection with a special type of restrictive placeholder.
use Mojolicious::Lite; # /hello get '/hello' => [format => 0] => {text => 'No format detection.'}; # Disable detection and allow the following routes to re-enable it on demand under [format => 0]; # /foo get '/foo' => {text => 'No format detection again.'}; # /bar.txt get '/bar' => [format => 'txt'] => {text => ' Just one format.'}; app->start;
use Mojolicious::Lite; # /hello (Accept: application/json) # /hello (Accept: application/xml) # /hello.json # /hello.xml # /hello?format=json # /hello?format=xml get '/hello' => sub { my $c = shift; $c->respond_to( json => {json => {hello => 'world'}}, xml => {text => '<hello>world</hello>'}, any => {data => '', status => 204} ); }; app->start;
MIME type mappings can be extended or changed easily with ``types'' in Mojolicious.
app->types->type(rdf => 'application/rdf+xml');
use Mojolicious::Lite; app->start; __DATA__ @@ something.js alert('hello!'); @@ test.txt (base64) dGVzdCAxMjMKbGFsYWxh
External static files are not limited to a single file extension and will be served automatically from a "public" directory if it exists.
$ mkdir public $ mv something.js public/something.js $ mv mojolicious.tar.gz public/mojolicious.tar.gz
Both have a higher precedence than routes for "GET" and "HEAD" requests. Content negotiation with "Range", "If-None-Match" and "If-Modified-Since" headers is supported as well and can be tested very easily with Mojolicious::Command::get.
$ ./myapp.pl get /something.js -v -H 'Range: bytes=2-4'
$ mkdir -p templates/foo $ echo 'Hello World!' > templates/foo/bar.html.ep
They have a higher precedence than templates in the "DATA" section.
use Mojolicious::Lite; # Render template "templates/foo/bar.html.ep" any '/external' => sub { my $c = shift; $c->render(template => 'foo/bar'); }; app->start;
$ mkdir cache $ echo 'Hello World!' > cache/hello.txt
There are many useful methods Mojo::Home inherits from Mojo::File, like ``child'' in Mojo::File and ``slurp'' in Mojo::File, that will help you keep your application portable across many different operating systems.
use Mojolicious::Lite; # Load message into memory my $hello = app->home->child('cache', 'hello.txt')->slurp; # Display message get '/' => sub { my $c = shift; $c->render(text => $hello); };
You can also introspect your application from the command line with Mojolicious::Command::eval.
$ ./myapp.pl eval -v 'app->home'
use Mojolicious::Lite; # Firefox get '/foo' => (agent => qr/Firefox/) => sub { my $c = shift; $c->render(text => 'Congratulations, you are using a cool browser.'); }; # Internet Explorer get '/foo' => (agent => qr/Internet Explorer/) => sub { my $c = shift; $c->render(text => 'Dude, you really need to upgrade to Firefox.'); }; # http://mojolicious.org/bar get '/bar' => (host => 'mojolicious.org') => sub { my $c = shift; $c->render(text => 'Hello Mojolicious.'); }; app->start;
use Mojolicious::Lite; # Access session data in action and template get '/counter' => sub { my $c = shift; $c->session->{counter}++; }; app->start; __DATA__ @@ counter.html.ep Counter: <%= session 'counter' %>
Note that you should use custom ``secrets'' in Mojolicious to make signed cookies really tamper resistant.
app->secrets(['My secret passphrase here']);
use Mojolicious::Lite; # Upload form in DATA section get '/' => 'form'; # Multipart upload handler post '/upload' => sub { my $c = shift; # Check file size return $c->render(text => 'File is too big.', status => 200) if $c->req->is_limit_exceeded; # Process uploaded file return $c->redirect_to('form') unless my $example = $c->param('example'); my $size = $example->size; my $name = $example->filename; $c->render(text => "Thanks for uploading $size byte file $name."); }; app->start; __DATA__ @@ form.html.ep <!DOCTYPE html> <html> <head><title>Upload</title></head> <body> %= form_for upload => (enctype => 'multipart/form-data') => begin %= file_field 'example' %= submit_button 'Upload' % end </body> </html>
To protect you from excessively large files there is also a limit of 16MiB by default, which you can tweak with the attribute ``max_request_size'' in Mojolicious.
# Increase limit to 1GiB app->max_request_size(1073741824);
use Mojolicious::Lite; # Blocking get '/headers' => sub { my $c = shift; my $url = $c->param('url') || 'https://mojolicious.org'; my $dom = $c->ua->get($url)->result->dom; $c->render(json => $dom->find('h1, h2, h3')->map('text')->to_array); }; # Non-blocking get '/title' => sub { my $c = shift; $c->ua->get('mojolicious.org' => sub { my ($ua, $tx) = @_; $c->render(data => $tx->result->dom->at('title')->text); }); }; # Concurrent non-blocking get '/titles' => sub { my $c = shift; my $mojo = $c->ua->get_p('https://mojolicious.org'); my $cpan = $c->ua->get_p('https://metacpan.org'); Mojo::Promise->all($mojo, $cpan)->then(sub { my ($mojo, $cpan) = @_; $c->render(json => { mojo => $mojo->[0]->result->dom->at('title')->text, cpan => $cpan->[0]->result->dom->at('title')->text }); })->wait; }; app->start;
For more information about the user agent see also ``USER AGENT'' in Mojolicious::Guides::Cookbook.
use Mojolicious::Lite; websocket '/echo' => sub { my $c = shift; $c->on(json => sub { my ($c, $hash) = @_; $hash->{msg} = "echo: $hash->{msg}"; $c->send({json => $hash}); }); }; get '/' => 'index'; app->start; __DATA__ @@ index.html.ep <!DOCTYPE html> <html> <head> <title>Echo</title> <script> var ws = new WebSocket('<%= url_for('echo')->to_abs %>'); ws.onmessage = function (event) { document.body.innerHTML += JSON.parse(event.data).msg; }; ws.onopen = function (event) { ws.send(JSON.stringify({msg: 'I ♥ Mojolicious!'})); }; </script> </head> </html>
For more information about real-time web features see also ``REAL-TIME WEB'' in Mojolicious::Guides::Cookbook.
use Mojolicious::Lite; # Prepare mode specific message during startup my $msg = app->mode eq 'development' ? 'Development!' : 'Something else!'; get '/' => sub { my $c = shift; $c->app->log->debug('Rendering mode specific message'); $c->render(text => $msg); }; app->log->debug('Starting application'); app->start;
The default operating mode will usually be "development" and can be changed with command line options or the "MOJO_MODE" and "PLACK_ENV" environment variables. A mode other than "development" will raise the log level from "debug" to "info".
$ ./myapp.pl daemon -m production
All messages will be written to "STDERR" or a "log/$mode.log" file if a "log" directory exists.
$ mkdir log
Mode changes also affect a few other aspects of the framework, such as the built-in "exception" and "not_found" pages. Once you switch modes from "development" to "production", no sensitive information will be revealed on those pages anymore.
use Test::More; use Mojo::File 'path'; use Test::Mojo; # Portably point to "../myapp.pl" my $script = path(__FILE__)->dirname->sibling('myapp.pl'); my $t = Test::Mojo->new($script); $t->get_ok('/')->status_is(200)->content_like(qr/Funky/); done_testing();
Just run your tests with prove.
$ prove -l -v $ prove -l -v t/basic.t