Search code examples
perlmojolicious

Documentation on Serving static files


I have a question about the docs for serving static files... It claims

Static files are automatically served from the public directories of the application, which can be customized with "paths" in Mojolicious::Static, or one of the DATA sections from "classes" in Mojolicious::Static. And if that's not enough you can also serve them manually with "reply->static" in Mojolicious::Plugin::DefaultHelpers and "reply->file" in Mojolicious::Plugin::DefaultHelpers.

What does it mean by automatically served from public directories and how does it differ from manually serving them?

I guess my question is -> How do you access or use the automatically served pages in your code?


Solution

  • This is also briefly covered in the tutorial. Basically, before going through the dynamic routes you add with get and so on, it will check if the requested file path is provided in your public directories or data sections. By default the only public directory assigned is public/ in your application root. And by default the only class whose __DATA__ section is checked is main (as __DATA__ section templates are most commonly used for Mojolicious::Lite apps in a single file script).

    So as a real example, if you get a request for /foo.txt, it will first check if there is a public/foo.txt file or a foo.txt in the __DATA__ section for the main package. If it finds one, it will be served as-is, with some optimizations for browsers that cache static files. If not, it will try to match it to the routes you have declared.

    The paths and classes attributes in the Mojolicious::Static object for your application (accessible as the static attribute on the application) can be changed or appended during startup with other places to look.

    push @{$app->static->paths}, $app->home->child('other');
    $app->static->classes(['Some::Class']);