.\" -*- mode: troff; coding: utf-8 -*- .\" Automatically generated by Pod::Man 5.01 (Pod::Simple 3.43) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>. .ie n \{\ . ds C` "" . ds C' "" 'br\} .el\{\ . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Mojolicious::Guides::Tutorial 3pm" .TH Mojolicious::Guides::Tutorial 3pm 2024-05-15 "perl v5.38.2" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH NAME Mojolicious::Guides::Tutorial \- Get started with Mojolicious .SH TUTORIAL .IX Header "TUTORIAL" A quick example-driven introduction to the wonders of Mojolicious::Lite. Almost everything you'll learn here also applies to full Mojolicious applications. .PP 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. .SS "Hello World" .IX Subsection "Hello World" A simple Hello World application can look like this, strict, warnings, utf8 and Perl 5.16 features are automatically enabled and a few functions imported, when you use Mojolicious::Lite, turning your script into a full featured web application. .PP .Vb 2 \& #!/usr/bin/env perl \& use Mojolicious::Lite \-signatures; \& \& get \*(Aq/\*(Aq => sub ($c) { \& $c\->render(text => \*(AqHello World!\*(Aq); \& }; \& \& app\->start; .Ve .PP With Mojolicious::Command::Author::generate::lite_app there is also a helper command to generate a small example application. .PP .Vb 1 \& $ mojo generate lite\-app myapp.pl .Ve .SS Commands .IX Subsection "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. .PP .Vb 2 \& $ ./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)... .Ve .PP A call to "start" in Mojolicious (\f(CW\*(C`app\->start\*(C'\fR), which starts the command system, should be the last expression in your application, because its return value can be significant. .PP .Vb 2 \& # Use @ARGV to pick a command \& app\->start; \& \& # Start the "daemon" command \& app\->start(\*(Aqdaemon\*(Aq, \*(Aq\-l\*(Aq, \*(Aqhttp://*:8080\*(Aq); .Ve .SS Reloading .IX Subsection "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. .PP .Vb 2 \& $ morbo ./myapp.pl \& Web application available at http://127.0.0.1:3000 .Ve .PP For more information about how to deploy your application see also "DEPLOYMENT" in Mojolicious::Guides::Cookbook. .SS Routes .IX Subsection "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 (\f(CW$c\fR) is a Mojolicious::Controller object, containing both the HTTP request and response. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # Route leading to an action that renders some text \& get \*(Aq/foo\*(Aq => sub ($c) { \& $c\->render(text => \*(AqHello World!\*(Aq); \& }; \& \& app\->start; .Ve .PP Response content is often generated by actions with "render" in Mojolicious::Controller, but more about that later. .SS "GET/POST parameters" .IX Subsection "GET/POST parameters" All \f(CW\*(C`GET\*(C'\fR and \f(CW\*(C`POST\*(C'\fR parameters sent with the request are accessible via "param" in Mojolicious::Controller. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # /foo?user=sri \& get \*(Aq/foo\*(Aq => sub ($c) { \& my $user = $c\->param(\*(Aquser\*(Aq); \& $c\->render(text => "Hello $user."); \& }; \& \& app\->start; .Ve .SS "Stash and templates" .IX Subsection "Stash and templates" The "stash" in Mojolicious::Controller is used to pass data to templates, which can be inlined in the \f(CW\*(C`DATA\*(C'\fR section. A few stash values like \f(CW\*(C`template\*(C'\fR, \f(CW\*(C`text\*(C'\fR and \f(CW\*(C`data\*(C'\fR are reserved and will be used by "render" in Mojolicious::Controller to decide how a response should be generated. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # Route leading to an action that renders a template \& get \*(Aq/foo\*(Aq => sub ($c) { \& $c\->stash(one => 23); \& $c\->render(template => \*(Aqmagic\*(Aq, two => 24); \& }; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ magic.html.ep \& The magic numbers are <%= $one %> and <%= $two %>. .Ve .PP For more information about templates see also "Embedded Perl" in Mojolicious::Guides::Rendering. .SS HTTP .IX Subsection "HTTP" "req" in Mojolicious::Controller and "res" in Mojolicious::Controller give you full access to all HTTP features and information. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # Access request information \& get \*(Aq/agent\*(Aq => 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 \*(Aq/echo\*(Aq => sub ($c) { \& $c\->res\->headers\->header(\*(AqX\-Bender\*(Aq => \*(AqBite my shiny metal ass!\*(Aq); \& $c\->render(data => $c\->req\->body); \& }; \& \& app\->start; .Ve .PP You can test the more advanced examples right from the command line with Mojolicious::Command::get. .PP .Vb 1 \& $ ./myapp.pl get \-v \-M POST \-c \*(Aqtest\*(Aq /echo .Ve .SS JSON .IX Subsection "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 \f(CW\*(C`json\*(C'\fR. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # Modify the received JSON document and return it \& put \*(Aq/reverse\*(Aq => sub ($c) { \& my $hash = $c\->req\->json; \& $hash\->{message} = reverse $hash\->{message}; \& $c\->render(json => $hash); \& }; \& \& app\->start; .Ve .PP You can send JSON documents from the command line with Mojolicious::Command::get. .PP .Vb 1 \& $ ./myapp.pl get \-M PUT \-c \*(Aq{"message":"Hello Mojo!"}\*(Aq /reverse .Ve .ie n .SS "Built-in ""exception"" and ""not_found"" pages" .el .SS "Built-in \f(CWexception\fP and \f(CWnot_found\fP pages" .IX Subsection "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. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # Not found (404) \& get \*(Aq/missing\*(Aq => sub ($c) { \& $c\->render(template => \*(Aqdoes_not_exist\*(Aq); \& }; \& \& # Exception (500) \& get \*(Aq/dies\*(Aq => sub { die \*(AqIntentional error\*(Aq }; \& \& app\->start; .Ve .PP You can even use CSS selectors with Mojolicious::Command::get to extract only the information you're actually interested in. .PP .Vb 1 \& $ ./myapp.pl get /dies \*(Aq#error\*(Aq .Ve .PP 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. .SS "Route names" .IX Subsection "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. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # Render the template "index.html.ep" \& get \*(Aq/\*(Aq => sub ($c) { \& $c\->render; \& } => \*(Aqindex\*(Aq; \& \& # Render the template "hello.html.ep" \& get \*(Aq/hello\*(Aq; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ index.html.ep \& <%= link_to Hello => \*(Aqhello\*(Aq %>. \& <%= link_to Reload => \*(Aqindex\*(Aq %>. \& \& @@ hello.html.ep \& Hello World! .Ve .PP Nameless routes get an automatically generated one assigned that is simply equal to the route itself without non-word characters. .SS Layouts .IX Subsection "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. .PP .Vb 1 \& use Mojolicious::Lite; \& \& get \*(Aq/with_layout\*(Aq; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ with_layout.html.ep \& % title \*(AqGreen\*(Aq; \& % layout \*(Aqgreen\*(Aq; \& Hello World! \& \& @@ layouts/green.html.ep \& \& \& <%= title %> \& <%= content %> \& .Ve .PP The stash or helpers like "title" in Mojolicious::Plugin::DefaultHelpers can be used to pass additional data to the layout. .SS Blocks .IX Subsection "Blocks" Template blocks can be used like normal Perl functions and are always delimited by the \f(CW\*(C`begin\*(C'\fR and \f(CW\*(C`end\*(C'\fR keywords, they are the foundation for many helpers. .PP .Vb 1 \& use Mojolicious::Lite; \& \& get \*(Aq/with_block\*(Aq => \*(Aqblock\*(Aq; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ block.html.ep \& % my $link = begin \& % my ($url, $name) = @_; \& Try <%= link_to $url => begin %><%= $name %><% end %>. \& % end \& \& \& Sebastians frameworks \& \& %= $link\->(\*(Aqhttp://mojolicious.org\*(Aq, \*(AqMojolicious\*(Aq) \& %= $link\->(\*(Aqhttp://mojojs.org\*(Aq, \*(Aqmojo.js\*(Aq) \& \& .Ve .SS Helpers .IX Subsection "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. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # A helper to identify visitors \& helper whois => sub ($c) { \& my $agent = $c\->req\->headers\->user_agent || \*(AqAnonymous\*(Aq; \& my $ip = $c\->tx\->remote_address; \& return "$agent ($ip)"; \& }; \& \& # Use helper in action and template \& get \*(Aq/secret\*(Aq => 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 %>. .Ve .PP A list of all built-in ones can be found in Mojolicious::Plugin::DefaultHelpers and Mojolicious::Plugin::TagHelpers. .SS Plugins .IX Subsection "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 \f(CW\*(C`Mojolicious::Plugin::\*(C'\fR part of the name, and optionally provide configuration for the plugin. .PP .Vb 1 \& use Mojolicious::Lite; \& \& plugin Config => {file => \*(Aq/etc/myapp.conf\*(Aq, default => {foo => \*(Aqbar\*(Aq}}; \& \& # Return configured foo value, or default if no configuration file \& get \*(Aq/foo\*(Aq => sub ($c) { \& my $foo = $c\->app\->config(\*(Aqfoo\*(Aq); \& $c\->render(json => {foo => $foo}); \& }; \& \& app\->start; .Ve .PP 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 . .SS Placeholders .IX Subsection "Placeholders" Route placeholders allow capturing parts of a request path until a \f(CW\*(C`/\*(C'\fR or \f(CW\*(C`.\*(C'\fR separator occurs, similar to the regular expression \f(CW\*(C`([^/.]+)\*(C'\fR. Results are accessible via "stash" in Mojolicious::Controller and "param" in Mojolicious::Controller. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # /foo/test \& # /foo/test123 \& get \*(Aq/foo/:bar\*(Aq => sub ($c) { \& my $bar = $c\->stash(\*(Aqbar\*(Aq); \& $c\->render(text => "Our :bar placeholder matched $bar"); \& }; \& \& # /testsomething/foo \& # /test123something/foo \& get \*(Aq/<:bar>something/foo\*(Aq => sub ($c) { \& my $bar = $c\->param(\*(Aqbar\*(Aq); \& $c\->render(text => "Our :bar placeholder matched $bar"); \& }; \& \& app\->start; .Ve .PP To separate them from the surrounding text, you can surround your placeholders with \f(CW\*(C`<\*(C'\fR and \f(CW\*(C`>\*(C'\fR, which also makes the colon prefix optional. .SS "Relaxed Placeholders" .IX Subsection "Relaxed Placeholders" Relaxed placeholders allow matching of everything until a \f(CW\*(C`/\*(C'\fR occurs, similar to the regular expression \f(CW\*(C`([^/]+)\*(C'\fR. .PP .Vb 1 \& use Mojolicious::Lite; \& \& # /hello/test \& # /hello/test.html \& get \*(Aq/hello/#you\*(Aq => \*(Aqgroovy\*(Aq; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ groovy.html.ep \& Your name is <%= $you %>. .Ve .SS "Wildcard placeholders" .IX Subsection "Wildcard placeholders" Wildcard placeholders allow matching absolutely everything, including \f(CW\*(C`/\*(C'\fR and \f(CW\*(C`.\*(C'\fR, similar to the regular expression \&\f(CW\*(C`(.+)\*(C'\fR. .PP .Vb 1 \& use Mojolicious::Lite; \& \& # /hello/test \& # /hello/test123 \& # /hello/test.123/test/123 \& get \*(Aq/hello/*you\*(Aq => \*(Aqgroovy\*(Aq; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ groovy.html.ep \& Your name is <%= $you %>. .Ve .SS "HTTP methods" .IX Subsection "HTTP methods" Routes can be restricted to specific request methods with different keywords like "get" in Mojolicious::Lite and "any" in Mojolicious::Lite. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # GET /hello \& get \*(Aq/hello\*(Aq => sub ($c) { \& $c\->render(text => \*(AqHello World!\*(Aq); \& }; \& \& # PUT /hello \& put \*(Aq/hello\*(Aq => sub ($c) { \& my $size = length $c\->req\->body; \& $c\->render(text => "You uploaded $size bytes to /hello."); \& }; \& \& # GET|POST|PATCH /bye \& any [\*(AqGET\*(Aq, \*(AqPOST\*(Aq, \*(AqPATCH\*(Aq] => \*(Aq/bye\*(Aq => sub ($c) { \& $c\->render(text => \*(AqBye World!\*(Aq); \& }; \& \& # * /whatever \& any \*(Aq/whatever\*(Aq => sub ($c) { \& my $method = $c\->req\->method; \& $c\->render(text => "You called /whatever with $method."); \& }; \& \& app\->start; .Ve .SS "Optional placeholders" .IX Subsection "Optional placeholders" All placeholders require a value, but by assigning them default values you can make capturing optional. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # /hello \& # /hello/Sara \& get \*(Aq/hello/:name\*(Aq => {name => \*(AqSebastian\*(Aq, day => \*(AqMonday\*(Aq} => sub ($c) { \& $c\->render(template => \*(Aqgroovy\*(Aq, format => \*(Aqtxt\*(Aq); \& }; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ groovy.txt.ep \& My name is <%= $name %> and it is <%= $day %>. .Ve .PP Default values that don't belong to a placeholder simply get merged into the stash all the time. .SS "Restrictive placeholders" .IX Subsection "Restrictive placeholders" A very easy way to make placeholders more restrictive are alternatives, you just make a list of possible values. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # /test \& # /123 \& any \*(Aq/:foo\*(Aq => [foo => [\*(Aqtest\*(Aq, \*(Aq123\*(Aq]] => sub ($c) { \& my $foo = $c\->param(\*(Aqfoo\*(Aq); \& $c\->render(text => "Our :foo placeholder matched $foo"); \& }; \& \& app\->start; .Ve .PP All placeholders get compiled to a regular expression internally, this process can also be customized. Just make sure not to use \f(CW\*(C`^\*(C'\fR and \f(CW\*(C`$\*(C'\fR, or capturing groups \f(CW\*(C`(...)\*(C'\fR, non-capturing groups \f(CW\*(C`(?:...)\*(C'\fR are fine though. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # /1 \& # /123 \& any \*(Aq/:bar\*(Aq => [bar => qr/\ed+/] => sub ($c) { \& my $bar = $c\->param(\*(Aqbar\*(Aq); \& $c\->render(text => "Our :bar placeholder matched $bar"); \& }; \& \& app\->start; .Ve .PP You can take a closer look at all the generated regular expressions with the command Mojolicious::Command::routes. .PP .Vb 1 \& $ ./myapp.pl routes \-v .Ve .SS Under .IX Subsection "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. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # Authenticate based on name parameter \& under sub ($c) { \& \& # Authenticated \& my $name = $c\->param(\*(Aqname\*(Aq) || \*(Aq\*(Aq; \& return 1 if $name eq \*(AqBender\*(Aq; \& \& # Not authenticated \& $c\->render(template => \*(Aqdenied\*(Aq); \& return undef; \& }; \& \& # Only reached when authenticated \& get \*(Aq/\*(Aq => \*(Aqindex\*(Aq; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ denied.html.ep \& You are not Bender, permission denied. \& \& @@ index.html.ep \& Hi Bender. .Ve .PP Prefixing multiple routes is another good use for it. .PP .Vb 1 \& use Mojolicious::Lite; \& \& # /foo \& under \*(Aq/foo\*(Aq; \& \& # /foo/bar \& get \*(Aq/bar\*(Aq => {text => \*(Aqfoo bar\*(Aq}; \& \& # /foo/baz \& get \*(Aq/baz\*(Aq => {text => \*(Aqfoo baz\*(Aq}; \& \& # / (reset) \& under \*(Aq/\*(Aq => {msg => \*(Aqwhatever\*(Aq}; \& \& # /bar \& get \*(Aq/bar\*(Aq => {inline => \*(Aq<%= $msg %> works\*(Aq}; \& \& app\->start; .Ve .PP You can also group related routes with "group" in Mojolicious::Lite, which allows nesting of routes generated with "under" in Mojolicious::Lite. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # Global logic shared by all routes \& under sub ($c) { \& return 1 if $c\->req\->headers\->header(\*(AqX\-Bender\*(Aq); \& $c\->render(text => "You\*(Aqre not Bender."); \& return undef; \& }; \& \& # Admin section \& group { \& \& # Local logic shared only by routes in this group \& under \*(Aq/admin\*(Aq => sub ($c) { \& return 1 if $c\->req\->headers\->header(\*(AqX\-Awesome\*(Aq); \& $c\->render(text => "You\*(Aqre not awesome enough."); \& return undef; \& }; \& \& # GET /admin/dashboard \& get \*(Aq/dashboard\*(Aq => {text => \*(AqNothing to see here yet.\*(Aq}; \& }; \& \& # GET /welcome \& get \*(Aq/welcome\*(Aq => {text => \*(AqHi Bender.\*(Aq}; \& \& app\->start; .Ve .SS Formats .IX Subsection "Formats" Formats can be automatically detected from file extensions like \f(CW\*(C`.html\*(C'\fR, they are used to find the right template and generate the correct \f(CW\*(C`Content\-Type\*(C'\fR header. Use a restrictive placeholder to declare the possible values. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # /detection.html \& # /detection.txt \& get \*(Aq/detection\*(Aq => [format => [\*(Aqhtml\*(Aq, \*(Aqtxt\*(Aq]] => sub ($c) { \& $c\->render(template => \*(Aqdetected\*(Aq); \& }; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ detected.html.ep \& \& \& Detected \& HTML was detected. \& \& \& @@ detected.txt.ep \& TXT was detected. .Ve .PP And just like with placeholders you can use a default value to make the format optional. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # /hello \& # /hello.json \& # /hello.txt \& get \*(Aq/hello\*(Aq => [format => [\*(Aqjson\*(Aq, \*(Aqtxt\*(Aq]] => {format => \*(Aqtxt\*(Aq} => sub ($c) { \& return $c\->render(json => {hello => \*(Aqworld\*(Aq}) if $c\->stash(\*(Aqformat\*(Aq) eq \*(Aqjson\*(Aq; \& $c\->render(text => \*(Aqhello world\*(Aq); \& }; \& \& app\->start; .Ve .PP The default format is \f(CW\*(C`html\*(C'\fR and the renderer will fall back to when necessary. .SS "Content negotiation" .IX Subsection "Content negotiation" For resources with different representations and that require truly RESTful content negotiation you can also use "respond_to" in Mojolicious::Plugin::DefaultHelpers. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # /hello (Accept: application/json) \& # /hello (Accept: application/xml) \& # /hello.json \& # /hello.xml \& # /hello?_format=json \& # /hello?_format=xml \& get \*(Aq/hello\*(Aq => [format => [\*(Aqjson\*(Aq, \*(Aqxml\*(Aq]] => {format => undef} => sub ($c) { \& $c\->respond_to( \& json => {json => {hello => \*(Aqworld\*(Aq}}, \& xml => {text => \*(Aqworld\*(Aq}, \& any => {data => \*(Aq\*(Aq, status => 204} \& ); \& }; \& \& app\->start; .Ve .PP MIME type mappings can be extended or changed easily with "types" in Mojolicious. .PP .Vb 1 \& app\->types\->type(rdf => \*(Aqapplication/rdf+xml\*(Aq); .Ve .SS "Static files" .IX Subsection "Static files" Similar to templates, but with only a single file extension and optional Base64 encoding, static files can be inlined in the \f(CW\*(C`DATA\*(C'\fR section and are served automatically. .PP .Vb 1 \& use Mojolicious::Lite; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ something.js \& alert(\*(Aqhello!\*(Aq); \& \& @@ test.txt (base64) \& dGVzdCAxMjMKbGFsYWxh .Ve .PP External static files are not limited to a single file extension and will be served automatically from a \f(CW\*(C`public\*(C'\fR directory if it exists. .PP .Vb 3 \& $ mkdir public \& $ mv something.js public/something.js \& $ mv mojolicious.tar.gz public/mojolicious.tar.gz .Ve .PP Both have a higher precedence than routes for \f(CW\*(C`GET\*(C'\fR and \f(CW\*(C`HEAD\*(C'\fR requests. Content negotiation with \f(CW\*(C`Range\*(C'\fR, \&\f(CW\*(C`If\-None\-Match\*(C'\fR and \f(CW\*(C`If\-Modified\-Since\*(C'\fR headers is supported as well and can be tested very easily with Mojolicious::Command::get. .PP .Vb 1 \& $ ./myapp.pl get /something.js \-v \-H \*(AqRange: bytes=2\-4\*(Aq .Ve .SS "External templates" .IX Subsection "External templates" External templates will be searched by the renderer in a \f(CW\*(C`templates\*(C'\fR directory if it exists. .PP .Vb 2 \& $ mkdir \-p templates/foo \& $ echo \*(AqHello World!\*(Aq > templates/foo/bar.html.ep .Ve .PP They have a higher precedence than templates in the \f(CW\*(C`DATA\*(C'\fR section. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # Render template "templates/foo/bar.html.ep" \& any \*(Aq/external\*(Aq => sub ($c) { \& $c\->render(template => \*(Aqfoo/bar\*(Aq); \& }; \& \& app\->start; .Ve .SS Home .IX Subsection "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 \f(CW\*(C`public\*(C'\fR and \f(CW\*(C`templates\*(C'\fR directories, but you can use it to store all sorts of application specific data. .PP .Vb 2 \& $ mkdir cache \& $ echo \*(AqHello World!\*(Aq > cache/hello.txt .Ve .PP 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. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # Load message into memory \& my $hello = app\->home\->child(\*(Aqcache\*(Aq, \*(Aqhello.txt\*(Aq)\->slurp; \& \& # Display message \& get \*(Aq/\*(Aq => sub ($c) { \& $c\->render(text => $hello); \& }; .Ve .PP You can also introspect your application from the command line with Mojolicious::Command::eval. .PP .Vb 1 \& $ ./myapp.pl eval \-v \*(Aqapp\->home\*(Aq .Ve .SS Conditions .IX Subsection "Conditions" Conditions such as \f(CW\*(C`agent\*(C'\fR and \f(CW\*(C`host\*(C'\fR from Mojolicious::Plugin::HeaderCondition allow even more powerful route constructs. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # Firefox \& get \*(Aq/foo\*(Aq => (agent => qr/Firefox/) => sub ($c) { \& $c\->render(text => \*(AqCongratulations, you are using a cool browser.\*(Aq); \& }; \& \& # Internet Explorer \& get \*(Aq/foo\*(Aq => (agent => qr/Internet Explorer/) => sub ($c) { \& $c\->render(text => \*(AqDude, you really need to upgrade to Firefox.\*(Aq); \& }; \& \& # http://mojolicious.org/bar \& get \*(Aq/bar\*(Aq => (host => \*(Aqmojolicious.org\*(Aq) => sub ($c) { \& $c\->render(text => \*(AqHello Mojolicious.\*(Aq); \& }; \& \& app\->start; .Ve .SS Sessions .IX Subsection "Sessions" Cookie-based sessions just work out of the box, as soon as you start using them through the helper "session" in Mojolicious::Plugin::DefaultHelpers. Just be aware that all session data gets serialized with Mojo::JSON and stored client-side, with a cryptographic signature to prevent tampering. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # Access session data in action and template \& get \*(Aq/counter\*(Aq => sub ($c) { \& $c\->session\->{counter}++; \& }; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ counter.html.ep \& Counter: <%= session \*(Aqcounter\*(Aq %> .Ve .PP Note that you should use custom "secrets" in Mojolicious to make signed cookies really tamper resistant. .PP .Vb 1 \& app\->secrets([\*(AqMy secret passphrase here\*(Aq]); .Ve .SS "File uploads" .IX Subsection "File uploads" All files uploaded via \f(CW\*(C`multipart/form\-data\*(C'\fR request are automatically available as Mojo::Upload objects from "param" in Mojolicious::Controller. And you don't have to worry about memory usage, because all files above 250KiB will be automatically streamed into a temporary file. To build HTML forms more efficiently, you can also use tag helpers like "form_for" in Mojolicious::Plugin::TagHelpers. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # Upload form in DATA section \& get \*(Aq/\*(Aq => \*(Aqform\*(Aq; \& \& # Multipart upload handler \& post \*(Aq/upload\*(Aq => sub ($c) { \& \& # Check file size \& return $c\->render(text => \*(AqFile is too big.\*(Aq, status => 200) if $c\->req\->is_limit_exceeded; \& \& # Process uploaded file \& return $c\->redirect_to(\*(Aqform\*(Aq) unless my $example = $c\->param(\*(Aqexample\*(Aq); \& my $size = $example\->size; \& my $name = $example\->filename; \& $c\->render(text => "Thanks for uploading $size byte file $name."); \& }; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ form.html.ep \& \& \& Upload \& \& %= form_for upload => (enctype => \*(Aqmultipart/form\-data\*(Aq) => begin \& %= file_field \*(Aqexample\*(Aq \& %= submit_button \*(AqUpload\*(Aq \& % end \& \& .Ve .PP 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. .PP .Vb 2 \& # Increase limit to 1GiB \& app\->max_request_size(1073741824); .Ve .SS "User agent" .IX Subsection "User agent" With Mojo::UserAgent, which is available through the helper "ua" in Mojolicious::Plugin::DefaultHelpers, there's a full featured HTTP and WebSocket user agent built right in. Especially in combination with Mojo::JSON and Mojo::DOM this can be a very powerful tool. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # Blocking \& get \*(Aq/headers\*(Aq => sub ($c) { \& my $url = $c\->param(\*(Aqurl\*(Aq) || \*(Aqhttps://mojolicious.org\*(Aq; \& my $dom = $c\->ua\->get($url)\->result\->dom; \& $c\->render(json => $dom\->find(\*(Aqh1, h2, h3\*(Aq)\->map(\*(Aqtext\*(Aq)\->to_array); \& }; \& \& # Non\-blocking \& get \*(Aq/title\*(Aq => sub ($c) { \& $c\->ua\->get(\*(Aqmojolicious.org\*(Aq => sub ($ua, $tx) { \& $c\->render(data => $tx\->result\->dom\->at(\*(Aqtitle\*(Aq)\->text); \& }); \& }; \& \& # Concurrent non\-blocking \& get \*(Aq/titles\*(Aq => sub ($c) { \& my $mojo = $c\->ua\->get_p(\*(Aqhttps://mojolicious.org\*(Aq); \& my $cpan = $c\->ua\->get_p(\*(Aqhttps://metacpan.org\*(Aq); \& Mojo::Promise\->all($mojo, $cpan)\->then(sub ($mojo, $cpan) { \& $c\->render(json => { \& mojo => $mojo\->[0]\->result\->dom\->at(\*(Aqtitle\*(Aq)\->text, \& cpan => $cpan\->[0]\->result\->dom\->at(\*(Aqtitle\*(Aq)\->text \& }); \& })\->wait; \& }; \& \& app\->start; .Ve .PP For more information about the user agent see also "USER AGENT" in Mojolicious::Guides::Cookbook. .SS WebSockets .IX Subsection "WebSockets" WebSocket applications have never been this simple before. 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. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& websocket \*(Aq/echo\*(Aq => sub ($c) { \& $c\->on(json => sub ($c, $hash) { \& $hash\->{msg} = "echo: $hash\->{msg}"; \& $c\->send({json => $hash}); \& }); \& }; \& \& get \*(Aq/\*(Aq => \*(Aqindex\*(Aq; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ index.html.ep \& \& \& \& Echo \& \& \& .Ve .PP For more information about real-time web features see also "REAL-TIME WEB" in Mojolicious::Guides::Cookbook. .SS Mode .IX Subsection "Mode" You can use the Mojo::Log object from "log" in Mojolicious to portably collect debug messages and 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. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # Prepare mode specific message during startup \& my $msg = app\->mode eq \*(Aqdevelopment\*(Aq ? \*(AqDevelopment!\*(Aq : \*(AqSomething else!\*(Aq; \& \& get \*(Aq/\*(Aq => sub ($c) { \& $c\->app\->log\->debug(\*(AqRendering mode specific message\*(Aq); \& $c\->render(text => $msg); \& }; \& \& app\->log\->debug(\*(AqStarting application\*(Aq); \& app\->start; .Ve .PP The default operating mode will usually be \f(CW\*(C`development\*(C'\fR and can be changed with command line options or the \&\f(CW\*(C`MOJO_MODE\*(C'\fR and \f(CW\*(C`PLACK_ENV\*(C'\fR environment variables. A mode other than \f(CW\*(C`development\*(C'\fR will raise the log level from \&\f(CW\*(C`trace\*(C'\fR to \f(CW\*(C`info\*(C'\fR. All messages will be written to \f(CW\*(C`STDERR\*(C'\fR by default. .PP .Vb 1 \& $ ./myapp.pl daemon \-m production .Ve .PP Mode changes also affect a few other aspects of the framework, such as the built-in \f(CW\*(C`exception\*(C'\fR and \f(CW\*(C`not_found\*(C'\fR pages. Once you switch modes from \f(CW\*(C`development\*(C'\fR to \f(CW\*(C`production\*(C'\fR, no sensitive information will be revealed on those pages anymore. .SS Testing .IX Subsection "Testing" Testing your application is as easy as creating a \f(CW\*(C`t\*(C'\fR directory and filling it with normal Perl tests like \&\f(CW\*(C`t/basic.t\*(C'\fR, which can be a lot of fun thanks to Test::Mojo. .PP .Vb 3 \& use Test::More; \& use Mojo::File qw(curfile); \& use Test::Mojo; \& \& # Portably point to "../myapp.pl" \& my $script = curfile\->dirname\->sibling(\*(Aqmyapp.pl\*(Aq); \& \& my $t = Test::Mojo\->new($script); \& $t\->get_ok(\*(Aq/\*(Aq)\->status_is(200)\->content_like(qr/Funky/); \& \& done_testing(); .Ve .PP Just run your tests with prove. .PP .Vb 2 \& $ prove \-l \-v \& $ prove \-l \-v t/basic.t .Ve .SH MORE .IX Header "MORE" You can continue with Mojolicious::Guides now or take a look at the Mojolicious wiki , which contains a lot more documentation and examples by many different authors. .SH SUPPORT .IX Header "SUPPORT" If you have any questions the documentation might not yet answer, don't hesitate to ask in the Forum , on IRC , or Matrix .