.\" Automatically generated by Pod::Man 2.25 (Pod::Simple 3.16) .\" .\" 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 .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' '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 turned on, 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. .ie \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . nr % 0 . rr F .\} .el \{\ . de IX .. .\} .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "Mojolicious::Guides::Cookbook 3pm" .TH Mojolicious::Guides::Cookbook 3pm "2012-09-05" "perl v5.14.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 \- Cookbook .SH "OVERVIEW" .IX Header "OVERVIEW" This document cotains many fun recipes for cooking with Mojolicious. .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 reactor, 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 \s-1HTTP\s0 1.1 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/myapp daemon \& Server available at http://127.0.0.1:3000. .Ve .PP It has many configuration options and is known to work on every platform Perl works on. .PP .Vb 2 \& $ ./script/myapp daemon \-h \& ...List of available options... .Ve .PP Another huge advantage is that it supports \s-1TLS\s0 and WebSockets out of the box. .PP .Vb 2 \& $ ./script/myapp daemon \-l https://*:3000 \& Server available at https://127.0.0.1:3000. .Ve .PP A development certificate for testing purposes is built right in, so it just works. .SS "Morbo" .IX Subsection "Morbo" After reading the Mojolicious::Lite 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. .PP .Vb 2 \& $ morbo script/myapp \& Server available at http://127.0.0.1:3000. .Ve .SS "Hypnotoad" .IX Subsection "Hypnotoad" For bigger applications Mojolicious contains the \s-1UNIX\s0 optimized preforking web server Mojo::Server::Hypnotoad that will allow you to take advantage of multiple cpu cores and copy-on-write. .PP .Vb 5 \& Mojo::Server::Hypnotoad \& |\- Mojo::Server::Daemon [1] \& |\- Mojo::Server::Daemon [2] \& |\- Mojo::Server::Daemon [3] \& +\- Mojo::Server::Daemon [4] .Ve .PP It is also based on the Mojo::Server::Daemon web server, but optimized specifically for production environments out of the box. .PP .Vb 2 \& $ hypnotoad script/myapp \& Server available at http://127.0.0.1:8080. .Ve .PP You can tweak many configuration settings right from within your application, for a full list see \*(L"\s-1SETTINGS\s0\*(R" in Mojo::Server::Hypnotoad. .PP .Vb 1 \& use Mojolicious::Lite; \& \& app\->config(hypnotoad => {listen => [\*(Aqhttp://*:3000\*(Aq]}); \& \& get \*(Aq/\*(Aq => {text => \*(AqALL 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 or Mojolicious::Config::JSONConfig configuration file. .PP .Vb 2 \& # myapp.conf \& {hypnotoad => {listen => [\*(Aqhttp://*:80\*(Aq], workers => 10}}; .Ve .PP Or change the application configuration directly. .PP But one of its biggest advantages is the support for effortless zero downtime software upgrades. 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/myapp \& 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\-HTTPS\*(C'\fR headers. .PP .Vb 2 \& # myapp.conf \& {hypnotoad => {proxy => 1}}; .Ve .SS "Nginx" .IX Subsection "Nginx" One of the most popular setups these days is the built-in web server behind a Nginx reverse proxy. .PP .Vb 10 \& upstream myapp { \& server 127.0.0.1:8080; \& } \& server { \& listen 80; \& server_name localhost; \& location / { \& proxy_read_timeout 300; \& proxy_pass http://myapp; \& proxy_set_header Host $host; \& proxy_set_header X\-Forwarded\-For $proxy_add_x_forwarded_for; \& proxy_set_header X\-Forwarded\-HTTPS 0; \& } \& } .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 very similar to the Nginx one above. .PP .Vb 12 \& \& ServerName localhost \& \& Order deny,allow \& Allow from all \& \& ProxyRequests Off \& ProxyPreserveHost On \& ProxyPass / http://localhost:8080/ keepalive=On \& ProxyPassReverse / http://localhost:8080/ \& RequestHeader set X\-Forwarded\-HTTPS "0" \& .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. .PP .Vb 1 \& ScriptAlias / /home/sri/myapp/script/myapp/ .Ve .SS "PSGI/Plack" .IX Subsection "PSGI/Plack" \&\s-1PSGI\s0 is an interface between Perl web frameworks and web servers, and Plack is a Perl module and toolkit that contains \s-1PSGI\s0 middleware, helpers and adapters to web servers. \s-1PSGI\s0 and Plack are inspired by Python's \s-1WSGI\s0 and Ruby's Rack. Mojolicious applications are ridiculously simple to deploy with Plack. .PP .Vb 2 \& $ plackup ./script/myapp \& HTTP::Server::PSGI: Accepting connections at http://0:5000/ .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`SCGI\*(C'\fR and \f(CW\*(C`mod_perl\*(C'\fR. Make sure to run \f(CW\*(C`plackup\*(C'\fR from your applications home directory, otherwise libraries might not be found. .PP .Vb 1 \& $ plackup ./script/myapp \-s FCGI \-l /tmp/myapp.sock .Ve .PP Because of the way \f(CW\*(C`plackup\*(C'\fR loads your script, Mojolicious is not always able to detect the applications home directory, if that's the case you can simply use the \f(CW\*(C`MOJO_HOME\*(C'\fR environment variable. Also note that \&\f(CW\*(C`app\->start\*(C'\fR needs to be the last Perl statement in the application script for the same reason. .PP .Vb 2 \& $ MOJO_HOME=/home/sri/myapp plackup ./script/myapp \& HTTP::Server::PSGI: Accepting connections at http://0:5000/ .Ve .PP Some server adapters might ask for a \f(CW\*(C`.psgi\*(C'\fR file, if that's the case you can just point them at your application script because 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 \*(Aqmyapp.pl\*(Aq; \& }; .Ve .PP But you could even use middleware right in your application. .PP .Vb 2 \& use Mojolicious::Lite; \& use Plack::Builder; \& \& get \*(Aq/welcome\*(Aq => sub { \& my $self = shift; \& $self\->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\-*\*(C'\fR headers. In such cases you can use a \f(CW\*(C`before_dispatch\*(C'\fR hook to rewrite incoming requests. .PP .Vb 6 \& # Change scheme if "X\-Forwarded\-Protocol" header is set to "https" \& app\->hook(before_dispatch => sub { \& my $self = shift; \& $self\->req\->url\->base\->scheme(\*(Aqhttps\*(Aq) \& if $self\->req\->headers\->header(\*(AqX\-Forwarded\-Protocol\*(Aq) eq \*(Aqhttps\*(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. .PP .Vb 6 \& # Move first part from path to base path in production mode \& app\->hook(before_dispatch => sub { \& my $self = shift; \& push @{$self\->req\->url\->base\->path\->parts}, \& shift @{$self\->req\->url\->path\->parts}; \& }) if app\->mode eq \*(Aqproduction\*(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 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 $app\->static\->root; \& say $app\->config\->{secret_identity}; \& say $app\->dumper(just => \*(Aqa helper test\*(Aq); .Ve .SS "Web server embedding" .IX Subsection "Web server embedding" You can also use the built-in web server to embed Mojolicious applications into alien environments like foreign event loops. .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 reactor, which provides many very powerful features that allow real-time web applications to scale up to thousands of clients. .SS "Backend web services" .IX Subsection "Backend web services" Since Mojo::UserAgent is also based on the Mojo::IOLoop reactor, 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; \& \& # Search Twitter for "perl" \& get \*(Aq/\*(Aq => sub { \& my $self = shift; \& $self\->ua\->get(\*(Aqhttp://search.twitter.com/search.json?q=perl\*(Aq => sub { \& my ($ua, $tx) = @_; \& $self\->render(\*(Aqtwitter\*(Aq, results => $tx\->res\->json\->{results}); \& }); \& }; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ twitter.html.ep \& \& \& Twitter results for "perl" \& \& % for my $result (@$results) { \&

<%= $result\->{text} %>

\& % } \& \& .Ve .PP Multiple events such as parallel requests can be easily synchronized with a Mojo::IOLoop delay. .PP .Vb 2 \& use Mojolicious::Lite; \& use Mojo::IOLoop; \& \& # Search Twitter for "perl" and "python" \& get \*(Aq/\*(Aq => sub { \& my $self = shift; \& \& # Delay rendering \& my $delay = Mojo::IOLoop\->delay(sub { \& my ($delay, @results) = @_; \& $self\->render(json => {results => \e@results}); \& }); \& \& # First request \& $delay\->begin; \& $self\->ua\->get(\*(Aqhttp://search.twitter.com/search.json?q=perl\*(Aq => sub { \& my ($ua, $tx) = @_; \& $delay\->end($tx\->res\->json\->{results}[0]{text}); \& }); \& \& # Second request \& $delay\->begin; \& $self\->ua\->get(\*(Aqhttp://search.twitter.com/search.json?q=python\*(Aq => sub { \& my ($ua, $tx) = @_; \& $delay\->end($tx\->res\->json\->{results}[0]{text}); \& }); \& }; \& \& app\->start; .Ve .SS "Timers" .IX Subsection "Timers" Another primary feature of the Mojo::IOLoop reactor are timers, which 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 in parallel. .PP .Vb 2 \& use Mojolicious::Lite; \& use Mojo::IOLoop; \& \& # Wait 3 seconds before rendering a response \& get \*(Aq/\*(Aq => sub { \& my $self = shift; \& Mojo::IOLoop\->timer(3 => sub { \& $self\->render(text => \*(AqDelayed by 3 seconds!\*(Aq); \& }); \& }; \& \& app\->start; .Ve .PP Recurring timers are slightly more powerful, but need to be stopped manually, or they would just keep getting emitted. .PP .Vb 2 \& use Mojolicious::Lite; \& use Mojo::IOLoop; \& \& # Count to 5 in 1 second steps \& get \*(Aq/\*(Aq => sub { \& my $self = shift; \& \& # Start recurring timer \& my $i = 1; \& my $id = Mojo::IOLoop\->recurring(1 => sub { \& $self\->write_chunk($i); \& $self\->finish if $i++ == 5; \& }); \& \& # Stop recurring timer \& $self\->on(finish => sub { 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; \& use Mojo::IOLoop; \& \& # Count seconds since startup \& my $i = 0; \& Mojo::IOLoop\->recurring(1 => sub { $i++ }); \& \& # Show counter \& get \*(Aq/\*(Aq => sub { \& my $self = shift; \& $self\->render(text => "About $i seconds running!"); \& }; \& \& app\->start; .Ve .PP Since timers and other low level event watchers are also independent from applications, errors can't get logged automatically, you can change that by subscribing to the event \*(L"error\*(R" in Mojo::Reactor. .PP .Vb 5 \& # Forward error messages to the application log \& Mojo::IOLoop\->singleton\->reactor\->on(error => sub { \& my ($reactor, $err) = @_; \& app\->log\->error($err); \& }); .Ve .PP Just remember that all events are processed cooperatively, so your callbacks shouldn't block for too long. .SS "WebSocket web service" .IX Subsection "WebSocket web service" The WebSocket protocol offers full bi-directional low-latency communication channels between clients and servers. Receiving messages is as easy as subscribing to the event \*(L"message\*(R" in Mojo::Transaction::WebSocket with the method \*(L"on\*(R" in Mojolicious::Controller. .PP .Vb 2 \& use Mojolicious::Lite; \& use Mojo::IOLoop; \& \& # Template with browser\-side code \& get \*(Aq/\*(Aq => \*(Aqindex\*(Aq; \& \& # WebSocket echo service \& websocket \*(Aq/echo\*(Aq => sub { \& my $self = shift; \& \& # Connected \& $self\->app\->log\->debug(\*(AqWebSocket connected.\*(Aq); \& \& # Increase inactivity timeout for connection a bit \& Mojo::IOLoop\->stream($self\->tx\->connection)\->timeout(300); \& \& # Incoming message \& $self\->on(message => sub { \& my ($self, $message) = @_; \& $self\->send("echo: $message"); \& }); \& \& # Disconnected \& $self\->on(finish => sub { \& my $self = shift; \& $self\->app\->log\->debug(\*(AqWebSocket disconnected.\*(Aq); \& }); \& }; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ index.html.ep \& \& \& Echo \& \& \& \& .Ve .PP The event \*(L"finish\*(R" in Mojo::Transaction::WebSocket will be emitted right after the WebSocket connection has been closed. .SS "Testing WebSocket web services" .IX Subsection "Testing WebSocket web services" While the message flow on WebSocket connections can be rather dynamic, it more often than not is quite predictable, which allows this rather pleasant Test::Mojo \s-1API\s0 to be used. .PP .Vb 2 \& use Test::More tests => 4; \& use Test::Mojo; \& \& # Include application \& use FindBin; \& require "$FindBin::Bin/../echo.pl"; \& \& # Test echo web service \& my $t = Test::Mojo\->new; \& $t\->websocket_ok(\*(Aq/echo\*(Aq) \& \->send_ok(\*(AqHello Mojo!\*(Aq) \& \->message_is(\*(Aqecho: Hello Mojo!\*(Aq) \& \->finish_ok; .Ve .SS "EventSource web service" .IX Subsection "EventSource web service" \&\s-1HTML5\s0 EventSource is a special form of long-polling where you can directly send \s-1DOM\s0 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 \s-1HTTP\s0 protocol for transport. .PP .Vb 2 \& use Mojolicious::Lite; \& use Mojo::IOLoop; \& \& # Template with browser\-side code \& get \*(Aq/\*(Aq => \*(Aqindex\*(Aq; \& \& # EventSource for log messages \& get \*(Aq/events\*(Aq => sub { \& my $self = shift; \& \& # Increase inactivity timeout for connection a bit \& Mojo::IOLoop\->stream($self\->tx\->connection)\->timeout(300); \& \& # Change content type \& $self\->res\->headers\->content_type(\*(Aqtext/event\-stream\*(Aq); \& \& # Subscribe to "message" event and forward "log" events to browser \& my $cb = $self\->app\->log\->on(message => sub { \& my ($log, $level, $message) = @_; \& $self\->write("event:log\endata: [$level] $message\en\en"); \& }); \& \& # Unsubscribe from "message" event again once we are done \& $self\->on(finish => sub { \& my $self = shift; \& $self\->app\->log\->unsubscribe(message => $cb); \& }); \& }; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ index.html.ep \& \& \& LiveLog \& \& \& \& .Ve .PP The event \*(L"message\*(R" in Mojo::Log will be emitted for every new log message and the event \*(L"finish\*(R" 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 hardest problems in web development. .PP .Vb 2 \& use Mojolicious::Lite; \& use Scalar::Util \*(Aqweaken\*(Aq; \& \& # Emit "request" event early for requests that get upgraded to multipart \& hook after_build_tx => sub { \& my $tx = shift; \& weaken $tx; \& $tx\->req\->content\->on(upgrade => sub { $tx\->emit(\*(Aqrequest\*(Aq) }); \& }; \& \& # Upload form in DATA section \& get \*(Aq/\*(Aq => \*(Aqindex\*(Aq; \& \& # Streaming multipart upload (invoked twice, due to early "request" event) \& post \*(Aq/upload\*(Aq => sub { \& my $self = shift; \& \& # First invocation, subscribe to "part" event to find the right one \& return $self\->req\->content\->on(part => sub { \& my ($multi, $single) = @_; \& \& # Subscribe to "body" event of part to make sure we have all headers \& $single\->on(body => sub { \& my $single = shift; \& \& # 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 { \& my ($single, $chunk) = @_; \& \& # Log size of every chunk we receive \& $self\->app\->log\->debug(length($chunk) . \*(Aq bytes uploaded.\*(Aq); \& }); \& }); \& }) unless $self\->req\->is_finished; \& \& # Second invocation, render response \& $self\->render(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 "Event loops" .IX Subsection "Event loops" Internally the Mojo::IOLoop reactor can use multiple event loop backends, \&\s-1EV\s0 for example will be automatically used if installed. Which in turn allows event loops like IO::Async to just work. .PP .Vb 4 \& use Mojolicious::Lite; \& use EV; \& use IO::Async::Loop::EV; \& use IO::Async::Timer::Absolute; \& \& my $loop = IO::Async::Loop::EV\->new; \& \& # Wait 3 seconds before rendering a response \& get \*(Aq/\*(Aq => sub { \& my $self = shift; \& $loop\->add(IO::Async::Timer::Absolute\->new( \& time => time + 3, \& on_expire => sub { $self\->render(text => \*(AqDelayed by 3 seconds!\*(Aq) } \& )); \& }; \& \& app\->start; .Ve .PP Same for AnyEvent. .PP .Vb 3 \& use Mojolicious::Lite; \& use EV; \& use AnyEvent; \& \& # Wait 3 seconds before rendering a response \& get \*(Aq/\*(Aq => sub { \& my $self = shift; \& my $w; \& $w = AE::timer 3, 0, sub { \& $self\->render(text => \*(AqDelayed by 3 seconds!\*(Aq); \& undef $w; \& }; \& }; \& \& app\->start; .Ve .PP Who actually controls the event loop backend is not important. .PP .Vb 3 \& use Mojo::UserAgent; \& use EV; \& use AnyEvent; \& \& # Search Twitter for "perl" \& my $cv = AE::cv; \& my $ua = Mojo::UserAgent\->new; \& $ua\->get(\*(Aqhttp://search.twitter.com/search.json?q=perl\*(Aq => sub { \& my ($ua, $tx) = @_; \& $cv\->send($tx\->res\->json\->{results}[0]{text}); \& }); \& say $cv\->recv; .Ve .PP You could for example just embed the built-in web server into an AnyEvent application. .PP .Vb 4 \& use Mojolicious::Lite; \& use Mojo::Server::Daemon; \& use EV; \& use AnyEvent; \& \& # 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; \& \& # Let AnyEvent take control \& AE::cv\->recv; .Ve .SH "USER AGENT" .IX Header "USER AGENT" When we say Mojolicious is a web framework we actually mean it. .SS "Web scraping" .IX Subsection "Web scraping" Scraping information from web sites has never been this much fun before. The built-in \s-1HTML5/XML\s0 parser Mojo::DOM supports all \s-1CSS3\s0 selectors that make sense for a standalone parser. .PP .Vb 1 \& use Mojo::UserAgent; \& \& # Fetch web site \& my $ua = Mojo::UserAgent\->new; \& my $tx = $ua\->get(\*(Aqmojolicio.us/perldoc\*(Aq); \& \& # Extract title \& say \*(AqTitle: \*(Aq, $tx\->res\->dom\->at(\*(Aqhead > title\*(Aq)\->text; \& \& # Extract headings \& $tx\->res\->dom(\*(Aqh1, h2, h3\*(Aq)\->each(sub { \& say \*(AqHeading: \*(Aq, shift\->all_text; \& }); .Ve .PP Especially for unit testing your Mojolicious applications this can be a very powerful tool. .SS "\s-1JSON\s0 web services" .IX Subsection "JSON web services" Most web services these days are based on the \s-1JSON\s0 data-interchange format. That's why Mojolicious comes with the possibly fastest pure-Perl implementation Mojo::JSON built right in. .PP .Vb 2 \& use Mojo::UserAgent; \& use Mojo::Util \*(Aqencode\*(Aq; \& \& # Fresh user agent \& my $ua = Mojo::UserAgent\->new; \& \& # Fetch the latest news about Mojolicious from Twitter \& my $search = \*(Aqhttp://search.twitter.com/search.json?q=Mojolicious\*(Aq; \& for $tweet (@{$ua\->get($search)\->res\->json\->{results}}) { \& \& # Tweet text \& my $text = $tweet\->{text}; \& \& # Twitter user \& my $user = $tweet\->{from_user}; \& \& # Show both \& say encode(\*(AqUTF\-8\*(Aq, "$text \-\-$user"); \& } .Ve .SS "Basic authentication" .IX Subsection "Basic authentication" You can just add username and password to the \s-1URL\s0. .PP .Vb 1 \& use Mojo::UserAgent; \& \& my $ua = Mojo::UserAgent\->new; \& say $ua\->get(\*(Aqhttps://sri:secret@mojolicio.us/hideout\*(Aq)\->res\->body; .Ve .SS "Decorating followup requests" .IX Subsection "Decorating followup requests" Mojo::UserAgent can automatically follow redirects, the event \&\*(L"start\*(R" 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 { \& my ($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)\->res\->dom\->at(\*(Aqhead > title\*(Aq)\->text; .Ve .PP This even works for proxy \f(CW\*(C`CONNECT\*(C'\fR requests. .SS "Streaming response" .IX Subsection "Streaming response" Receiving a streaming response can be really tricky in most \s-1HTTP\s0 clients, but Mojo::UserAgent makes it actually easy. .PP .Vb 1 \& use Mojo::UserAgent; \& \& # Build a normal transaction \& my $ua = Mojo::UserAgent\->new; \& my $tx = $ua\->build_tx(GET => \*(Aqhttp://mojolicio.us\*(Aq); \& \& # Replace "read" events to disable default content parser \& $tx\->res\->content\->unsubscribe(\*(Aqread\*(Aq)\->on(read => sub { \& my ($content, $chunk) = @_; \& say "Streaming: $chunk"; \& }); \& \& # Process transaction \& $ua\->start($tx); .Ve .PP The event \*(L"read\*(R" in Mojo::Content will be emitted for every chunk of data that is received, even \f(CW\*(C`chunked\*(C'\fR 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(GET => \*(Aqhttp://mojolicio.us\*(Aq); \& \& # Prepare content \& my $content = \*(AqHello world!\*(Aq; \& $tx\->req\->headers\->content_length(length $content); \& \& # Start writing directly with a drain callback \& my $drain; \& $drain = sub { \& my $req = shift; \& my $chunk = substr $content, 0, 1, \*(Aq\*(Aq; \& $drain = undef unless length $content; \& $req\->write($chunk, $drain); \& }; \& $tx\->req\->$drain; \& \& # Process transaction \& $ua\->start($tx); .Ve .PP The drain callback passed to \*(L"write\*(R" in Mojo::Message will be invoked whenever the entire previous chunk has actually been written. .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 \f(CW\*(C`250KB\*(C'\fR into a temporary file. .PP .Vb 1 \& use Mojo::UserAgent; \& \& # Lets fetch the latest Mojolicious tarball \& my $ua = Mojo::UserAgent\->new(max_redirects => 5); \& my $tx = $ua\->get(\*(Aqlatest.mojolicio.us\*(Aq); \& $tx\->res\->content\->asset\->move_to(\*(Aqmojo.tar.gz\*(Aq); .Ve .PP To protect you from excessively large files there is also a limit of \f(CW\*(C`5MB\*(C'\fR by default, which you can tweak with the \f(CW\*(C`MOJO_MAX_MESSAGE_SIZE\*(C'\fR environment variable. .PP .Vb 2 \& # Increase limit to 1GB \& $ENV{MOJO_MAX_MESSAGE_SIZE} = 1073741824; .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_form(\*(Aqmojolicio.us/upload\*(Aq, \& {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. .PP .Vb 1 \& use Mojo::UserAgent; \& \& # Upload file via PUT \& my $ua = Mojo::UserAgent\->new; \& my $asset = Mojo::Asset::File\->new(path => \*(Aq/home/sri/hello.png\*(Aq); \& my $tx = $ua\->build_tx(PUT => \*(Aqmojolicio.us/upload\*(Aq); \& $tx\->req\->content\->asset($asset); \& $ua\->start($tx); .Ve .SS "Non-blocking" .IX Subsection "Non-blocking" Mojo::UserAgent has been designed from the ground up to be non-blocking, the whole blocking \s-1API\s0 is just a simple convenience wrapper. Especially for high latency tasks like web crawling this can be extremely useful, because you can keep many parallel connections active at the same time. .PP .Vb 3 \& use Mojo::UserAgent; \& use Mojo::IOLoop; \& use Mojo::URL; \& \& # FIFO queue \& my @urls = (\*(Aqgoogle.com\*(Aq); \& \& # User agent following up to 5 redirects \& my $ua = Mojo::UserAgent\->new(max_redirects => 5); \& \& # Crawler \& my $crawl; \& $crawl = sub { \& my $id = shift; \& \& # Dequeue or wait for more URLs \& return Mojo::IOLoop\->timer(2 => sub { $crawl\->($id) }) \& unless my $url = shift @urls; \& \& # Fetch non\-blocking just by adding a callback \& $ua\->get($url => sub { \& my ($ua, $tx) = @_; \& \& # Extract URLs \& say "[$id] $url"; \& $tx\->res\->dom(\*(Aqa[href]\*(Aq)\->each(sub { \& my $e = shift; \& \& # Build absolute URL \& my $url = Mojo::URL\->new($e\->{href})\->to_abs($tx\->req\->url); \& say " \-> $url"; \& \& # Enqueue \& push @urls, $url; \& }); \& \& # Next \& $crawl\->($id); \& }); \& }; \& \& # Start a bunch of parallel crawlers sharing the same user agent \& $crawl\->($_) for 1 .. 3; \& \& # Start reactor if necessary \& Mojo::IOLoop\->start unless Mojo::IOLoop\->is_running; .Ve .PP You can take full control of the Mojo::IOLoop reactor. .SS "Parallel blocking requests" .IX Subsection "Parallel blocking requests" You can emulate blocking behavior by using a Mojo::IOLoop delay to synchronize multiple non-blocking requests. Just be aware that the resulting transactions will be in random order. .PP .Vb 2 \& use Mojo::UserAgent; \& use Mojo::IOLoop; \& \& # Synchronize non\-blocking requests and capture result \& my $ua = Mojo::UserAgent\->new; \& my $delay = Mojo::IOLoop\->delay; \& $ua\->get(\*(Aqhttp://mojolicio.us\*(Aq => $delay\->begin); \& $ua\->get(\*(Aqhttp://mojolicio.us/perldoc\*(Aq => $delay\->begin); \& my ($tx, $tx2) = $delay\->wait; .Ve .PP The event \*(L"finish\*(R" in Mojo::IOLoop::Delay can be used for code that needs to be able to work standalone as well as inside Mojolicious applications. .PP .Vb 2 \& use Mojo::UserAgent; \& use Mojo::IOLoop; \& \& # Synchronize non\-blocking requests portably \& my $ua = Mojo::UserAgent\->new; \& my $delay = Mojo::IOLoop\->delay(sub { \& my ($delay, $tx, $tx2) = @_; \& ... \& }); \& $ua\->get(\*(Aqhttp://mojolicio.us\*(Aq => $delay\->begin); \& $ua\->get(\*(Aqhttp://mojolicio.us/perldoc\*(Aq => $delay\->begin); \& $delay\->wait unless Mojo::IOLoop\->is_running; .Ve .SS "Command line" .IX Subsection "Command line" Don't you hate checking huge \s-1HTML\s0 files from the command line? Thanks to the \&\f(CW\*(C`mojo get\*(C'\fR command that is about to change. You can just pick the parts that actually matter with the \s-1CSS3\s0 selectors from Mojo::DOM and \s-1JSON\s0 Pointers from Mojo::JSON::Pointer. .PP .Vb 1 \& $ mojo get http://mojolicio.us \*(Aqhead > title\*(Aq .Ve .PP How about a list of all id attributes? .PP .Vb 1 \& $ mojo get http://mojolicio.us \*(Aq*\*(Aq attr id .Ve .PP Or the text content of all heading tags? .PP .Vb 1 \& $ mojo get http://mojolicio.us \*(Aqh1, h2, h3\*(Aq text .Ve .PP Maybe just the text of the third heading? .PP .Vb 1 \& $ mojo get http://mojolicio.us \*(Aqh1, h2, h3\*(Aq 3 text .Ve .PP You can also extract all text from nested child elements. .PP .Vb 1 \& $ mojo get http://mojolicio.us \*(Aq#mojobar\*(Aq all .Ve .PP The request can be customized as well. .PP .Vb 2 \& $ mojo get \-M POST \-c \*(AqHello!\*(Aq http://mojolicio.us \& $ mojo get \-H \*(AqX\-Bender: Bite my shiny metal ass!\*(Aq http://google.com .Ve .PP You can follow redirects and view the headers for all messages. .PP .Vb 1 \& $ mojo get \-r \-v http://reddit.com \*(Aqhead > title\*(Aq .Ve .PP Extract just the information you really need from \s-1JSON\s0 data structures. .PP .Vb 1 \& $ mojo get http://search.twitter.com/search.json /error .Ve .PP This can be an invaluable tool for testing your applications. .PP .Vb 1 \& $ ./myapp.pl get /welcome \*(Aqhead > title\*(Aq .Ve .SS "Oneliners" .IX Subsection "Oneliners" For quick hacks and especially testing, ojo oneliners are also a great choice. .PP .Vb 1 \& $ perl \-Mojo \-E \*(Aqsay g("mojolicio.us")\->dom\->html\->head\->title\->text\*(Aq .Ve .SH "HACKS" .IX Header "HACKS" Fun hacks you might not use very often but that might come in handy some day. .SS "Adding commands to Mojolicious" .IX Subsection "Adding commands to Mojolicious" By now you've propably 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? .PP .Vb 2 \& package Mojolicious::Command::spy; \& use Mojo::Base \*(AqMojo::Command\*(Aq; \& \& has description => "Spy on application.\en"; \& has usage => "usage: $0 spy [TARGET]\en"; \& \& sub run { \& my ($self, $whatever) = @_; \& \& # Leak secret passphrase \& if ($whatever eq \*(Aqsecret\*(Aq) { \& my $secret = $self\->app\->secret; \& say qq{The secret of this application is "$secret".}; \& } \& } \& \& 1; .Ve .PP There are many more useful methods and attributes in Mojo::Command that you can use or overload. .PP .Vb 2 \& $ mojo spy secret \& The secret of this application is "Mojolicious::Lite". \& \& $ ./myapp.pl spy secret \& The secret of this application is "secr3t". .Ve .SS "Running code against your application" .IX Subsection "Running code against your application" Ever thought about running a quick oneliner against your Mojolicious application to test something? Thanks to the \f(CW\*(C`eval\*(C'\fR command you can do just that, the application object itself can be accessed via \f(CW\*(C`app\*(C'\fR. .PP .Vb 2 \& $ mojo generate lite_app \& $ ./myapp.pl eval \*(Aqsay app\->static\->root\*(Aq .Ve .PP The \f(CW\*(C`verbose\*(C'\fR option will automatically print the return value to \f(CW\*(C`STDOUT\*(C'\fR. .PP .Vb 1 \& $ ./myapp.pl eval \-v \*(Aqapp\->static\->root\*(Aq .Ve .SS "Making your application installable" .IX Subsection "Making your application installable" Ever thought about releasing your Mojolicious application to \s-1CPAN\s0? It's actually much easier than you might think. .PP .Vb 4 \& $ mojo generate app \& $ cd my_mojolicious_app \& $ mv public lib/MyMojoliciousApp/ \& $ mv templates lib/MyMojoliciousApp/ .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. .PP .Vb 2 \& package MyMojoliciousApp; \& use Mojo::Base \*(AqMojolicious\*(Aq; \& \& use File::Basename \*(Aqdirname\*(Aq; \& use File::Spec::Functions \*(Aqcatdir\*(Aq; \& \& # Every CPAN module needs a version \& our $VERSION = \*(Aq1.0\*(Aq; \& \& sub startup { \& my $self = shift; \& \& # Switch to installable home directory \& $self\->home\->parse(catdir(dirname(_\|_FILE_\|_), \*(AqMyMojoliciousApp\*(Aq)); \& \& # Switch to installable "public" directory \& $self\->static\->paths\->[0] = $self\->home\->rel_dir(\*(Aqpublic\*(Aq); \& \& # Switch to installable "templates" directory \& $self\->renderer\->paths\->[0] = $self\->home\->rel_dir(\*(Aqtemplates\*(Aq); \& \& $self\->plugin(\*(AqPODRenderer\*(Aq); \& \& my $r = $self\->routes; \& $r\->get(\*(Aq/welcome\*(Aq)\->to(\*(Aqexample#welcome\*(Aq); \& } \& \& 1; .Ve .PP That's really everything, now you can package your application like any other \&\s-1CPAN\s0 module. .PP .Vb 5 \& $ ./script/my_mojolicious_app generate makefile \& $ perl Makefile.PL \& $ make test \& $ make manifest \& $ make dist .Ve .PP And if you have a \f(CW\*(C`PAUSE\*(C'\fR account (which can be requested at ) even upload it. .PP .Vb 1 \& $ mojo cpanify \-u USER \-p PASS MyMojoliciousApp\-0.01.tar.gz .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 oneliners" .IX Subsection "Hello World oneliners" The \f(CW\*(C`Hello World\*(C'\fR example above can get even a little bit shorter in an ojo oneliner. .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.