Mojolic...Tutorial(3)
okay bestie, this is Mojolic...Tutorial(3) β the User Contributed Perl Documentation entry for Mojolicious::Guides::Tutorial, aka the get-started guide for Mojolicious. Buckle up π
π NAME π
Mojolicious::Guides::Tutorial β Get started with Mojolicious.
π TUTORIAL π
Okay so, quick example-driven introduction to the wonders of Mojolicious::Lite. Almost everything you'll learn here also applies to full Mojolicious applications. No cap.
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. iykyk π
β¨ Hello World β¨
A simple Hello World application can look like this β and bestie, when you use Mojolicious::Lite, strict, warnings, utf8 and Perl 5.16 features are automatically enabled and a few functions imported, turning your script into a full featured web application. Iconic.
#!/usr/bin/env perl
use Mojolicious::Lite -signatures;
get '/' => sub ($c) {
$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. So convenient.
$ mojo generate lite-app myapp.pl
π Commands π
Many different commands are automatically available from the command line. CGI and PSGI environments can even be detected and will usually just work without commands. Obsessed.
$ ./myapp.pl daemon
Web application available at http://127.0.0.1:3000
$ ./myapp.pl daemon -l http://*:8080
Web application 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. fr fr.
# Use @ARGV to pick a command
app->start;
# Start the "daemon" command
app->start('daemon', '-l', 'http://*:8080');
π₯ Reloading π₯
Your application will automatically reload itself if you start it with the morbo development web server, so you don't have to restart the server after every change. Main character energy.
$ morbo ./myapp.pl
Web application available at http://127.0.0.1:3000
For more information about how to deploy your application see also "DEPLOYMENT" in Mojolicious::Guides::Cookbook.
π£οΈ Routes π£οΈ
Routes are basically just fancy paths that can contain different kinds of placeholders and usually lead to an action, if they match the path part of the request URL. The first argument passed to all actions ($c) is a Mojolicious::Controller object, containing both the HTTP request and response. Periodt.
use Mojolicious::Lite -signatures;
# Route leading to an action that renders some text
get '/foo' => sub ($c) {
$c->render(text => 'Hello World!');
};
app->start;
Response content is often generated by actions with render in Mojolicious::Controller, but more about that later.
πΈ GET/POST parameters πΈ
All "GET" and "POST" parameters sent with the request are accessible via param in Mojolicious::Controller. iykyk.
use Mojolicious::Lite -signatures;
# /foo?user=sri
get '/foo' => sub ($c) {
my $user = $c->param('user');
$c->render(text => "Hello $user.");
};
app->start;
π Stash and templates π
The stash in Mojolicious::Controller is used to pass data to templates, which can be inlined in the "DATA" section. A few stash values like "template", "text" and "data" are reserved and will be used by render in Mojolicious::Controller to decide how a response should be generated. Not me loving reserved stash values.
use Mojolicious::Lite -signatures;
# Route leading to an action that renders a template
get '/foo' => sub ($c) {
$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.
π¦ HTTP π¦
req in Mojolicious::Controller and res in Mojolicious::Controller give you full access to all HTTP features and information. Slay.
use Mojolicious::Lite -signatures;
# 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;
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
β JSON β
JSON is the most commonly used data-interchange format for web services. Mojolicious loves JSON and comes with the possibly fastest pure-Perl implementation Mojo::JSON built right in, which is accessible through json in Mojo::Message as well as the reserved stash value "json". Obsessed.
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;
You can send JSON documents from the command line with Mojolicious::Command::get.
$ ./myapp.pl get -M PUT -c '{"message":"Hello Mojo!"}' /reverse
π Built-in "exception" and "not_found" pages π
During development you will encounter these pages whenever you make a mistake, they are gorgeous and contain a lot of valuable information that will aid you in debugging your application. They ate.
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;
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. Safety slay.
π Route names π
All routes can have a name associated with them, this allows automatic template detection and backreferencing with url_for in Mojolicious::Controller, on which many methods and helpers like link_to in Mojolicious::Plugin::TagHelpers rely. Iconic.
use Mojolicious::Lite -signatures;
# Render the template "index.html.ep"
get '/' => sub ($c) {
$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. Lowkey magic.
π Layouts π
Templates can have layouts too, you just select one with the helper layout in Mojolicious::Plugin::DefaultHelpers and place the result of the current template with the helper content in Mojolicious::Plugin::DefaultHelpers. So cute.
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.
π§ Blocks π§
Template blocks can be used like normal Perl functions and are always delimited by the begin and end keywords, they are the foundation for many helpers. Literally the foundation.
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://mojojs.org', 'mojo.js')
</body>
</html>
π Helpers π
Helpers are little functions you can create with the keyword helper in Mojolicious::Lite and reuse throughout your whole application, from actions to templates. Main character helpers.
use Mojolicious::Lite -signatures;
# A helper to identify visitors
helper whois => sub ($c) {
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 ($c) {
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.
π¦ Plugins π¦
Plugins are application extensions that help with code sharing and organization. You can load a plugin with the keyword plugin in Mojolicious::Lite, which can omit the Mojolicious::Plugin:: part of the name, and optionally provide configuration for the plugin. Slay.
use Mojolicious::Lite;
plugin Config => {file => '/etc/myapp.conf', default => {foo => 'bar'}};
# 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});
};
app->start;
Mojolicious::Plugin::Config is a built-in plugin which can populate config in Mojolicious using a config file. Plugins can also set up routes, hooks, handlers, or even load other plugins. A list of built-in plugins can be found at "PLUGINS" in Mojolicious::Plugins, and many more are available from CPAN β URL: https://metacpan.org/search?q=Mojolicious+Plugin. So many plug-ins, so little time.
π Placeholders π
Route placeholders allow capturing parts of a request path until a "/" or "." separator occurs, similar to the regular expression ([^/.]+). Results are accessible via stash in Mojolicious::Controller and param in Mojolicious::Controller. Vibe check: captured.
okay so hereβs the code for the basic :bar placeholder moment and the <:bar> glow-up:
use Mojolicious::Lite -signatures;
# /foo/test
# /foo/test123
get '/foo/:bar' => sub ($c) {
my $bar = $c->stash('bar');
$c->render(text => "Our :bar placeholder matched $bar");
};
# /testsomething/foo
# /test123something/foo
get '/<:bar>something/foo' => sub ($c) {
my $bar = $c->param('bar');
$c->render(text => "Our :bar placeholder matched $bar");
};
app->start;
So the whole point: if you want to keep your placeholders from blending into the text around them, wrap them in < and > β that also makes the colon prefix optional. Iconic. π
β¨ Relaxed Placeholders β¨
Relaxed placeholders are the chill ones: they match everything until a / shows up, basically the regular expression ([^/]+). Lowkey perfect for simple captures.
use Mojolicious::Lite;
# /hello/test
# /hello/test.html
get '/hello/#you' => 'groovy';
app->start;
__DATA__
@@ groovy.html.ep
Your name is <%= $you %>.
π¦ Wildcard placeholders π¦
Wildcard placeholders are feral in the best way β they match absolutely everything, including / and ., similar to the regular expression (.+). No cap, they will eat the whole URL path. π
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 %>.
π HTTP methods π
Routes can be restricted to specific request methods with different keywords, like get in Mojolicious::Lite and any in Mojolicious::Lite. Itβs giving βchoose your fighter.β βοΈ
use Mojolicious::Lite -signatures;
# GET /hello
get '/hello' => sub ($c) {
$c->render(text => 'Hello World!');
};
# PUT /hello
put '/hello' => sub ($c) {
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) {
$c->render(text => 'Bye World!');
};
# * /whatever
any '/whatever' => sub ($c) {
my $method = $c->req->method;
$c->render(text => "You called /whatever with $method.");
};
app->start;
πΈ Optional placeholders πΈ
All placeholders require a value, but by assigning them default values you can make capturing optional. Bestie, thatβs called giving yourself options. β¨
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 %>.
Default values that donβt belong to a placeholder simply get merged into the stash all the time. Theyβre just always there, main character energy. π
π Restrictive placeholders π
A very easy way to make placeholders more restrictive is alternatives: just make a list of possible values. Itβs like a VIP list but for URL chunks.
use Mojolicious::Lite -signatures;
# /test
# /123
any '/:foo' => [foo => ['test', '123']] => sub ($c) {
my $foo = $c->param('foo');
$c->render(text => "Our :foo placeholder matched $foo");
};
app->start;
All placeholders get compiled to a regular expression internally, and 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 -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;
You can take a closer look at all the generated regular expressions with the command Mojolicious::Command::routes.
$ ./myapp.pl routes -v
π§ Under π§
Authentication and code shared between multiple routes can be realized easily with routes generated by under in Mojolicious::Lite. All following routes are only evaluated if the callback returned a true value. Itβs giving gatekeeping, but make it useful. π
use Mojolicious::Lite -signatures;
# Authenticate based on name parameter
under sub ($c) {
# 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. Very βletβs keep this little family together.β π
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. Nested route lore, iykyk. π
use Mojolicious::Lite -signatures;
# Global logic shared by all routes
under sub ($c) {
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 ($c) {
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;
π Formats π
Formats can be automatically detected from file extensions like .html; theyβre used to find the right template and generate the correct Content-Type header. Use a restrictive placeholder to declare the possible values. β¨
use Mojolicious::Lite -signatures;
# /detection.html
# /detection.txt
get '/detection' => [format => ['html', 'txt']] => sub ($c) {
$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.
And just like with placeholders, you can use a default value to make the format optional. Flexible format queen behavior. π
use Mojolicious::Lite -signatures;
# /hello
# /hello.json
# /hello.txt
get '/hello' => [format => ['json', 'txt']] => {format => 'txt'} => sub ($c) {
return $c->render(json => {hello => 'world'}) if $c->stash('format') eq 'json';
$c->render(text => 'hello world');
};
app->start;
The default format is html, and the renderer will fall back to it when necessary.
π¦ Content negotiation π¦
For resources with different representations and that require truly RESTful content negotiation, you can also use respond_to in Mojolicious::Plugin::DefaultHelpers. Very demure, very RESTful. π
use Mojolicious::Lite -signatures;
# /hello (Accept: application/json)
# /hello (Accept: application/xml)
# /hello.json
# /hello.xml
# /hello?_format=json
# /hello?_format=xml
get '/hello' => [format => ['json', 'xml']] => {format => undef} => sub ($c) {
$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');
π Static files π
Similar to templates, but with only a single file extension and optional Base64 encoding, static files can be inlined in the DATA section and are served automatically. Convenient? Obsessed. π₯
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'
π External templates π
External templates will be searched by the renderer in a templates directory if it exists. Folder structure slay.
$ 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 -signatures;
# Render template "templates/foo/bar.html.ep"
any '/external' => sub ($c) {
$c->render(template => 'foo/bar');
};
app->start;
π Home π
You can use home in Mojolicious to interact with the directory your application considers its home. This is the directory it will search for public and templates directories, but you can use it to store all sorts of application specific data. Itβs your appβs little apartment. ποΈ
$ 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. Cross-platform bestie behavior. π
use Mojolicious::Lite -signatures;
# Load message into memory
my $hello = app->home->child('cache', 'hello.txt')->slurp;
# Display message
get '/' => sub ($c) {
$c->render(text => $hello);
};
You can also introspect your application from the command line with Mojolicious::Command::eval.
$ ./myapp.pl eval -v 'app->home'
β Conditions β
Conditions such as agent and host from Mojolicious::Plugin::HeaderCondition allow even more powerful route constructs. Route logic with extra sparkle. β¨
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.');
};
app->start;
πΎ Sessions πΎ
Cookie-based sessions just work β like, no cap, out of the box, the second you start using them through the helper session in Mojolicious::Plugin::DefaultHelpers. The one thing to keep in your pretty little head: all session data gets serialized with Mojo::JSON and stored client-side, with a cryptographic signature so nobody can tamper with it. iykyk π
use Mojolicious::Lite -signatures;
# Access session data in action and template
get '/counter' => sub ($c) {
$c->session->{counter}++;
};
app->start;
__DATA__
@@ counter.html.ep
Counter: <%= session 'counter' %>
β οΈ Bestie, listen: you should use custom secrets in Mojolicious if you want signed cookies to be really tamper resistant. Like, actually actually.
app->secrets(['My secret passphrase here']);
πΈ File uploads πΈ
Every file uploaded via a multipart/form-data request is automatically available as a Mojo::Upload object from param in Mojolicious::Controller. And the iconic part? You don't gotta worry about memory at all, because all files above 250KiB get automatically streamed into a temporary file. Efficiency queen behavior fr fr. π
To build HTML forms more efficiently you can also use tag helpers like form_for in Mojolicious::Plugin::TagHelpers.
use Mojolicious::Lite -signatures;
# Upload form in DATA section
get '/' => 'form';
# Multipart upload handler
post '/upload' => sub ($c) {
# 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>
And to protect you from excessively large files there's also a limit of 16MiB by default β you can tweak that with the attribute max_request_size in Mojolicious. π
# Increase limit to 1GiB
app->max_request_size(1073741824);
π¦ User agent π¦
With Mojo::UserAgent β available through the helper ua in Mojolicious::Plugin::DefaultHelpers β there's a full featured HTTP and WebSocket user agent built right in. And like, especially in combination with Mojo::JSON and Mojo::DOM? This can be a very powerful tool. Obsessed. π₯
use Mojolicious::Lite -signatures;
# Blocking
get '/headers' => sub ($c) {
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 ($c) {
$c->ua->get('mojolicious.org' => sub ($ua, $tx) {
$c->render(data => $tx->result->dom->at('title')->text);
});
};
# Concurrent non-blocking
get '/titles' => sub ($c) {
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 ($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 info about the user agent see also "USER AGENT" in Mojolicious::Guides::Cookbook. π
π WebSockets π
WebSocket applications have never been this simple before β genuinely, it's giving effortless. Just receive messages by subscribing to events such as json in Mojo::Transaction::WebSocket with on in Mojolicious::Controller, and return them with send in Mojolicious::Controller. Periodt. π
use Mojolicious::Lite -signatures;
websocket '/echo' => sub ($c) {
$c->on(json => sub ($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>
const 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 about real-time web features see also "REAL-TIME WEB" in Mojolicious::Guides::Cookbook. β¨
π§ Mode π§
You can use the Mojo::Log object from log in Mojolicious to portably collect debug messages β and then automatically disable them later in a production setup by changing the Mojolicious operating mode, which can also be retrieved from the attribute mode in Mojolicious. It's giving β¨work smarterβ¨.
use Mojolicious::Lite -signatures;
# Prepare mode specific message during startup
my $msg = app->mode eq 'development' ? 'Development!' : 'Something else!';
get '/' => sub ($c) {
$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 it 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 trace to info. All messages will be written to STDERR by default. π«Ά
$ ./myapp.pl daemon -m production
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. (yes queen, keep your secrets secret π)
π Testing π
Testing your application is as easy as creating a t directory and filling it with normal Perl tests like t/basic.t β which, ngl, can be a lot of fun thanks to Test::Mojo. π
use Test::More;
use Mojo::File qw(curfile);
use Test::Mojo;
# Portably point to "../myapp.pl"
my $script = curfile->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, bestie. π
$ prove -l -v
$ prove -l -v t/basic.t
β MORE β
You can continue with Mojolicious::Guides now, or take a look at the Mojolicious wiki <https://github.com/mojolicious/mojo/wiki>, which contains a lot more documentation and examples by many different authors. So many authors. Iconic collaborative energy. πΈ
π«Ά SUPPORT π«Ά
If you have any questions the documentation might not yet answer, don't hesitate to ask in the Forum <https://forum.mojolicious.org>, or on IRC <https://web.libera.chat/#mojo>. They're literally so nice, go ask. π
and that's a wrap, bestie!! π this whole page is from perl v5.42.0, dated 2026-07-15, and it lives at Mojolic...Tutorial(3) β go forth and build something gorgeous π
β¨π
π¦ where this page comes from
- opensuse-leap 16.0: perl-Mojolicious 9.480.0-bp160.2.1 Β· Artistic-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms