Mojolicious Documentation

repository·main·Indexed 25 days ago

https://github.com/mojolicious/mojo

A real-time Perl web framework and toolkit for building scalable, cloud-native web applications. It provides components for HTTP and WebSocket communication, supporting everything from Mojolicious::Lite prototypes to complex MVC applications. Includes a suite of CLI tools for scaffolding (mojo generate), deployment (cpanify), and server management (daemon, prefork, cgi), as well as a built-in User Agent for HTTP requests via the 'get' command.

Tokens
6.5K
Snippets
19
Records
32
Agent score
82%

What's inside Mojolicious

  1. Install Mojolicious

    main

    You can install Mojolicious using a single command via cpanmin. It is recommended to use a perlbrew environment for managing your Perl installations.

    $ curl -L https://cpanmin.us | perl - -M https://cpan.metacpan.org -n Mojolicious
  2. Run a Mojolicious application with morbo

    main

    To run your application using the built-in development web server, use the morbo command. This server supports features like hot deployment and is ideal for development.

    $ morbo hello.pl
    Web application available at http://127.0.0.1:3000
  3. Get started with a Mojolicious web application

    main

    You can create a minimal web application using Mojolicious::Lite. This example defines a single route for the root path (/) that returns a plain text response.

    use Mojolicious::Lite;
    
    get '/' => {text => 'I ♥ Mojolicious!'};
    
    app->start;
  4. Run a Mojolicious application with prefork

    main

    Use the prefork command to start your Mojolicious application using the Mojo::Server::Prefork backend. This allows for a multi-worker HTTP and WebSocket server setup.

    Basic Usage:

    ./myapp.pl prefork

    Common Examples:

    • Run in production mode on port 8080: ./myapp.pl prefork -m production -p -l http://*:8080
    • Listen on multiple locations: ./myapp.pl prefork -l http://127.0.0.1:8080 -l https://[::]:8081
    • Use a Unix socket with 12 workers: ./myapp.pl prefork -l http+unix://%2Ftmp%2Fmyapp.sock -w 12
    • Configure SSL with specific certificate and key: ./myapp.pl prefork -l 'https://*:443?cert=./server.crt&key=./server.key'
    ./myapp.pl prefork
  5. Extract data using Selectors or JSON Pointers

    main

    After the URL, you can provide a SELECTOR (CSS selector for HTML/XML) or a JSON-POINTER (starting with /) to extract specific data from the response body.

    CSS Selector Commands: Once a selector is provided, you can chain commands to process the results:

    • [number]: Select a specific index (e.g., 0, 1).
    • text: Return the text content of the matched elements.
    • all: Return all text content from matched elements.
    • attr [name]: Return the value of a specific attribute (e.g., attr href).

    JSON Pointer: If the selector starts with /, it is treated as a JSON Pointer to navigate the parsed JSON response.

    # CSS Selector examples
    mojo get mojolicious.org 'head > title' text
    mojo get mojolicious.org a attr href
    mojo get mojolicious.org 'h1, h2, h3' 3 text
    
    # JSON Pointer example
    mojo get https://fastapi.metacpan.org/v1/author/SRI /name
  6. Generate a Mojolicious application with 'mojo generate app'

    main

    Use the mojo generate app command to scaffold a fully functional Mojolicious application directory structure. This includes the application class, a controller, configuration files, templates, static files, and a basic test suite.

    Usage

    # Generate an application with the default name (MyApp)
    mojo generate app
    
    # Generate an application named 'TestApp'
    mojo generate app TestApp
    
    # Generate an application using a namespaced class
    mojo generate app My::TestApp
    mojo generate app TestApp
  7. Run a Mojolicious application as a daemon

    main

    Use the daemon command to start your Mojolicious application with an HTTP and WebSocket server using the Mojo::Server::Daemon backend. This is a core command available by default in Mojolicious applications.

    Basic Usage

    ./myapp.pl daemon

    Common Scenarios

    Run in production mode on a specific port:

    ./myapp.pl daemon -m production -p -l http://*:8080

    Listen on multiple interfaces (HTTP and HTTPS):

    ./myapp.pl daemon -l http://127.0.0.1:8080 -l https://[::]:8081

    Use SSL with specific certificate and key files:

    ./myapp.pl daemon -l 'https://*:443?cert=./server.crt&key=./server.key'

    Use a Unix domain socket:

    ./myapp.pl daemon -l http+unix://%2Ftmp%2Fmyapp.sock

    Configure reverse proxy with trusted networks:

    ./myapp.pl daemon -l http://127.0.0.1:8080 -p 127.0.0.0/8 -p fc00::/7
  8. Create a real-time web application with WebSockets and templates

    main

    Mojolicious allows you to combine RESTful routes, WebSocket services, and embedded templates (using the __DATA__ section) in a single file. This example demonstrates a WebSocket service that fetches the <title> of a provided URL using the built-in User Agent (ua) and DOM parser.

    use Mojolicious::Lite -signatures;
    
    # Render template "index.html.ep" from the DATA section
    get '/' => sub ($c) {
      $c->render(template => 'index');
    };
    
    # WebSocket service used by the template to extract the title from a website
    websocket '/title' => sub ($c) {
      $c->on(message => sub ($c, $msg) {
        my $title = $c->ua->get($msg)->result->dom->at('title')->text;
        $c->send($title);
      });
    };
    
    app->start;
    __DATA__
    
    @@ index.html.ep
    % my $url = url_for 'title';
    <script>
      const ws = new WebSocket('<%= $url->to_abs %>');
      ws.onmessage = function (event) { document.body.innerHTML += event.data };
      ws.onopen    = function (event) { ws.send('https://mojolicious.org') };
    </script>
  9. Configure Mojolicious::Command::prefork options

    main

    The prefork command accepts several options to tune the server behavior.

    OptionFlagDescription
    accepts-a, --accepts <number>Number of connections for workers to accept (default: 10000)
    backlog-b, --backlog <size>Listen backlog size (default: SOMAXCONN)
    clients-c, --clients <number>Maximum number of concurrent connections (default: 1000)
    graceful-timeout-G, --graceful-timeout <seconds>Graceful timeout in seconds (default: 120)
    heartbeat-interval-I, --heartbeat-interval <seconds>Heartbeat interval in seconds (default: 5)
    heartbeat-timeout-H, --heartbeat-timeout <seconds>Heartbeat timeout in seconds (default: 50)
    inactivity-timeout-i, --inactivity-timeout <seconds>Inactivity timeout in seconds (default: MOJO_INACTIVITY_TIMEOUT or 30)
    keep-alive-timeout-k, --keep-alive-timeout <seconds>Keep-alive timeout in seconds (default: MOJO_KEEP_ALIVE_TIMEOUT or 5)
    listen-l, --listen <location>One or more locations to listen on (default: MOJO_LISTEN or http://*:3000)
    pid-file-P, --pid-file <path>Path to process id file (default: prefork.pid in a temporary directory)
    proxy-p, --proxy [<network>]Activate reverse proxy support. Optionally takes one or more trusted proxy addresses or networks
    requests-r, --requests <number>Maximum number of requests per keep-alive connection (default: 100)
    spare-s, --spare <number>Temporarily spawn up to this number of additional workers (default: 2)
    workers-w, --workers <number>Number of workers (default: 4)
    mode-m, --mode <name>Operating mode (default: MOJO_MODE/PLACK_ENV or development)
    home--home <path>Path to home directory (default: MOJO_HOME or auto-detection)
  10. Configure the psgi command options

    main

    When using the psgi command, you can specify the following options:

    OptionLong FlagDescription
    -h--helpShow this summary of available options
    --home <path>Path to home directory of your application. Defaults to the value of MOJO_HOME or auto-detection.
    -m--mode <name>Operating mode for your application. Defaults to the value of MOJO_MODE/PLACK_ENV or "development".
    Options:
        -h, --help          Show this summary of available options
            --home <path>   Path to home directory of your application, defaults to
                            the value of MOJO_HOME or auto-detection
        -m, --mode <name>   Operating mode for your application, defaults to the
                            value of MOJO_MODE/PLACK_ENV or "development"
  11. Options for the inflate command

    main

    The inflate command supports the following options:

    OptionLong FlagDescription
    -h--helpShow this summary of available options
    --home <path>Path to home directory of your application, defaults to the value of MOJO_HOME or auto-detection
    -m--mode <name>Operating mode for your application, defaults to the value of MOJO_MODE/PLACK_ENV or "development"
    Usage: APPLICATION inflate [OPTIONS]
    
    Options:
        -h, --help          Show this summary of available options
            --home <path>   Path to home directory of your application, defaults to
                            the value of MOJO_HOME or auto-detection
        -m, --mode <name>   Operating mode for your application, defaults to the
                            value of MOJO_MODE/PLACK_ENV or "development"
  12. Use `eval` command options to inspect application data

    main

    When using the eval command, you can use the following flags to control how the result of your code is outputted:

    OptionFlagDescription
    --verbose-vPrint the return value to STDOUT
    --home <path>Path to home directory of your application (defaults to MOJO_HOME or auto-detection)
    --mode <name>-mOperating mode for your application (defaults to MOJO_MODE, PLACK_ENV, or "development")
    (Data Dumper)-VPrint the returned data structure to STDOUT using app->dumper