.\" -*- 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::Cookbook 3pm" .TH Mojolicious::Guides::Cookbook 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::Cookbook \- Cooking with Mojolicious .SH OVERVIEW .IX Header "OVERVIEW" This document contains many fun recipes for cooking with Mojolicious. .SH CONCEPTS .IX Header "CONCEPTS" Essentials every Mojolicious developer should know. .SS "Blocking and non-blocking operations" .IX Subsection "Blocking and non-blocking operations" A \fIblocking\fR operation is a subroutine that blocks the execution of the calling subroutine until the subroutine is finished. .PP .Vb 4 \& sub foo { \& my $result = blocking_subroutine(); \& ... \& } .Ve .PP A \fInon-blocking\fR operation on the other hand lets the calling subroutine continue execution even though the subroutine is not yet finished. Instead of waiting, the calling subroutine passes along a callback to be executed once the subroutine is finished, this is called continuation-passing style. .PP .Vb 6 \& sub foo { \& non_blocking_subroutine(sub ($result) { \& ... \& }); \& ... \& } .Ve .PP While Mojolicious has been designed from the ground up for non-blocking I/O and event loops, it is not possible to magically make Perl code non-blocking. You have to use specialized non-blocking code available through modules like Mojo::IOLoop and Mojo::UserAgent, or third-party event loops. You can wrap your blocking code in subprocesses though to prevent it from interfering with your non-blocking code. .SS "Event loops" .IX Subsection "Event loops" An event loop is basically a loop that continually tests for external events and executes the appropriate callbacks to handle them, it is often the main loop in a program. Non-blocking tests for readability/writability of file descriptors and timers are commonly used events for highly scalable network servers, because they allow a single process to handle thousands of client connections concurrently. .PP .Vb 3 \& while (1) { \& my @readable = test_fds_for_readability(); \& handle_readable_fds(@readable); \& \& my @writable = test_fds_for_writability(); \& handle_writable_fds(@writable); \& \& my @expired = test_timers(); \& handle_timers(@expired); \& } .Ve .PP In Mojolicious this event loop is Mojo::IOLoop. .SS "Reverse proxy" .IX Subsection "Reverse proxy" A reverse proxy architecture is a deployment technique used in many production environments, where a \fIreverse proxy\fR server is put in front of your application to act as the endpoint accessible by external clients. It can provide a lot of benefits, like terminating SSL connections from the outside, limiting the number of concurrent open sockets towards the Mojolicious application (or even using Unix sockets), balancing load across multiple instances, or supporting several applications through the same IP/port. .PP .Vb 10 \& .......................................... \& : : \& +\-\-\-\-\-\-\-\-+ : +\-\-\-\-\-\-\-\-\-\-\-+ +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ : \& | |\-\-\-\-\-\-\-\->| | | | : \& | client | : | reverse |\-\-\-\-\->| Mojolicious | : \& | |<\-\-\-\-\-\-\-\-| proxy | | application | : \& +\-\-\-\-\-\-\-\-+ : | |<\-\-\-\-\-| | : \& : +\-\-\-\-\-\-\-\-\-\-\-+ +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ : \& : : \& .. system boundary (e.g. same host) ...... .Ve .PP This setup introduces some problems, though: the application will receive requests from the reverse proxy instead of the original client; the address/hostname where your application lives internally will be different from the one visible from the outside; and if terminating SSL, the reverse proxy exposes services via HTTPS while using HTTP towards the Mojolicious application. .PP As an example, compare a sample request from the client and what the Mojolicious application receives: .PP .Vb 4 \& client reverse proxy Mojolicious app \& _\|_|_\|_ _\|_\|_\|_\|_\|_\|_\|_\|_\|_\|_\|_\|_\|_\|_|_\|_\|_\|_\|_\|_\|_\|_\|_\|_\|_\|_\|_\|_ _\|_\|_\|_|_\|_\|_\|_ \& / \e / \e / \e \& 1.2.3.4 \-\-HTTPS\-\-> api.example.com 10.20.30.39 \-\-HTTP\-\-> 10.20.30.40 \& \& GET /foo/1 HTTP/1.1 | GET /foo/1 HTTP/1.1 \& Host: api.example.com | Host: 10.20.30.40 \& User\-Agent: Firefox | User\-Agent: ShinyProxy/1.2 \& ... | ... .Ve .PP However, now the client address is no longer available (which might be useful for analytics, or Geo-IP) and URLs generated via "url_for" in Mojolicious::Controller will look like this: .PP .Vb 1 \& http://10.20.30.40/bar/2 .Ve .PP instead of something meaningful for the client, like this: .PP .Vb 1 \& https://api.example.com/bar/2 .Ve .PP To solve these problems, you can configure your reverse proxy to send the missing data (see "Nginx" and "Apache/mod_proxy") and tell your application about it by setting the environment variable \f(CW\*(C`MOJO_REVERSE_PROXY\*(C'\fR. In more complex situations, usually involving multiple proxies or proxies that live outside your network, it can be necessary to tell the application from which ip addresses to expect proxy requests by setting \f(CW\*(C`MOJO_TRUSTED_PROXIES\*(C'\fR to a list of comma separated addresses or CIDR networks. For even finer control, "Rewriting" includes examples of how the changes could be implemented manually. .SH DEPLOYMENT .IX Header "DEPLOYMENT" Getting Mojolicious and Mojolicious::Lite applications running on different platforms. Note that many real-time web features are based on the Mojo::IOLoop event loop, and therefore require one of the built-in web servers to be able to use them to their full potential. .SS "Built-in web server" .IX Subsection "Built-in web server" Mojolicious contains a very portable non-blocking I/O HTTP and WebSocket server with Mojo::Server::Daemon. It is usually used during development and in the construction of more advanced web servers, but is solid and fast enough for small to mid sized applications. .PP .Vb 2 \& $ ./script/my_app daemon \& Web application available at http://127.0.0.1:3000 .Ve .PP It is available to every application through the command Mojolicious::Command::daemon, which has many configuration options and is known to work on every platform Perl works on with its single-process architecture. .PP .Vb 2 \& $ ./script/my_app daemon \-h \& ...List of available options... .Ve .PP Another huge advantage is that it supports TLS and WebSockets out of the box, a development certificate for testing purposes is built right in, so it just works, but you can specify all listen locations supported by "listen" in Mojo::Server::Daemon. .PP .Vb 2 \& $ ./script/my_app daemon \-l https://[::]:3000 \& Web application available at https://[::]:3000 .Ve .PP To manage the web server with systemd, you can use a unit configuration file like this. .PP .Vb 3 \& [Unit] \& Description=My Mojolicious application \& After=network.target \& \& [Service] \& Type=simple \& User=sri \& ExecStart=/home/sri/myapp/script/my_app daemon \-m production \-l http://*:8080 \& \& [Install] \& WantedBy=multi\-user.target .Ve .SS Pre-forking .IX Subsection "Pre-forking" For bigger applications Mojolicious contains the UNIX optimized pre-forking web server Mojo::Server::Prefork, which can take advantage of multiple CPU cores and copy-on-write memory management to scale up to thousands of concurrent client connections. .PP .Vb 5 \& Mojo::Server::Prefork \& |\- Mojo::Server::Daemon [1] \& |\- Mojo::Server::Daemon [2] \& |\- Mojo::Server::Daemon [3] \& +\- Mojo::Server::Daemon [4] .Ve .PP It is based on Mojo::Server::Daemon and available to every application through the command Mojolicious::Command::prefork. .PP .Vb 2 \& $ ./script/my_app prefork \& Web application available at http://127.0.0.1:3000 .Ve .PP Since all built-in web servers are based on the Mojo::IOLoop event loop, they scale best with non-blocking operations. But if your application for some reason needs to perform many blocking operations, you can improve performance by increasing the number of worker processes and decreasing the number of concurrent connections each worker is allowed to handle (often as low as \f(CW1\fR). .PP .Vb 2 \& $ ./script/my_app prefork \-m production \-w 10 \-c 1 \& Web application available at http://127.0.0.1:3000 .Ve .PP During startup your application is preloaded in the manager process, which does not run an event loop, so you can use "next_tick" in Mojo::IOLoop to run code whenever a new worker process has been forked and its event loop gets started. .PP .Vb 1 \& use Mojolicious::Lite; \& \& Mojo::IOLoop\->next_tick(sub ($ioloop) { \& app\->log\->info("Worker $$ star...ALL GLORY TO THE HYPNOTOAD!"); \& }); \& \& get \*(Aq/\*(Aq => {text => \*(AqHello Wor...ALL GLORY TO THE HYPNOTOAD!\*(Aq}; \& \& app\->start; .Ve .PP And to manage the pre-forking web server with systemd, you can use a unit configuration file like this. .PP .Vb 3 \& [Unit] \& Description=My Mojolicious application \& After=network.target \& \& [Service] \& Type=simple \& User=sri \& ExecStart=/home/sri/myapp/script/my_app prefork \-m production \-l http://*:8080 \& \& [Install] \& WantedBy=multi\-user.target .Ve .SS Morbo .IX Subsection "Morbo" After reading the Mojolicious::Guides::Tutorial, you should already be familiar with Mojo::Server::Morbo. .PP .Vb 2 \& Mojo::Server::Morbo \& +\- Mojo::Server::Daemon .Ve .PP It is basically a restarter that forks a new Mojo::Server::Daemon web server whenever a file in your project changes, and should therefore only be used during development. To start applications with it you can use the morbo script. .PP .Vb 2 \& $ morbo ./script/my_app \& Web application available at http://127.0.0.1:3000 .Ve .SS Containers .IX Subsection "Containers" There are many ways to go cloud-native with Mojolicious. To get you started with containerizing your web applications we will explore one of them in this recipe. First, you will need to declare the CPAN dependencies of your application, for example in a \f(CW\*(C`Makefile.PL\*(C'\fR file. This should always include at the very least Mojolicious itself. .PP .Vb 2 \& use strict; \& use warnings; \& \& use ExtUtils::MakeMaker; \& \& WriteMakefile( \& VERSION => \*(Aq0.01\*(Aq, \& PREREQ_PM => { \& \*(AqMojolicious\*(Aq => \*(Aq8.65\*(Aq, \& \*(AqMojolicious::Plugin::Status\*(Aq => \*(Aq1.12\*(Aq \& }, \& test => {TESTS => \*(Aqt/*.t\*(Aq} \& ); .Ve .PP The helper command Mojolicious::Command::Author::generate::makefile can also generate a minimal \f(CW\*(C`Makefile.PL\*(C'\fR for you. .PP .Vb 2 \& $ ./myapp.pl generate makefile \& ... .Ve .PP And then we are going to need a \f(CW\*(C`Dockerfile\*(C'\fR describing the container. A very simple one will do for now. .PP .Vb 6 \& FROM perl \& WORKDIR /opt/myapp \& COPY . . \& RUN cpanm \-\-installdeps \-n . \& EXPOSE 3000 \& CMD ./myapp.pl prefork .Ve .PP It uses the latest Perl container from Docker Hub, copies all the contents of your application directory into the container, installs CPAN dependencies with App::cpanminus, and then starts the application on port \f(CW3000\fR with the pre-forking web server. With Mojolicious::Command::Author::generate::dockerfile there is also a helper command to generate a minimal \f(CW\*(C`Dockerfile\*(C'\fR for you. .PP .Vb 2 \& $ ./myapp.pl generate dockerfile \& ... .Ve .PP To build and deploy our container there are also many options available, here we will simply use Docker. .PP .Vb 4 \& $ docker build \-t myapp_image . \& ... \& $ docker run \-d \-p 3000:3000 \-\-name myapp_container myapp_image \& ... .Ve .PP And now your web application should be deployed as a container under \f(CW\*(C`http://127.0.0.1:3000\*(C'\fR. For more information and many more container deployment options we recommend the Docker and Kubernetes documentation. .SS Hypnotoad .IX Subsection "Hypnotoad" Hypnotoad is based on the Mojo::Server::Prefork web server, and adds some features especially optimized for high availability non-containerized production environments. To start applications with it you can use the hypnotoad script, which listens on port \f(CW8080\fR, automatically daemonizes the server process and defaults to \f(CW\*(C`production\*(C'\fR mode for Mojolicious and Mojolicious::Lite applications. .PP .Vb 1 \& $ hypnotoad ./script/my_app .Ve .PP Many configuration settings can be tweaked right from within your application with "config" in Mojolicious, for a full list see "SETTINGS" in Mojo::Server::Hypnotoad. .PP .Vb 1 \& use Mojolicious::Lite; \& \& app\->config(hypnotoad => {listen => [\*(Aqhttp://*:80\*(Aq]}); \& \& get \*(Aq/\*(Aq => {text => \*(AqHello Wor...ALL GLORY TO THE HYPNOTOAD!\*(Aq}; \& \& app\->start; .Ve .PP Or just add a \f(CW\*(C`hypnotoad\*(C'\fR section to your Mojolicious::Plugin::Config, Mojolicious::Plugin::JSONConfig or Mojolicious::Plugin::NotYAMLConfig configuration file. .PP .Vb 7 \& # myapp.conf \& { \& hypnotoad => { \& listen => [\*(Aqhttps://*:443?cert=/etc/server.crt&key=/etc/server.key\*(Aq], \& workers => 10 \& } \& }; .Ve .PP But one of its biggest advantages is the support for effortless zero downtime software upgrades (hot deployment). That means you can upgrade Mojolicious, Perl or even system libraries at runtime without ever stopping the server or losing a single incoming connection, just by running the command above again. .PP .Vb 2 \& $ hypnotoad ./script/my_app \& Starting hot deployment for Hypnotoad server 31841. .Ve .PP You might also want to enable proxy support if you're using Hypnotoad behind a reverse proxy. This allows Mojolicious to automatically pick up the \f(CW\*(C`X\-Forwarded\-For\*(C'\fR and \f(CW\*(C`X\-Forwarded\-Proto\*(C'\fR headers. .PP .Vb 2 \& # myapp.conf \& {hypnotoad => {proxy => 1}}; .Ve .PP To manage Hypnotoad with systemd, you can use a unit configuration file like this. .PP .Vb 3 \& [Unit] \& Description=My Mojolicious application \& After=network.target \& \& [Service] \& Type=forking \& User=sri \& PIDFile=/home/sri/myapp/script/hypnotoad.pid \& ExecStart=/path/to/hypnotoad /home/sri/myapp/script/my_app \& ExecReload=/path/to/hypnotoad /home/sri/myapp/script/my_app \& KillMode=process \& \& [Install] \& WantedBy=multi\-user.target .Ve .SS "Zero downtime software upgrades" .IX Subsection "Zero downtime software upgrades" Hypnotoad makes zero downtime software upgrades (hot deployment) very simple, as you can see above, but on modern operating systems that support the \f(CW\*(C`SO_REUSEPORT\*(C'\fR socket option, there is also another method available that works with all built-in web servers. .PP .Vb 2 \& $ ./script/my_app prefork \-P /tmp/first.pid \-l http://*:8080?reuse=1 \& Web application available at http://127.0.0.1:8080 .Ve .PP All you have to do, is to start a second web server listening to the same port, and stop the first web server gracefully afterwards. .PP .Vb 3 \& $ ./script/my_app prefork \-P /tmp/second.pid \-l http://*:8080?reuse=1 \& Web application available at http://127.0.0.1:8080 \& $ kill \-s TERM \`cat /tmp/first.pid\` .Ve .PP Just remember that both web servers need to be started with the \f(CW\*(C`reuse\*(C'\fR parameter. .SS Nginx .IX Subsection "Nginx" One of the most popular setups these days is Hypnotoad behind an Nginx reverse proxy, which even supports WebSockets in newer versions. .PP .Vb 10 \& upstream myapp { \& server 127.0.0.1:8080; \& } \& server { \& listen 80; \& server_name localhost; \& location / { \& proxy_pass http://myapp; \& proxy_http_version 1.1; \& proxy_set_header Upgrade $http_upgrade; \& proxy_set_header Connection "upgrade"; \& proxy_set_header Host $host; \& proxy_set_header X\-Forwarded\-For $proxy_add_x_forwarded_for; \& proxy_set_header X\-Forwarded\-Proto $scheme; \& } \& } .Ve .SS Apache/mod_proxy .IX Subsection "Apache/mod_proxy" Another good reverse proxy is Apache with \f(CW\*(C`mod_proxy\*(C'\fR, the configuration looks quite similar to the Nginx one above. And if you need WebSocket support, newer versions come with \f(CW\*(C`mod_proxy_wstunnel\*(C'\fR. .PP .Vb 12 \& \& ServerName localhost \& \& Require all granted \& \& ProxyRequests Off \& ProxyPreserveHost On \& ProxyPass /echo ws://localhost:8080/echo \& ProxyPass / http://localhost:8080/ keepalive=On \& ProxyPassReverse / http://localhost:8080/ \& RequestHeader set X\-Forwarded\-Proto "http" \& .Ve .SS Apache/CGI .IX Subsection "Apache/CGI" \&\f(CW\*(C`CGI\*(C'\fR is supported out of the box and your Mojolicious application will automatically detect that it is executed as a \f(CW\*(C`CGI\*(C'\fR script. Its use in production environments is discouraged though, because as a result of how \f(CW\*(C`CGI\*(C'\fR works, it is very slow and many web servers are making it exceptionally hard to configure properly. Additionally, many real-time web features, such as WebSockets, are not available. .PP .Vb 1 \& ScriptAlias / /home/sri/my_app/script/my_app/ .Ve .SS Envoy .IX Subsection "Envoy" Mojolicious applications can be deployed on cloud-native environments that use Envoy , such as with this reverse proxy configuration similar to the Apache and Nginx ones above. .PP .Vb 10 \& static_resources: \& listeners: \& \- name: listener_0 \& address: \& socket_address: { address: 0.0.0.0, port_value: 80 } \& filter_chains: \& \- filters: \& \- name: envoy.filters.network.http_connection_manager \& typed_config: \& "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager \& codec_type: auto \& stat_prefix: index_http \& route_config: \& name: local_route \& virtual_hosts: \& \- name: service \& domains: ["*"] \& routes: \& \- match: \& prefix: "/" \& route: \& cluster: local_service \& upgrade_configs: \& \- upgrade_type: websocket \& http_filters: \& \- name: envoy.filters.http.router \& typed_config: \& clusters: \& \- name: local_service \& connect_timeout: 0.25s \& type: strict_dns \& lb_policy: round_robin \& load_assignment: \& cluster_name: local_service \& endpoints: \& \- lb_endpoints: \& \- endpoint: \& address: \& socket_address: { address: mojo, port_value: 8080 } .Ve .PP While this configuration works for simple applications, Envoy's typical use case is for implementing proxies of applications as a "service mesh" providing advanced filtering, load balancing, and observability features, such as seen in Istio . For more examples, visit the Envoy documentation . .SS PSGI/Plack .IX Subsection "PSGI/Plack" PSGI is an interface between Perl web frameworks and web servers, and Plack is a Perl module and toolkit that contains PSGI middleware, helpers and adapters to web servers. PSGI and Plack are inspired by Python's WSGI and Ruby's Rack. Mojolicious applications are ridiculously simple to deploy with Plack, but be aware that many real-time web features, such as WebSockets, are not available. .PP .Vb 1 \& $ plackup ./script/my_app .Ve .PP Plack provides many server and protocol adapters for you to choose from, such as \f(CW\*(C`FCGI\*(C'\fR, \f(CW\*(C`uWSGI\*(C'\fR and \f(CW\*(C`mod_perl\*(C'\fR. .PP .Vb 1 \& $ plackup ./script/my_app \-s FCGI \-l /tmp/myapp.sock .Ve .PP The \f(CW\*(C`MOJO_REVERSE_PROXY\*(C'\fR environment variable can be used to enable proxy support, this allows Mojolicious to automatically pick up the \f(CW\*(C`X\-Forwarded\-For\*(C'\fR and \f(CW\*(C`X\-Forwarded\-Proto\*(C'\fR headers. .PP .Vb 1 \& $ MOJO_REVERSE_PROXY=1 plackup ./script/my_app .Ve .PP If an older server adapter is unable to correctly detect the application home directory, you can simply use the \&\f(CW\*(C`MOJO_HOME\*(C'\fR environment variable. .PP .Vb 1 \& $ MOJO_HOME=/home/sri/my_app plackup ./script/my_app .Ve .PP There is no need for a \f(CW\*(C`.psgi\*(C'\fR file, just point the server adapter at your application script, it will automatically act like one if it detects the presence of a \f(CW\*(C`PLACK_ENV\*(C'\fR environment variable. .SS "Plack middleware" .IX Subsection "Plack middleware" Wrapper scripts like \f(CW\*(C`myapp.fcgi\*(C'\fR are a great way to separate deployment and application logic. .PP .Vb 2 \& #!/usr/bin/env plackup \-s FCGI \& use Plack::Builder; \& \& builder { \& enable \*(AqDeflater\*(Aq; \& require \*(Aq./script/my_app\*(Aq; \& }; .Ve .PP Mojo::Server::PSGI can be used directly to load and customize applications in the wrapper script. .PP .Vb 3 \& #!/usr/bin/env plackup \-s FCGI \& use Mojo::Server::PSGI; \& use Plack::Builder; \& \& builder { \& enable \*(AqDeflater\*(Aq; \& my $server = Mojo::Server::PSGI\->new; \& $server\->load_app(\*(Aq./script/my_app\*(Aq); \& $server\->app\->config(foo => \*(Aqbar\*(Aq); \& $server\->to_psgi_app; \& }; .Ve .PP But you could even use middleware right in your application. .PP .Vb 2 \& use Mojolicious::Lite \-signatures; \& use Plack::Builder; \& \& get \*(Aq/welcome\*(Aq => sub ($c) { \& $c\->render(text => \*(AqHello Mojo!\*(Aq); \& }; \& \& builder { \& enable \*(AqDeflater\*(Aq; \& app\->start; \& }; .Ve .SS Rewriting .IX Subsection "Rewriting" Sometimes you might have to deploy your application in a blackbox environment where you can't just change the server configuration or behind a reverse proxy that passes along additional information with \f(CW\*(C`X\-Forwarded\-*\*(C'\fR headers. In such cases you can use the hook "before_dispatch" in Mojolicious to rewrite incoming requests. .PP .Vb 5 \& # Change scheme if "X\-Forwarded\-HTTPS" header is set \& $app\->hook(before_dispatch => sub ($c) { \& $c\->req\->url\->base\->scheme(\*(Aqhttps\*(Aq) \& if $c\->req\->headers\->header(\*(AqX\-Forwarded\-HTTPS\*(Aq); \& }); .Ve .PP Since reverse proxies generally don't pass along information about path prefixes your application might be deployed under, rewriting the base path of incoming requests is also quite common. This allows "url_for" in Mojolicious::Controller for example, to generate portable URLs based on the current environment. .PP .Vb 5 \& # Move first part and slash from path to base path in production mode \& $app\->hook(before_dispatch => sub ($c) { \& push @{$c\->req\->url\->base\->path\->trailing_slash(1)}, \& shift @{$c\->req\->url\->path\->leading_slash(0)}; \& }) if $app\->mode eq \*(Aqproduction\*(Aq; .Ve .PP Mojo::URL objects are very easy to manipulate, just make sure that the URL (\f(CW\*(C`foo/bar?baz=yada\*(C'\fR), which represents the routing destination, is always relative to the base URL (\f(CW\*(C`http://example.com/myapp/\*(C'\fR), which represents the deployment location of your application. .SS "Deployment specific plugins" .IX Subsection "Deployment specific plugins" Deployment specific 3rd party plugins such as Mojolicious::Plugin::SetUserGroup do not need to be included in your application code. They can also be loaded later on via the reserved \f(CW\*(C`plugins\*(C'\fR value for Mojolicious applications that are using any one of the built-in configuration plugins Mojolicious::Plugin::Config, Mojolicious::Plugin::JSONConfig or Mojolicious::Plugin::NotYAMLConfig. .PP .Vb 6 \& # myapp.conf \& { \& plugins => [ \& {SetUserGroup => {user => \*(Aqsri\*(Aq, group => \*(Aqstaff\*(Aq}} \& ] \& }; .Ve .SS "Application embedding" .IX Subsection "Application embedding" From time to time you might want to reuse parts of Mojolicious applications like configuration files, database connection or helpers for other scripts, with this little Mojo::Server based mock server you can just embed them. .PP .Vb 1 \& use Mojo::Server; \& \& # Load application with mock server \& my $server = Mojo::Server\->new; \& my $app = $server\->load_app(\*(Aq./myapp.pl\*(Aq); \& \& # Access fully initialized application \& say for @{$app\->static\->paths}; \& say $app\->config\->{secret_identity}; \& say $app\->dumper({just => \*(Aqa helper test\*(Aq}); \& say $app\->build_controller\->render_to_string(template => \*(Aqfoo\*(Aq); .Ve .PP The plugin Mojolicious::Plugin::Mount uses this functionality to allow you to combine multiple applications into one and deploy them together. .PP .Vb 1 \& use Mojolicious::Lite; \& \& app\->config(hypnotoad => {listen => [\*(Aqhttp://*:80\*(Aq]}); \& \& plugin Mount => {\*(Aqtest1.example.com\*(Aq => \*(Aq/home/sri/myapp1.pl\*(Aq}; \& plugin Mount => {\*(Aqtest2.example.com\*(Aq => \*(Aq/home/sri/myapp2.pl\*(Aq}; \& \& app\->start; .Ve .SS "Web server embedding" .IX Subsection "Web server embedding" You can also use "one_tick" in Mojo::IOLoop to embed the built-in web server Mojo::Server::Daemon into alien environments like foreign event loops that for some reason can't just be integrated with a new reactor backend. .PP .Vb 3 \& use Mojolicious::Lite; \& use Mojo::IOLoop; \& use Mojo::Server::Daemon; \& \& # Normal action \& get \*(Aq/\*(Aq => {text => \*(AqHello World!\*(Aq}; \& \& # Connect application with web server and start accepting connections \& my $daemon = Mojo::Server::Daemon\->new(app => app, listen => [\*(Aqhttp://*:8080\*(Aq]); \& $daemon\->start; \& \& # Call "one_tick" repeatedly from the alien environment \& Mojo::IOLoop\->one_tick while 1; .Ve .SH "REAL-TIME WEB" .IX Header "REAL-TIME WEB" The real-time web is a collection of technologies that include Comet (long polling), EventSource and WebSockets, which allow content to be pushed to consumers with long-lived connections as soon as it is generated, instead of relying on the more traditional pull model. All built-in web servers use non-blocking I/O and are based on the Mojo::IOLoop event loop, which provides many very powerful features that allow real-time web applications to scale up to thousands of concurrent client connections. .SS "Backend web services" .IX Subsection "Backend web services" Since Mojo::UserAgent is also based on the Mojo::IOLoop event loop, it won't block the built-in web servers when used non-blocking, even for high latency backend web services. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # Search MetaCPAN for "mojolicious" \& get \*(Aq/\*(Aq => sub ($c) { \& $c\->ua\->get(\*(Aqfastapi.metacpan.org/v1/module/_search?q=mojolicious\*(Aq => sub ($ua, $tx) { \& $c\->render(\*(Aqmetacpan\*(Aq, hits => $tx\->result\->json\->{hits}{hits}); \& }); \& }; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ metacpan.html.ep \& \& \& MetaCPAN results for "mojolicious" \& \& % for my $hit (@$hits) { \&

<%= $hit\->{_source}{release} %>

\& % } \& \& .Ve .PP The callback passed to "get" in Mojo::UserAgent will be executed once the request to the backend web service has been finished, this is called continuation-passing style. .SS "Synchronizing non-blocking operations" .IX Subsection "Synchronizing non-blocking operations" Multiple non-blocking operations, such as concurrent requests, can be easily synchronized with promises and "all" in Mojo::Promise. You create Mojo::Promise objects manually or use methods like "get_p" in Mojo::UserAgent that create them for you. .PP .Vb 3 \& use Mojolicious::Lite \-signatures; \& use Mojo::Promise; \& use Mojo::URL; \& \& # Search MetaCPAN for "mojo" and "minion" \& get \*(Aq/\*(Aq => sub ($c) { \& \& # Create two promises \& my $url = Mojo::URL\->new(\*(Aqhttp://fastapi.metacpan.org/v1/module/_search\*(Aq); \& my $mojo = $c\->ua\->get_p($url\->clone\->query({q => \*(Aqmojo\*(Aq})); \& my $minion = $c\->ua\->get_p($url\->clone\->query({q => \*(Aqminion\*(Aq})); \& \& # Render a response once both promises have been resolved \& Mojo::Promise\->all($mojo, $minion)\->then(sub ($mojo, $minion) { \& $c\->render(json => { \& mojo => $mojo\->[0]\->result\->json(\*(Aq/hits/hits/0/_source/release\*(Aq), \& minion => $minion\->[0]\->result\->json(\*(Aq/hits/hits/0/_source/release\*(Aq) \& }); \& })\->catch(sub ($err) { \& $c\->reply\->exception($err); \& })\->wait; \& }; \& \& app\->start; .Ve .PP To create promises manually you just wrap your continuation-passing style APIs in functions that return promises. Here's an example for how "get_p" in Mojo::UserAgent works internally. .PP .Vb 2 \& use Mojo::UserAgent; \& use Mojo::Promise; \& \& # Wrap a user agent method with a promise \& my $ua = Mojo::UserAgent\->new; \& sub get_p { \& my $promise = Mojo::Promise\->new; \& $ua\->get(@_ => sub ($ua, $tx) { \& my $err = $tx\->error; \& $promise\->resolve($tx) if !$err || $err\->{code}; \& $promise\->reject($err\->{message}); \& }); \& return $promise; \& } \& \& # Use our new promise generating function \& get_p(\*(Aqhttps://mojolicious.org\*(Aq)\->then(sub ($tx) { \& say $tx\->result\->dom\->at(\*(Aqtitle\*(Aq)\->text; \& })\->wait; .Ve .PP Promises have three states, they start out as \f(CW\*(C`pending\*(C'\fR and you call "resolve" in Mojo::Promise to transition them to \&\f(CW\*(C`fulfilled\*(C'\fR, or "reject" in Mojo::Promise to transition them to \f(CW\*(C`rejected\*(C'\fR. .SS async/await .IX Subsection "async/await" And if you have Future::AsyncAwait installed you can make using promises even easier. The \f(CW\*(C`async\*(C'\fR and \f(CW\*(C`await\*(C'\fR keywords are enabled with the \f(CW\*(C`\-async_await\*(C'\fR flag of Mojo::Base, and make the use of closures with promises completely optional. .PP .Vb 1 \& use Mojo::Base \-strict, \-async_await; .Ve .PP The \f(CW\*(C`async\*(C'\fR keyword is placed before the \f(CW\*(C`sub\*(C'\fR keyword, and means that this function always returns a promise. Returned values that are not Mojo::Promise objects will be wrapped in a resolved promise automatically. And if an exception gets thrown in the function it will result in a rejected promise. .PP .Vb 1 \& use Mojo::Base \-strict, \-async_await; \& \& async sub hello_p { \& return \*(AqHello Mojo!\*(Aq; \& } \& \& hello_p()\->then(sub { say @_ })\->wait; .Ve .PP The \f(CW\*(C`await\*(C'\fR keyword on the other hand makes Perl wait for the promise to be settled. It then returns the fulfillment values or throws an exception with the rejection reason. While waiting, the event loop is free to perform other tasks however, so no resources are wasted. .PP .Vb 3 \& use Mojo::Base \-strict, \-signatures, \-async_await; \& use Mojo::UserAgent; \& use Mojo::URL; \& \& my $ua = Mojo::UserAgent\->new; \& \& # Search MetaCPAN non\-blocking for multiple terms sequentially \& async sub search_cpan_p ($terms) { \& my $cpan = Mojo::URL\->new(\*(Aqhttp://fastapi.metacpan.org/v1/module/_search\*(Aq); \& my @urls = map { $cpan\->clone\->query(q => $_) } @$terms; \& \& for my $url (@urls) { \& my $tx = await $ua\->get_p($url); \& say $tx\->result\->json(\*(Aq/hits/hits/0/_source/release\*(Aq); \& } \& } \& \& search_cpan_p([\*(Aqmojo\*(Aq, \*(Aqminion\*(Aq])\->wait; .Ve .PP The loop above performs all requests sequentially, awaiting a result before sending the next request. But you can also perform those requests concurrently instead, by using methods like "all" in Mojo::Promise to combine multiple promises before awaiting the results. .PP .Vb 4 \& use Mojo::Base \-strict, \-signatures, \-async_await; \& use Mojo::Promise; \& use Mojo::UserAgent; \& use Mojo::URL; \& \& my $ua = Mojo::UserAgent\->new; \& \& # Search MetaCPAN non\-blocking for multiple terms concurrently \& async sub search_cpan_p ($terms) { \& my $cpan = Mojo::URL\->new(\*(Aqhttp://fastapi.metacpan.org/v1/module/_search\*(Aq); \& my @urls = map { $cpan\->clone\->query(q => $_) } @$terms; \& \& my @promises = map { $ua\->get_p($_) } @urls; \& my @results = await Mojo::Promise\->all(@promises); \& for my $result (@results) { \& say $result\->[0]\->result\->json(\*(Aq/hits/hits/0/_source/release\*(Aq); \& } \& } \& \& search_cpan_p([\*(Aqmojo\*(Aq, \*(Aqminion\*(Aq])\->wait; .Ve .PP All of this also means that you can use normal Perl exception handling again. Even many 3rd party exception handling modules from CPAN work just fine. .PP .Vb 2 \& use Mojo::Base \-strict, \-async_await; \& use Mojo::Promise; \& \& # Catch a non\-blocking exception \& async sub hello_p { \& eval { await Mojo::Promise\->reject(\*(AqThis is an exception\*(Aq) }; \& if (my $err = $@) { warn "Error: $err" } \& } \& \& hello_p()\->wait; .Ve .PP And it works just the same in Mojolicious and Mojolicious::Lite applications. Just declare your actions with the \&\f(CW\*(C`async\*(C'\fR keyword and use \f(CW\*(C`await\*(C'\fR to wait for promises to be \f(CW\*(C`fulfilled\*(C'\fR or \f(CW\*(C`rejected\*(C'\fR. .PP .Vb 1 \& use Mojolicious::Lite \-signatures, \-async_await; \& \& # Request HTML titles from two sites non\-blocking \& get \*(Aq/\*(Aq => async sub ($c) { \& my $mojo_tx = await $c\->ua\->get_p(\*(Aqhttps://mojolicious.org\*(Aq); \& my $mojo_title = $mojo_tx\->result\->dom\->at(\*(Aqtitle\*(Aq)\->text; \& my $cpan_tx = await $c\->ua\->get_p(\*(Aqhttps://metacpan.org\*(Aq); \& my $cpan_title = $cpan_tx\->result\->dom\->at(\*(Aqtitle\*(Aq)\->text; \& \& $c\->render(json => {mojo => $mojo_title, cpan => $cpan_title}); \& }; \& \& app\->start; .Ve .PP Promises returned by actions will automatically get the default Mojolicious exception handler attached. Making it much harder to ever miss a non-blocking exception again, even if you forgot to handle it yourself. .SS Timers .IX Subsection "Timers" Timers, another primary feature of the event loop, are created with "timer" in Mojo::IOLoop and can, for example, be used to delay rendering of a response, and unlike \f(CW\*(C`sleep\*(C'\fR, won't block any other requests that might be processed concurrently. .PP .Vb 2 \& use Mojolicious::Lite \-signatures; \& use Mojo::IOLoop; \& \& # Wait 3 seconds before rendering a response \& get \*(Aq/\*(Aq => sub ($c) { \& Mojo::IOLoop\->timer(3 => sub ($ioloop) { \& $c\->render(text => \*(AqDelayed by 3 seconds!\*(Aq); \& }); \& }; \& \& app\->start; .Ve .PP Recurring timers created with "recurring" in Mojo::IOLoop are slightly more powerful, but need to be stopped manually, or they would just keep getting emitted. .PP .Vb 2 \& use Mojolicious::Lite \-signatures; \& use Mojo::IOLoop; \& \& # Count to 5 in 1 second steps \& get \*(Aq/\*(Aq => sub ($c) { \& \& # Start recurring timer \& my $i = 1; \& my $id = Mojo::IOLoop\->recurring(1 => sub ($ioloop) { \& $c\->write_chunk($i); \& $c\->finish if $i++ == 5; \& }); \& \& # Stop recurring timer \& $c\->on(finish => sub ($c) { Mojo::IOLoop\->remove($id) }); \& }; \& \& app\->start; .Ve .PP Timers are not tied to a specific request or connection, and can even be created at startup time. .PP .Vb 2 \& use Mojolicious::Lite \-signatures; \& use Mojo::IOLoop; \& \& # Check title in the background every 10 seconds \& my $title = \*(AqGot no title yet.\*(Aq; \& Mojo::IOLoop\->recurring(10 => sub ($ioloop) { \& app\->ua\->get(\*(Aqhttps://mojolicious.org\*(Aq => sub ($ua, $tx) { \& $title = $tx\->result\->dom\->at(\*(Aqtitle\*(Aq)\->text; \& }); \& }); \& \& # Show current title \& get \*(Aq/\*(Aq => sub ($c) { \& $c\->render(json => {title => $title}); \& }; \& \& app\->start; .Ve .PP Just remember that all these non-blocking operations are processed cooperatively, so your callbacks shouldn't block for too long. .SS Subprocesses .IX Subsection "Subprocesses" You can also use subprocesses, created with "subprocess" in Mojo::IOLoop, to perform computationally expensive operations without blocking the event loop. .PP .Vb 2 \& use Mojolicious::Lite \-signatures; \& use Mojo::IOLoop; \& \& # Operation that would block the event loop for 5 seconds \& get \*(Aq/\*(Aq => sub ($c) { \& Mojo::IOLoop\->subprocess\->run_p(sub { \& sleep 5; \& return \*(Aq♥\*(Aq, \*(AqMojolicious\*(Aq; \& })\->then(sub (@results) { \& $c\->render(text => "I $results[0] $results[1]!"); \& })\->catch(sub ($err) { \& $c\->reply\->exception($err); \& }); \& }; \& \& app\->start; .Ve .PP The callback passed to "run_p" in Mojo::IOLoop::Subprocess will be executed in a child process, without blocking the event loop of the parent process. The results of the callback will then be shared between both processes, and the promise fulfilled or rejected in the parent process. .SS "Exceptions in non-blocking operations" .IX Subsection "Exceptions in non-blocking operations" Since timers and other non-blocking operations are running solely in the event loop, outside of the application, exceptions that get thrown in callbacks can't get caught and handled automatically. But you can handle them manually by subscribing to the event "error" in Mojo::Reactor or catching them inside the callback. .PP .Vb 2 \& use Mojolicious::Lite \-signatures; \& use Mojo::IOLoop; \& \& # Forward error messages to the application log \& Mojo::IOLoop\->singleton\->reactor\->on(error => sub ($reactor, $err) { \& app\->log\->error($err); \& }); \& \& # Exception only gets logged (and connection times out) \& get \*(Aq/connection_times_out\*(Aq => sub ($c) { \& Mojo::IOLoop\->timer(2 => sub ($ioloop) { \& die \*(AqThis request will not be getting a response\*(Aq; \& }); \& }; \& \& # Exception gets caught and handled \& get \*(Aq/catch_exception\*(Aq => sub ($c) { \& Mojo::IOLoop\->timer(2 => sub ($ioloop) { \& eval { die \*(AqThis request will be getting a response\*(Aq }; \& $c\->reply\->exception($@) if $@; \& }); \& }; \& \& app\->start; .Ve .PP A default subscriber that turns all errors into warnings will usually be added by Mojo::IOLoop as a fallback. .PP .Vb 1 \& Mojo::IOLoop\->singleton\->reactor\->unsubscribe(\*(Aqerror\*(Aq); .Ve .PP During development or for applications where crashing is simply preferable, you can also make every exception that gets thrown in a callback fatal by removing all of its subscribers. .SS "WebSocket web service" .IX Subsection "WebSocket web service" The WebSocket protocol offers full bi-directional low-latency communication channels between clients and servers. Receive messages just by subscribing to events such as "message" in Mojo::Transaction::WebSocket with "on" in Mojolicious::Controller and return them with "send" in Mojolicious::Controller. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # Template with browser\-side code \& get \*(Aq/\*(Aq => \*(Aqindex\*(Aq; \& \& # WebSocket echo service \& websocket \*(Aq/echo\*(Aq => sub ($c) { \& \& # Opened \& $c\->app\->log\->debug(\*(AqWebSocket opened\*(Aq); \& \& # Increase inactivity timeout for connection a bit \& $c\->inactivity_timeout(300); \& \& # Incoming message \& $c\->on(message => sub ($c, $msg) { \& $c\->send("echo: $msg"); \& }); \& \& # Closed \& $c\->on(finish => sub ($c, $code, $reason = undef) { \& $c\->app\->log\->debug("WebSocket closed with status $code"); \& }); \& }; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ index.html.ep \& \& \& Echo \& \& \& \& .Ve .PP The event "finish" in Mojo::Transaction::WebSocket will be emitted right after the WebSocket connection has been closed. .PP .Vb 1 \& $c\->tx\->with_compression; .Ve .PP You can activate \f(CW\*(C`permessage\-deflate\*(C'\fR compression with "with_compression" in Mojo::Transaction::WebSocket, this can result in much better performance, but also increases memory usage by up to 300KiB per connection. .PP .Vb 1 \& my $proto = $c\->tx\->with_protocols(\*(Aqv2.proto\*(Aq, \*(Aqv1.proto\*(Aq); .Ve .PP You can also use "with_protocols" in Mojo::Transaction::WebSocket to negotiate a subprotocol. .SS "EventSource web service" .IX Subsection "EventSource web service" EventSource is a special form of long polling where you can use "write" in Mojolicious::Controller to directly send DOM events from servers to clients. It is uni-directional, that means you will have to use Ajax requests for sending data from clients to servers, the advantage however is low infrastructure requirements, since it reuses the HTTP protocol for transport. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # Template with browser\-side code \& get \*(Aq/\*(Aq => \*(Aqindex\*(Aq; \& \& # EventSource for log messages \& get \*(Aq/events\*(Aq => sub ($c) { \& \& # Increase inactivity timeout for connection a bit \& $c\->inactivity_timeout(300); \& \& # Change content type and finalize response headers \& $c\->res\->headers\->content_type(\*(Aqtext/event\-stream\*(Aq); \& $c\->write; \& \& # Subscribe to "message" event and forward "log" events to browser \& my $cb = $c\->app\->log\->on(message => sub ($log, $level, @lines) { \& $c\->write("event:log\endata: [$level] @lines\en\en"); \& }); \& \& # Unsubscribe from "message" event again once we are done \& $c\->on(finish => sub ($c) { \& $c\->app\->log\->unsubscribe(message => $cb); \& }); \& }; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ index.html.ep \& \& \& LiveLog \& \& \& \& .Ve .PP The event "message" in Mojo::Log will be emitted for every new log message and the event "finish" in Mojo::Transaction right after the transaction has been finished. .SS "Streaming multipart uploads" .IX Subsection "Streaming multipart uploads" Mojolicious contains a very sophisticated event system based on Mojo::EventEmitter, with ready-to-use events on almost all layers, and which can be combined to solve some of the hardest problems in web development. .PP .Vb 2 \& use Mojolicious::Lite \-signatures; \& use Scalar::Util qw(weaken); \& \& # Intercept multipart uploads and log each chunk received \& hook after_build_tx => sub ($tx, $app) { \& \& # Subscribe to "upgrade" event to identify multipart uploads \& weaken $tx; \& $tx\->req\->content\->on(upgrade => sub ($single, $multi) { \& return unless $tx\->req\->url\->path\->contains(\*(Aq/upload\*(Aq); \& \& # Subscribe to "part" event to find the right one \& $multi\->on(part => sub ($multi, $single) { \& \& # Subscribe to "body" event of part to make sure we have all headers \& $single\->on(body => sub ($single) { \& \& # Make sure we have the right part and replace "read" event \& return unless $single\->headers\->content_disposition =~ /example/; \& $single\->unsubscribe(\*(Aqread\*(Aq)\->on(read => sub ($single, $bytes) { \& \& # Log size of every chunk we receive \& $app\->log\->debug(length($bytes) . \*(Aq bytes uploaded\*(Aq); \& }); \& }); \& }); \& }); \& }; \& \& # Upload form in DATA section \& get \*(Aq/\*(Aq => \*(Aqindex\*(Aq; \& \& # Streaming multipart upload \& post \*(Aq/upload\*(Aq => {text => \*(AqUpload was successful.\*(Aq}; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ index.html.ep \& \& \& Streaming multipart upload \& \& %= form_for upload => (enctype => \*(Aqmultipart/form\-data\*(Aq) => begin \& %= file_field \*(Aqexample\*(Aq \& %= submit_button \*(AqUpload\*(Aq \& % end \& \& .Ve .SS "More event loops" .IX Subsection "More event loops" Internally, the Mojo::IOLoop event loop can use multiple reactor backends, EV for example, will be automatically used if possible. Which in turn allows other event loops like AnyEvent to just work. .PP .Vb 3 \& use Mojolicious::Lite \-signatures; \& use EV; \& use AnyEvent; \& \& # Wait 3 seconds before rendering a response \& get \*(Aq/\*(Aq => sub ($c) { \& my $w; \& $w = AE::timer 3, 0, sub { \& $c\->render(text => \*(AqDelayed by 3 seconds!\*(Aq); \& undef $w; \& }; \& }; \& \& app\->start; .Ve .SH "USER AGENT" .IX Header "USER AGENT" When we say Mojolicious is a web framework we actually mean it, with Mojo::UserAgent there's a full featured HTTP and WebSocket user agent built right in. .SS "REST web services" .IX Subsection "REST web services" Requests can be performed very comfortably with methods like "get" in Mojo::UserAgent, and always result in a Mojo::Transaction::HTTP object, which has many useful attributes and methods. You can check for connection errors with "result" in Mojo::Transaction, or access HTTP request and response information directly through "req" in Mojo::Transaction and "res" in Mojo::Transaction. .PP .Vb 1 \& use Mojo::UserAgent; \& \& # Request a resource and make sure there were no connection errors \& my $ua = Mojo::UserAgent\->new; \& my $tx = $ua\->get(\*(Aqhttps://docs.mojolicious.org/Mojo\*(Aq => {Accept => \*(Aqtext/plain\*(Aq}); \& my $res = $tx\->result; \& \& # Decide what to do with its representation \& if ($res\->is_success) { say $res\->body } \& elsif ($res\->is_error) { say $res\->message } \& elsif ($res\->code == 301) { say $res\->headers\->location } \& else { say \*(AqWhatever...\*(Aq } .Ve .PP While methods like "is_success" in Mojo::Message::Response and "is_error" in Mojo::Message::Response serve as building blocks for more sophisticated REST clients. .SS "Web scraping" .IX Subsection "Web scraping" Scraping information from websites has never been this much fun before. The built-in HTML/XML parser Mojo::DOM is accessible through "dom" in Mojo::Message and supports all CSS selectors that make sense for a standalone parser, it can be a very powerful tool especially for testing web application. .PP .Vb 1 \& use Mojo::UserAgent; \& \& # Fetch website \& my $ua = Mojo::UserAgent\->new; \& my $res = $ua\->get(\*(Aqhttps://docs.mojolicious.org\*(Aq)\->result; \& \& # Extract title \& say \*(AqTitle: \*(Aq, $res\->dom\->at(\*(Aqhead > title\*(Aq)\->text; \& \& # Extract headings \& $res\->dom(\*(Aqh1, h2, h3\*(Aq)\->each(sub ($dom, $i) { \& say \*(AqHeading: \*(Aq, $dom\->all_text; \& }); \& \& # Visit all nodes recursively to extract more than just text \& for my $n ($res\->dom\->descendant_nodes\->each) { \& \& # Text or CDATA node \& print $n\->content if $n\->type eq \*(Aqtext\*(Aq || $n\->type eq \*(Aqcdata\*(Aq; \& \& # Also include alternate text for images \& print $n\->{alt} if $n\->type eq \*(Aqtag\*(Aq && $n\->tag eq \*(Aqimg\*(Aq; \& } .Ve .PP For a full list of available CSS selectors see "SELECTORS" in Mojo::DOM::CSS. .SS "JSON web services" .IX Subsection "JSON web services" Most web services these days are based on the JSON data-interchange format. That's why Mojolicious comes with the possibly fastest pure-Perl implementation Mojo::JSON built right in, which is accessible through "json" in Mojo::Message. .PP .Vb 2 \& use Mojo::UserAgent; \& use Mojo::URL; \& \& # Fresh user agent \& my $ua = Mojo::UserAgent\->new; \& \& # Search MetaCPAN for "mojolicious" and list latest releases \& my $url = Mojo::URL\->new(\*(Aqhttp://fastapi.metacpan.org/v1/release/_search\*(Aq); \& $url\->query({q => \*(Aqmojolicious\*(Aq, sort => \*(Aqdate:desc\*(Aq}); \& for my $hit (@{$ua\->get($url)\->result\->json\->{hits}{hits}}) { \& say "$hit\->{_source}{name} ($hit\->{_source}{author})"; \& } .Ve .SS "Basic authentication" .IX Subsection "Basic authentication" You can just add username and password to the URL, an \f(CW\*(C`Authorization\*(C'\fR header will be automatically generated. .PP .Vb 1 \& use Mojo::UserAgent; \& \& my $ua = Mojo::UserAgent\->new; \& say $ua\->get(\*(Aqhttps://sri:secret@example.com/hideout\*(Aq)\->result\->body; .Ve .PP If you're using Mojo::URL to build the URL, be aware that the userinfo part will not be included if the object is stringified. You'll have to pass the object itself to Mojo::UserAgent or use "to_unsafe_string" in Mojo::URL. .PP .Vb 2 \& use Mojo::UserAgent; \& use Mojo::URL; \& \& my $ua = Mojo::UserAgent\->new; \& my $url = Mojo::URL\->new(\*(Aqhttps://example.com/hideout\*(Aq)\->userinfo(\*(Aqsri:secret\*(Aq); \& say $ua\->get($url)\->result\->body; .Ve .SS "Decorating follow-up requests" .IX Subsection "Decorating follow-up requests" Mojo::UserAgent can automatically follow redirects, the event "start" in Mojo::UserAgent allows you direct access to each transaction right after they have been initialized and before a connection gets associated with them. .PP .Vb 1 \& use Mojo::UserAgent; \& \& # User agent following up to 10 redirects \& my $ua = Mojo::UserAgent\->new(max_redirects => 10); \& \& # Add a witty header to every request \& $ua\->on(start => sub ($ua, $tx) { \& $tx\->req\->headers\->header(\*(AqX\-Bender\*(Aq => \*(AqBite my shiny metal ass!\*(Aq); \& say \*(AqRequest: \*(Aq, $tx\->req\->url\->clone\->to_abs; \& }); \& \& # Request that will most likely get redirected \& say \*(AqTitle: \*(Aq, $ua\->get(\*(Aqgoogle.com\*(Aq)\->result\->dom\->at(\*(Aqhead > title\*(Aq)\->text; .Ve .PP This even works for proxy \f(CW\*(C`CONNECT\*(C'\fR requests. .SS "Content generators" .IX Subsection "Content generators" Content generators can be registered with "add_generator" in Mojo::UserAgent::Transactor to generate the same type of content repeatedly for multiple requests. .PP .Vb 2 \& use Mojo::UserAgent; \& use Mojo::Asset::File; \& \& # Add "stream" generator \& my $ua = Mojo::UserAgent\->new; \& $ua\->transactor\->add_generator(stream => sub ($transactor, $tx, $path) { \& $tx\->req\->content\->asset(Mojo::Asset::File\->new(path => $path)); \& }); \& \& # Send multiple files streaming via PUT and POST \& $ua\->put(\*(Aqhttp://example.com/upload\*(Aq => stream => \*(Aq/home/sri/mojo.png\*(Aq); \& $ua\->post(\*(Aqhttp://example.com/upload\*(Aq => stream => \*(Aq/home/sri/minion.png\*(Aq); .Ve .PP The \f(CW\*(C`json\*(C'\fR, \f(CW\*(C`form\*(C'\fR and \f(CW\*(C`multipart\*(C'\fR content generators are always available. .PP .Vb 1 \& use Mojo::UserAgent; \& \& # Send "application/json" content via PATCH \& my $ua = Mojo::UserAgent\->new; \& my $tx = $ua\->patch(\*(Aqhttp://api.example.com\*(Aq => json => {foo => \*(Aqbar\*(Aq}); \& \& # Send query parameters via GET \& my $tx2 = $ua\->get(\*(Aqsearch.example.com\*(Aq => form => {q => \*(Aqtest\*(Aq}); \& \& # Send "application/x\-www\-form\-urlencoded" content via POST \& my $tx3 = $ua\->post(\*(Aqhttp://search.example.com\*(Aq => form => {q => \*(Aqtest\*(Aq}); \& \& # Send "multipart/form\-data" content via PUT \& my $tx4 = $ua\->put(\*(Aqupload.example.com\*(Aq => form => {test => {content => \*(AqHello World!\*(Aq}}); \& \& # Send custom multipart content via PUT \& my $tx5 = $ua\->put(\*(Aqapi.example.com\*(Aq => multipart => [\*(AqHello\*(Aq, \*(AqWorld!\*(Aq]); .Ve .PP For more information about available content generators see also "tx" in Mojo::UserAgent::Transactor. .SS "Large file downloads" .IX Subsection "Large file downloads" When downloading large files with Mojo::UserAgent you don't have to worry about memory usage at all, because it will automatically stream everything above 250KiB into a temporary file, which can then be moved into a permanent file with "save_to" in Mojo::Message. .PP .Vb 1 \& use Mojo::UserAgent; \& \& # Fetch the latest Mojolicious tarball \& my $ua = Mojo::UserAgent\->new(max_redirects => 5); \& my $tx = $ua\->get(\*(Aqhttps://www.github.com/mojolicious/mojo/tarball/main\*(Aq); \& $tx\->result\->save_to(\*(Aqmojo.tar.gz\*(Aq); .Ve .PP To protect you from excessively large files there is also a limit of 2GiB by default, which you can tweak with the attribute "max_response_size" in Mojo::UserAgent. .PP .Vb 2 \& # Increase limit to 10GiB \& $ua\->max_response_size(10737418240); .Ve .SS "Large file upload" .IX Subsection "Large file upload" Uploading a large file is even easier. .PP .Vb 1 \& use Mojo::UserAgent; \& \& # Upload file via POST and "multipart/form\-data" \& my $ua = Mojo::UserAgent\->new; \& $ua\->post(\*(Aqexample.com/upload\*(Aq => form => {image => {file => \*(Aq/home/sri/hello.png\*(Aq}}); .Ve .PP And once again you don't have to worry about memory usage, all data will be streamed directly from the file. .SS "Streaming response" .IX Subsection "Streaming response" Receiving a streaming response can be really tricky in most HTTP clients, but Mojo::UserAgent makes it actually easy. .PP .Vb 1 \& use Mojo::UserAgent; \& \& # Accept responses of indefinite size \& my $ua = Mojo::UserAgent\->new(max_response_size => 0); \& \& # Build a normal transaction \& my $tx = $ua\->build_tx(GET => \*(Aqhttp://example.com\*(Aq); \& \& # Replace "read" events to disable default content parser \& $tx\->res\->content\->unsubscribe(\*(Aqread\*(Aq)\->on(read => sub ($content, $bytes) { \& say "Streaming: $bytes"; \& }); \& \& # Process transaction \& $tx = $ua\->start($tx); .Ve .PP The event "read" in Mojo::Content will be emitted for every chunk of data that is received, even chunked transfer encoding and gzip content encoding will be handled transparently if necessary. .SS "Streaming request" .IX Subsection "Streaming request" Sending a streaming request is almost just as easy. .PP .Vb 1 \& use Mojo::UserAgent; \& \& # Build a normal transaction \& my $ua = Mojo::UserAgent\->new; \& my $tx = $ua\->build_tx(POST => \*(Aqhttp://example.com\*(Aq); \& \& # Prepare body \& my $body = \*(AqHello World!\*(Aq; \& $tx\->req\->headers\->content_length(length $body); \& \& # Start writing directly with a drain callback \& my $drain = sub ($content) { \& my $chunk = substr $body, 0, 1, \*(Aq\*(Aq; \& $content\->write($chunk, length $body ? _\|_SUB_\|_ : undef); \& }; \& $tx\->req\->content\->$drain; \& \& # Process transaction \& $tx = $ua\->start($tx); .Ve .PP The drain callback passed to "write" in Mojo::Content will be executed whenever the entire previous chunk of data has actually been written. .SS Non-blocking .IX Subsection "Non-blocking" Mojo::UserAgent has been designed from the ground up to be non-blocking, the whole blocking API is just a simple convenience wrapper. Especially for high latency tasks like web crawling this can be extremely useful, because you can keep many concurrent connections active at the same time. .PP .Vb 2 \& use Mojo::UserAgent; \& use Mojo::IOLoop; \& \& # Concurrent non\-blocking requests \& my $ua = Mojo::UserAgent\->new; \& $ua\->get(\*(Aqhttps://metacpan.org/search?q=mojo\*(Aq => sub ($ua, $mojo) { \& say $mojo\->result\->dom\->at(\*(Aqtitle\*(Aq)\->text; \& }); \& $ua\->get(\*(Aqhttps://metacpan.org/search?q=minion\*(Aq => sub ($ua, $minion) { \& say $minion\->result\->dom\->at(\*(Aqtitle\*(Aq)\->text; \& }); \& \& # Start event loop if necessary \& Mojo::IOLoop\->start unless Mojo::IOLoop\->is_running; .Ve .PP But don't try to open too many connections to one server at the same time, it might get overwhelmed. Better use a queue to process requests in smaller batches. .PP .Vb 2 \& use Mojo::Promise; \& use Mojo::UserAgent; \& \& my @urls = ( \& \*(Aqhttps://docs.mojolicious.org/Mojo/DOM\*(Aq, \*(Aqhttps://docs.mojolicious.org/Mojo\*(Aq, \& \*(Aqhttps://docs.mojolicious.org/Mojo/File\*(Aq, \*(Aqhttps://docs.mojolicious.org/Mojo/URL\*(Aq \& ); \& \& # User agent with a custom name, following up to 5 redirects \& my $ua = Mojo::UserAgent\->new(max_redirects => 5); \& $ua\->transactor\->name(\*(AqMyParallelCrawler 1.0\*(Aq); \& \& # Use a promise to keep the event loop running until we are done \& my $promise = Mojo::Promise\->new; \& my $count = 0; \& my $fetch = sub { \& \& # Stop if there are no more URLs \& return unless my $url = shift @urls; \& \& # Fetch the next title \& $ua\->get($url => sub ($ua, $tx) { \& say "$url: ", $tx\->result\->dom\->at(\*(Aqtitle\*(Aq)\->text; \& \& # Next request \& _\|_SUB_\|_\->(); \& $promise\->resolve if \-\-$count == 0; \& }); \& $count++; \& }; \& \& # Process two requests at a time \& $fetch\->() for 1 .. 2; \& $promise\->wait; .Ve .PP It is also strongly recommended to respect every sites \f(CW\*(C`robots.txt\*(C'\fR file as well as terms of service, and to wait a little before reopening connections to the same host, or the operators might be forced to block your access. .SS "Concurrent blocking requests" .IX Subsection "Concurrent blocking requests" You might have seen "wait" in Mojo::Promise already in some examples above. It is used to make non-blocking operations portable, allowing them to work inside an already running event loop or start one on demand. .PP .Vb 2 \& use Mojo::UserAgent; \& use Mojo::Promise; \& \& # Synchronize non\-blocking requests with promises \& my $ua = Mojo::UserAgent\->new; \& my $mojo_promise = $ua\->get_p(\*(Aqhttps://metacpan.org/search?q=mojo\*(Aq); \& my $minion_promise = $ua\->get_p(\*(Aqhttps://metacpan.org/search?q=minion\*(Aq); \& Mojo::Promise\->all($mojo_promise, $minion_promise)\->then(sub ($mojo, $minion) { \& say $mojo\->[0]\->result\->dom\->at(\*(Aqtitle\*(Aq)\->text; \& say $minion\->[0]\->result\->dom\->at(\*(Aqtitle\*(Aq)\->text; \& })\->wait; .Ve .SS WebSockets .IX Subsection "WebSockets" WebSockets are not just for the server-side, you can use "websocket_p" in Mojo::UserAgent to open new connections, which are always non-blocking. The WebSocket handshake uses HTTP, and is a normal \f(CW\*(C`GET\*(C'\fR request with a few additional headers. It can even contain cookies, and is followed by a \f(CW101\fR response from the server, notifying our user agent that the connection has been established and it can start using the bi-directional WebSocket protocol. .PP .Vb 2 \& use Mojo::UserAgent; \& use Mojo::Promise; \& \& # Open WebSocket to echo service \& my $ua = Mojo::UserAgent\->new; \& $ua\->websocket_p(\*(Aqwss://ws.postman\-echo.com/raw\*(Aq)\->then(sub ($tx) { \& \& # Prepare a followup promise so we can wait for messages \& my $promise = Mojo::Promise\->new; \& \& # Wait for WebSocket to be closed \& $tx\->on(finish => sub ($tx, $code, $reason) { \& say "WebSocket closed with status $code."; \& $promise\->resolve; \& }); \& \& # Close WebSocket after receiving one message \& $tx\->on(message => sub ($tx, $msg) { \& say "WebSocket message: $msg"; \& $tx\->finish; \& }); \& \& # Send a message to the server \& $tx\->send(\*(AqHi!\*(Aq); \& \& # Insert a new promise into the promise chain \& return $promise; \& })\->catch(sub ($err) { \& \& # Handle failed WebSocket handshakes and other exceptions \& warn "WebSocket error: $err"; \& })\->wait; .Ve .SS "UNIX domain sockets" .IX Subsection "UNIX domain sockets" Not just TCP/IP sockets are supported, but also UNIX domain sockets, which can have significant security and performance benefits when used for inter-process communication. Instead of \f(CW\*(C`http://\*(C'\fR and \f(CW\*(C`ws://\*(C'\fR you can use the \&\f(CW\*(C`http+unix://\*(C'\fR and \f(CW\*(C`ws+unix://\*(C'\fR schemes, and pass along a percent encoded path (\f(CW\*(C`/\*(C'\fR becomes \f(CW%2F\fR) instead of a hostname. .PP .Vb 2 \& use Mojo::UserAgent; \& use Mojo::Promise; \& \& # GET request via UNIX domain socket "/tmp/foo.sock" \& my $ua = Mojo::UserAgent\->new; \& say $ua\->get(\*(Aqhttp+unix://%2Ftmp%2Ffoo.sock/index.html\*(Aq)\->result\->body; \& \& # GET request with HOST header via UNIX domain socket "/tmp/bar.sock" \& my $tx = $ua\->get(\*(Aqhttp+unix://%2Ftmp%2Fbar.sock\*(Aq => {Host => \*(Aqexample.com\*(Aq}); \& say $tx\->result\->body; \& \& # WebSocket connection via UNIX domain socket "/tmp/baz.sock" \& $ua\->websocket_p(\*(Aqws+unix://%2Ftmp%2Fbaz.sock/echo\*(Aq)\->then(sub ($tx) { \& \& my $promise = Mojo::Promise\->new; \& $tx\->on(finish => sub ($tx) { $promise\->resolve }); \& \& $tx\->on(message => sub ($tx, $msg) { \& say "WebSocket message: $msg"; \& $tx\->finish; \& }); \& $tx\->send(\*(AqHi!\*(Aq); \& \& return $promise; \& })\->catch(sub ($err) { \& warn "WebSocket error: $err"; \& })\->wait; .Ve .PP You can set the \f(CW\*(C`Host\*(C'\fR header manually to pass along a hostname. .SS "Command line" .IX Subsection "Command line" Don't you hate checking huge HTML files from the command line? Thanks to the command Mojolicious::Command::get that is about to change. You can just pick the parts that actually matter with the CSS selectors from Mojo::DOM and JSON Pointers from Mojo::JSON::Pointer. .PP .Vb 1 \& $ mojo get https://mojolicious.org \*(Aqhead > title\*(Aq .Ve .PP How about a list of all id attributes? .PP .Vb 1 \& $ mojo get https://mojolicious.org \*(Aq*\*(Aq attr id .Ve .PP Or the text content of all heading tags? .PP .Vb 1 \& $ mojo get https://mojolicious.org \*(Aqh1, h2, h3\*(Aq text .Ve .PP Maybe just the text of the third heading? .PP .Vb 1 \& $ mojo get https://mojolicious.org \*(Aqh1, h2, h3\*(Aq 3 text .Ve .PP You can also extract all text from nested child elements. .PP .Vb 1 \& $ mojo get https://mojolicious.org \*(Aq#mojobar\*(Aq all .Ve .PP The request can be customized as well. .PP .Vb 1 \& $ mojo get \-M POST \-H \*(AqX\-Bender: Bite my shiny metal ass!\*(Aq http://google.com .Ve .PP Store response data by redirecting \f(CW\*(C`STDOUT\*(C'\fR. .PP .Vb 1 \& $ mojo get mojolicious.org > example.html .Ve .PP Pass request data by redirecting \f(CW\*(C`STDIN\*(C'\fR. .PP .Vb 1 \& $ mojo get \-M PUT mojolicious.org < example.html .Ve .PP Or use the output of another program. .PP .Vb 1 \& $ echo \*(AqHello World\*(Aq | mojo get \-M PUT https://mojolicious.org .Ve .PP Submit forms as \f(CW\*(C`application/x\-www\-form\-urlencoded\*(C'\fR content. .PP .Vb 1 \& $ mojo get \-M POST \-f \*(Aqq=Mojo\*(Aq \-f \*(Aqsize=5\*(Aq https://metacpan.org/search .Ve .PP And upload files as \f(CW\*(C`multipart/form\-data\*(C'\fR content. .PP .Vb 1 \& $ mojo get \-M POST \-f \*(Aqupload=@example.html\*(Aq mojolicious.org .Ve .PP You can follow redirects and view the headers for all messages. .PP .Vb 1 \& $ mojo get \-r \-v http://google.com \*(Aqhead > title\*(Aq .Ve .PP Extract just the information you really need from JSON data structures. .PP .Vb 1 \& $ mojo get https://fastapi.metacpan.org/v1/author/SRI /name .Ve .PP This can be an invaluable tool for testing your applications. .PP .Vb 1 \& $ ./myapp.pl get /welcome \*(Aqhead > title\*(Aq .Ve .SS One-liners .IX Subsection "One-liners" For quick hacks and especially testing, ojo one-liners are also a great choice. .PP .Vb 1 \& $ perl \-Mojo \-E \*(Aqsay g("mojolicious.org")\->dom\->at("title")\->text\*(Aq .Ve .SH APPLICATIONS .IX Header "APPLICATIONS" Fun Mojolicious application hacks for all occasions. .SS "Basic authentication" .IX Subsection "Basic authentication" Basic authentication data will be automatically extracted from the \f(CW\*(C`Authorization\*(C'\fR header. .PP .Vb 2 \& use Mojolicious::Lite \-signatures; \& use Mojo::Util qw(secure_compare); \& \& get \*(Aq/\*(Aq => sub ($c) { \& \& # Check for username "Bender" and password "rocks" \& return $c\->render(text => \*(AqHello Bender!\*(Aq) if secure_compare $c\->req\->url\->to_abs\->userinfo, \*(AqBender:rocks\*(Aq; \& \& # Require authentication \& $c\->res\->headers\->www_authenticate(\*(AqBasic\*(Aq); \& $c\->render(text => \*(AqAuthentication required!\*(Aq, status => 401); \& }; \& \& app\->start; .Ve .PP This can be combined with TLS for a secure authentication mechanism. .PP .Vb 1 \& $ ./myapp.pl daemon \-l \*(Aqhttps://*:3000?cert=./server.crt&key=./server.key\*(Aq .Ve .SS "Adding a configuration file" .IX Subsection "Adding a configuration file" Adding a configuration file to your application is as easy as adding a file to its home directory and loading the plugin Mojolicious::Plugin::Config. The default name is based on the value of "moniker" in Mojolicious (\f(CW\*(C`myapp\*(C'\fR), appended with a \f(CW\*(C`.conf\*(C'\fR extension (\f(CW\*(C`myapp.conf\*(C'\fR). .PP .Vb 5 \& $ mkdir myapp \& $ cd myapp \& $ touch myapp.pl \& $ chmod 744 myapp.pl \& $ echo \*(Aq{name => "my Mojolicious application"};\*(Aq > myapp.conf .Ve .PP Configuration files themselves are just Perl scripts that return a hash reference with configuration settings of your choice. All those settings are then available through the method "config" in Mojolicious and the helper "config" in Mojolicious::Plugin::DefaultHelpers. .PP .Vb 1 \& use Mojolicious::Lite; \& \& plugin \*(AqConfig\*(Aq; \& \& my $name = app\->config(\*(Aqname\*(Aq); \& app\->log\->debug("Welcome to $name"); \& \& get \*(Aq/\*(Aq => \*(Aqwith_config\*(Aq; \& \& app\->start; \& _\|_DATA_\|_ \& @@ with_config.html.ep \& \& \& <%= config \*(Aqname\*(Aq %> \& Welcome to <%= config \*(Aqname\*(Aq %> \& .Ve .PP Alternatively you can also use configuration files in the JSON format with Mojolicious::Plugin::JSONConfig. .SS "Adding a plugin to your application" .IX Subsection "Adding a plugin to your application" To organize your code better and to prevent helpers from cluttering your application, you can use application specific plugins. .PP .Vb 2 \& $ mkdir \-p lib/MyApp/Plugin \& $ touch lib/MyApp/Plugin/MyHelpers.pm .Ve .PP They work just like normal plugins and are also subclasses of Mojolicious::Plugin. Nested helpers with a prefix based on the plugin name are an easy way to avoid conflicts. .PP .Vb 2 \& package MyApp::Plugin::MyHelpers; \& use Mojo::Base \*(AqMojolicious::Plugin\*(Aq, \-signatures; \& \& sub register ($self, $app, $conf) { \& $app\->helper(\*(Aqmy_helpers.render_with_header\*(Aq => sub ($c, @args) { \& $c\->res\->headers\->header(\*(AqX\-Mojo\*(Aq => \*(AqI <3 Mojolicious!\*(Aq); \& $c\->render(@args); \& }); \& } \& \& 1; .Ve .PP You can have as many application specific plugins as you like, the only difference to normal plugins is that you load them using their full class name. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& use lib qw(lib); \& \& plugin \*(AqMyApp::Plugin::MyHelpers\*(Aq; \& \& get \*(Aq/\*(Aq => sub ($c) { \& $c\->my_helpers\->render_with_header(text => \*(AqI ♥ Mojolicious!\*(Aq); \& }; \& \& app\->start; .Ve .PP Of course these plugins can contain more than just helpers, take a look at "PLUGINS" in Mojolicious::Plugins for a few ideas. .SS "Adding commands to Mojolicious" .IX Subsection "Adding commands to Mojolicious" By now you've probably used many of the built-in commands described in Mojolicious::Commands, but did you know that you can just add new ones and that they will be picked up automatically by the command line interface if they are placed in a directory from \f(CW@INC\fR? .PP .Vb 2 \& package Mojolicious::Command::spy; \& use Mojo::Base \*(AqMojolicious::Command\*(Aq, \-signatures; \& \& has description => \*(AqSpy on application\*(Aq; \& has usage => "Usage: APPLICATION spy [TARGET]\en"; \& \& sub run ($self, @args) { \& \& # Leak secret passphrases \& if ($args[0] eq \*(Aqsecrets\*(Aq) { say for @{$self\->app\->secrets} } \& \& # Leak mode \& elsif ($args[0] eq \*(Aqmode\*(Aq) { say $self\->app\->mode } \& } \& \& 1; .Ve .PP Command line arguments are passed right through and there are many useful attributes and methods in Mojolicious::Command that you can use or overload. .PP .Vb 2 \& $ mojo spy secrets \& HelloWorld \& \& $ ./script/myapp spy secrets \& secr3t .Ve .PP And to make your commands application specific, just add a custom namespace to "namespaces" in Mojolicious::Commands and use a class name like \f(CW\*(C`MyApp::Command::spy\*(C'\fR instead of \f(CW\*(C`Mojolicious::Command::spy\*(C'\fR. .PP .Vb 3 \& # Application \& package MyApp; \& use Mojo::Base \*(AqMojolicious\*(Aq, \-signatures; \& \& sub startup ($self) { \& \& # Add another namespace to load commands from \& push @{$self\->commands\->namespaces}, \*(AqMyApp::Command\*(Aq; \& } \& \& 1; .Ve .PP The options \f(CW\*(C`\-h\*(C'\fR/\f(CW\*(C`\-\-help\*(C'\fR, \f(CW\*(C`\-\-home\*(C'\fR and \f(CW\*(C`\-m\*(C'\fR/\f(CW\*(C`\-\-mode\*(C'\fR are handled automatically by Mojolicious::Commands and are shared by all commands. .PP .Vb 2 \& $ ./script/myapp spy \-m production mode \& production .Ve .PP For a full list of shared options see "SYNOPSIS" in Mojolicious::Commands. .SS "Running code against your application" .IX Subsection "Running code against your application" Ever thought about running a quick one-liner against your Mojolicious application to test something? Thanks to the command Mojolicious::Command::eval you can do just that, the application object itself can be accessed via \f(CW\*(C`app\*(C'\fR. .PP .Vb 3 \& $ mojo generate lite\-app myapp.pl \& $ ./myapp.pl eval \*(Aqsay for @{app\->static\->paths}\*(Aq \& $ ./myapp.pl eval \*(Aqsay for sort keys %{app\->renderer\->helpers}\*(Aq .Ve .PP The \f(CW\*(C`verbose\*(C'\fR options will automatically print the return value or returned data structure to \f(CW\*(C`STDOUT\*(C'\fR. .PP .Vb 2 \& $ ./myapp.pl eval \-v \*(Aqapp\->static\->paths\->[0]\*(Aq \& $ ./myapp.pl eval \-V \*(Aqapp\->static\->paths\*(Aq .Ve .SS "Making your application installable" .IX Subsection "Making your application installable" Ever thought about releasing your Mojolicious application to CPAN? It's actually much easier than you might think. .PP .Vb 4 \& $ mojo generate app MyApp \& $ cd my_app \& $ mv public lib/MyApp/ \& $ mv templates lib/MyApp/ .Ve .PP The trick is to move the \f(CW\*(C`public\*(C'\fR and \f(CW\*(C`templates\*(C'\fR directories so they can get automatically installed with the modules. Additionally author commands from the \f(CW\*(C`Mojolicious::Command::Author\*(C'\fR namespace are not usually wanted by an installed application so they can be excluded. .PP .Vb 3 \& # Application \& package MyApp; \& use Mojo::Base \*(AqMojolicious\*(Aq, \-signatures; \& \& use Mojo::File qw(curfile); \& use Mojo::Home; \& \& # Every CPAN module needs a version \& our $VERSION = \*(Aq1.0\*(Aq; \& \& sub startup ($self) { \& \& # Switch to installable home directory \& $self\->home(Mojo::Home\->new(curfile\->sibling(\*(AqMyApp\*(Aq))); \& \& # Switch to installable "public" directory \& $self\->static\->paths\->[0] = $self\->home\->child(\*(Aqpublic\*(Aq); \& \& # Switch to installable "templates" directory \& $self\->renderer\->paths\->[0] = $self\->home\->child(\*(Aqtemplates\*(Aq); \& \& # Exclude author commands \& $self\->commands\->namespaces([\*(AqMojolicious::Command\*(Aq]); \& \& my $r = $self\->routes; \& $r\->get(\*(Aq/\*(Aq)\->to(\*(Aqexample#welcome\*(Aq); \& } \& \& 1; .Ve .PP Finally there is just one small change to be made to the application script. The shebang line becomes the recommended \&\f(CW\*(C`#!perl\*(C'\fR, which the toolchain can rewrite to the proper shebang during installation. .PP .Vb 1 \& #!perl \& \& use strict; \& use warnings; \& \& use Mojo::File qw(curfile); \& use lib curfile\->dirname\->sibling(\*(Aqlib\*(Aq)\->to_string; \& use Mojolicious::Commands; \& \& # Start command line interface for application \& Mojolicious::Commands\->start_app(\*(AqMyApp\*(Aq); .Ve .PP That's really everything, now you can package your application like any other CPAN module. .PP .Vb 5 \& $ ./script/my_app generate makefile \& $ perl Makefile.PL \& $ make test \& $ make manifest \& $ make dist .Ve .PP And if you have a PAUSE account (which can be requested at ) even upload it. .PP .Vb 1 \& $ mojo cpanify \-u USER \-p PASS MyApp\-0.01.tar.gz .Ve .SS Proxy .IX Subsection "Proxy" While every Mojolicious application has the built-in user agent "ua" in Mojolicious::Plugin::DefaultHelpers for you to perform requests to backend web services, this is not always the most efficient solution. The specialized proxy helpers "proxy\->get_p" in Mojolicious::Plugin::DefaultHelpers and "proxy\->start_p" in Mojolicious::Plugin::DefaultHelpers can stream response content straight to the client, as soon as a new chunk of data is received from the backend web service. Additionally they will take care of removing hop-by-hop headers and protect you automatically from backpressure issues. Which can happen in situations where the connection to the backend web service is faster than the connection to the client and data forwarding needs to be throttled. And the best of all, everything happens non-blocking, that means your web server can process other requests concurrently while waiting for I/O. .PP .Vb 1 \& use Mojolicious::Lite \-signatures; \& \& # Just forward the response \& get \*(Aq/\*(Aq => sub ($c) { \& $c\->proxy\->get_p(\*(Aqhttps://mojolicious.org\*(Aq)\->catch(sub ($err) { \& $c\->log\->error("Proxy error: $err"); \& $c\->render(text => \*(AqCould not connect to backend web service!\*(Aq, status => 400); \& }); \& }; \& \& # Forward response and customize a few things \& get \*(Aq/*docs\*(Aq => sub ($c) { \& \& # Custom request \& my $tx = $c\->ua\->build_tx(GET => \*(Aqhttps://docs.mojolicious.org\*(Aq); \& my $docs = $c\->param(\*(Aqdocs\*(Aq); \& $tx\->req\->url\->path("/$docs"); \& $tx\->req\->headers\->user_agent(\*(AqMojoProxy/1.0\*(Aq); \& \& # Start non\-blocking request \& $c\->proxy\->start_p($tx)\->catch(sub ($err) { \& $c\->log\->error("Proxy error: $err"); \& $c\->render(text => \*(AqCould not connect to backend web service!\*(Aq, status => 400); \& }); \& \& # Custom response \& $tx\->res\->content\->once(body => sub ($content) { \& $c\->res\->headers\->server(\*(AqMojoProxy/1.0\*(Aq); \& }); \& }; \& \& app\->start; .Ve .PP All proxy helpers return a Mojo::Promise object, which should be used to handle connection errors to backend web services gracefully. And if you ever need to forward all headers from the client to the backend web service, make sure to use "dehop" in Mojo::Headers to remove all hop-by-hop headers. .PP .Vb 4 \& # Clone and modify request headers \& my $headers = $c\->req\->headers\->clone\->dehop; \& $headers\->accept(\*(Aqapplication/json\*(Aq); \& my $tx = $c\->ua\->build_tx(PUT => \*(Aqhttps://mojolicious.org\*(Aq => $headers\->to_hash); .Ve .SS "Hello World" .IX Subsection "Hello World" If every byte matters this is the smallest \f(CW\*(C`Hello World\*(C'\fR application you can write with Mojolicious::Lite. .PP .Vb 3 \& use Mojolicious::Lite; \& any {text => \*(AqHello World!\*(Aq}; \& app\->start; .Ve .PP It works because all routes without a pattern default to \f(CW\*(C`/\*(C'\fR and automatic rendering kicks in even if no actual code gets executed by the router. The renderer just picks up the \f(CW\*(C`text\*(C'\fR value from the stash and generates a response. .SS "Hello World one-liners" .IX Subsection "Hello World one-liners" The \f(CW\*(C`Hello World\*(C'\fR example above can get even a little bit shorter in an ojo one-liner. .PP .Vb 1 \& $ perl \-Mojo \-E \*(Aqa({text => "Hello World!"})\->start\*(Aq daemon .Ve .PP And you can use all the commands from Mojolicious::Commands. .PP .Vb 1 \& $ perl \-Mojo \-E \*(Aqa({text => "Hello World!"})\->start\*(Aq get \-v / .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 .