Dancer2::Config(3)
π Dancer2::Config β Configure Dancer2 to suit your needs π
Okay so this is the user-contributed Perl documentation for Dancer2::Config(3), and it is literally your little guide to making Dancer2 behave exactly how you want. π«Ά
β¨ VERSION β¨
version 1.1.2
πΈ DESCRIPTION πΈ
The Dancer2 configuration (as implemented by Dancer2::Core::Role::ConfigReader) handles reading and changing the configuration of your Dancer2 apps. This document describes how to manipulate Dancer2's configuration settings (through code or by file), and to document the various settings that are available in Dancer2. No cap. π
π MANIPULATING SETTINGS VIA CODE π
You can change a setting with the keyword set:
use Dancer2;
# changing default settings
set port => 8080;
set content_type => 'text/plain';
set startup_info => 0;
π MANIPULATING SETTINGS VIA CONFIGURATION FILES π
There's nothing wrong with using set to configure your application. In fact you might have some great reasons for doing so. For greater flexibility, ease of deployment, etc., you should also consider extracting those settings into a configuration file.
π Configuration file path and file names
Dancer2 will first look for the file config.EXT (where EXT is the type of configuration file you are using; e.g. ini or json or yml) in the root directory of your application. This is considered your global Dancer2 config file. If you do not care to have separate settings for production and development environments (not a recommended practice!), then this file is all you need. π
Next, Dancer2 will look for a file called config_local.EXT. This file is typically useful for deployment-specific configuration that should not be checked into source control. For instance, database credentials could be stored in this file. Any settings in this file are merged into the existing configuration such that those with the same name in your local configuration file will take precedence over those settings in the global file.
Next, Dancer2 will look in the environments directory for a configuration file specific to the platform you are deploying to (production.EXT or development.EXT, for example). Again, the configuration from the environment is merged with the existing configuration with the deployment config taking precedence.
Finally, Dancer2 will look in the environments directory for a local configuration for the specific platform you are deploying to (e.g. production_local.EXT or development_local.EXT). The configuration in this file is merged as before.
Much like config_local.EXT, this file would be useful for environment-specific configuration that would not be checked into source control. For instance, when developing an application that talks to multiple services, each developer could have their own URLs to those services stored within their environments/development_local.yaml file.
Note: if there is noconfig.EXT, Dancer2 will not look for aconfig_local.EXT. The same is true for the local environment configuration.
π§© Supported configuration file formats
Dancer2 supports any configuration file format that is supported by Config::Any. At the time of this writing, that includes YAML (.yml and .yaml), JSON (.jsn and .json), INI (.ini), Apache-style configurations (.cnf and .conf), XML (.xml), and Perl-style hashes (.pl and .perl).
Dancer2 iterates over these file extensions in the order provided by Config::Any and loads any config files that it finds with later configuration information overriding earlier config information. To restrict which file extension Dancer2 looks for, you may set the DANCER_CONFIG_EXT environment variable to a specific extension and Dancer2 will only look for config files with that extension.
Make sure you pick the appropriate extension for your configuration file name, as Dancer2 guesses the type of format based on the file extension.
π Sample configuration files π
Note: Not all possibilities are covered here, only the most common options.
If you prefer YAML, a sample YAML based config file might look like this:
appname: "Hello"
charset: "UTF-8"
auto_page: 1
session: "YAML"
serializer: "JSON"
plugins:
DBIC:
default:
dsn: dbi:SQLite:db/mydata.db
schema_class: Hello::Schema
If JSON is more your thing, your file might look more like this:
{
"appname": "Hello",
"charset": "UTF-8",
"auto_page": "1",
"session": "YAML",
"serializer": "JSON",
"plugins": {
"DBIC": {
"default": {
"dsn": "dbi:SQLite:db/mydata.db",
"schema_class": "Hello::Schema"
}
}
}
}
If you like Apache configuration files, try something similar to:
appname = Hello
charset = UTF-8
auto_page = 1
session = YAML
serializer = JSON
<plugins>
<DBIC>
<default>
dsn = dbi =SQLite =db/mydata.db
schema_class = Hello = =Schema
</default>
</DBIC>
</plugins>
INI-style files are deliberately simplistic and not recommended for use in your Dancer2 applications.
π SUPPORTED SETTINGS π
π Run mode and listening interface/port
host(string) β The IP address that the Dancer2 app should bind to. Default is0.0.0.0, i.e. bind to all available interfaces.port(int) β The port Dancer2 will listen to. Default value is3000. This setting can be changed on the command-line with the--portswitch.behind_proxy(boolean) β If set to true, Dancer2 will look toX-Forwarded-ProtocolandX-Forwarded-hostwhen constructing URLs (for example, when usingredirectorhost). This is useful if your application is behind a proxy.
Note: If either of these are missing, the values of the proxy server will be used instead. For example, if the client sends a HTTP/1.0 request to a proxy that is hosted locally, thenhostwill return the valuelocalhost. In a similar vein, if the client makes a secure connection to the proxy, but the proxy does not passX-Forwarded-Protocol, thenbasewill returnhttp://.... For these reasons, it is recommended that the values are hard-configured in the proxy if possible. For Apache this would be:
RequestHeader set X_FORWARDED_PROTO "https"
RequestHeader set X_FORWARDED_HOST "www.example.com"
no_default_middleware(boolean) β If set to true, your Dancer2 application will NOT be wrapped with the default PSGI middleware. The default middleware wrappers are:Plack::Middleware::FixMissingBodyInRedirectPlack::Middleware::Head
π¨ Content type / character set
content_type(string) β The default content type of outgoing content. Default value is'text/html'.charset(string) β This setting has multiple effects:- It sets the default charset of outgoing content.
charset=item will be added to Content-Type response header. - It makes Unicode bodies in HTTP responses of
text/*types to be encoded to this charset. - It also indicates to Dancer2 in which charset the static files and templates are encoded.
- If you're using
Dancer2::Plugin::Database, UTF-8 support will automatically be enabled for your database β see "AUTOMATIC UTF-8 SUPPORT" inDancer2::Plugin::Database.
- It sets the default charset of outgoing content.
Default value is empty which means don't do anything. HTTP responses without charset will be interpreted as ISO-8859-1 by most clients.
You can cancel any charset processing by specifying your own charset in Content-Type header or by ensuring that response body leaves your handler without Unicode flag set (by encoding it into some 8bit charset, for example).
Also, since automatically serialized JSON responses have application/json Content-Type, you should always encode them by hand.
default_mime_type(string) β Dancer2'sDancer2::Core::MIMEmodule usesapplication/dataas a default mime type. This setting lets the user change it. For example, if you have a lot of files being served in the public folder that do not have an extension, and are text files, set thedefault_mime_typetotext/plain.
π¦ Serializing responses
serializer(string) β When writing a webservice, data serialization/deserialization is a common issue to deal with. Dancer2 can automatically handle that for you, via a serializer.
Available serializer engines
The following serializers are available, be aware they dynamically depend on Perl modules you may not have on your system.
- JSON β Requires
JSON. - YAML β Requires
YAML. - XML β Requires
XML::Simple. - Mutable β Will try to find the appropriate serializer using the Content-Type and Accept-type header of the request.
π Serializer engine
The serializer can be configured in a separate engines section, like so:
serializer: "JSON"
engines:
serializer:
JSON:
pretty: 1
See documentation for a particular serializer for supported options.
π File / directory locations
environment(string) β This is the name of the environment that should be used. Standard Dancer2 applications have aenvironmentsfolder with specific configuration files for different environments (usually development and production environments). They specify different kind of error reporting, deployment details, etc. These files are read after the genericconfig.ymlconfiguration file.appdir(directory) β This is the path where your application will live. It's where Dancer2 will look by default for your config files, templates and static content. It is typically set byuse Dancer2to use the same directory as your script.public_dir(directory) β This is the directory, where static files are stored. Any existing file in that directory will be served as a static file, before matching any route. See alsostatic_handler. Default:$appdir/public.static_handler(boolean) β This setting have to be declared and set to true if you modify standardpublic_dirlocation. Default: true if$ENV{DANCER_PUBLIC}is set orpublic_diris set to$appdir/public.views(directory) β This is the directory where your templates and layouts live. It's the "view" part of MVC (model, view, controller). Default:$appdir/views.
π§΅ Templating & layouts
templateβ Allows you to configure which template engine should be used. For instance, to use Template Toolkit, add the following toconfig.yml:
template: template_toolkit
layout(string)
...so the name of the layout to use when rendering a view? That's this one. Dancer2 goes looking for a matching template in the $views/layouts directory. π
And like, you can override the default layout β just use the third argument of the template keyword. Check the Dancer2 manpage for the full deets if you're nosy (affectionate).
layout_dir (string) β a relative path to where the layouts live inside the views directory, bestie.
layout_dir: actual_layouts
Default: layouts. Slay.
πΈ Logging, debugging and error handling πΈ
startup_info (boolean)
Set it to true and you get a banner printed at server start with stuff like versions and the environment (or "dancefloor"). Cute little hello from your app. β¨
Conforms to the environment variable DANCER_STARTUP_INFO.
traces (boolean)
Set to true and Dancer2 will show you the full stack traces whenever a warning or a die happens. (Internally it sets Carp::Verbose.) Default is false. Turn it on when you're debugging and things are going feral β it's giving forensics. π₯
no_server_tokens (boolean)
If set to true, Dancer2 will not add an X-Powered-By header and also append the Dancer2 version to the Server header. Default is false β adding. iykyk.
You can also use the environment variable DANCER_NO_SERVER_TOKENS.
logger (enum)
Pick which logger you want. For example, to write to log files with Dancer2::Logger::File:
logger: File
Or to yeet log messages at the console you started your Dancer2 app from, with Dancer2::Logger::Console:
logger: Console
Loggers get configured with a matching Logger engine section, shown below. β¬οΈ
session (enum)
This one lets you enable a session engine for your web app. No cap: sessions are disabled by default in Dancer2 β you literally have to choose a session engine to use them. Pick your fighter. π
Sessions are configured with a corresponding Session engine section, as shown below.
show_errors (boolean)
Deprecated configuration, bestie. π«Ά Use show_stacktrace (described right below) instead.
show_stacktrace (boolean)
Set to true and Dancer2 renders a detailed debug screen every time an error gets caught. Set to false and you get the default error page instead, using $public/$error_code.html if it exists, then $views/$error_code.tt, or the template specified by the error_template setting.
The error screen tries to sanitise sensitive-looking info (passwords, card numbers in the request, etc.) but you still should not have show_stacktrace enabled while in production β there's still a risk of divulging details. Like, seriously, don't. π
error_template (template path)
This is where you specify a template to use in case of a runtime error. Right now the template (and the $views/$error_code.tt templates too) can use four variables:
titleβ the error title.contentβ the error-specific content (if any).statusβ the HTTP status code throwing that error.exceptionβ the stringified exception (e.g.$@) if any.
Keep in mind that content and exception can vary depending on the problem. Fr fr, they're not fixed.
For example:
- A 404 has an empty
exception, andcontentholds the URI that wasn't found. Unless you do the 404 yourself viasend_error("You chose ... poorly!", 404);β thencontentisYou chose ... poorly!. - A 500 because of, say, dividing 0 by 0 will have an empty
content, andexceptionlikeIllegal division by zero at .... - A 401 from
send_error("You can not know the secret until you sign in grasshopper!", 401);will have an emptyexception, andcontentwill containYou can not know the secret until you sign in grasshopper!.
π§ Logger engine π§
The logger has to be configured in a separate engines section, like so:
logger: Console
engines:
logger:
Console:
log_level: core
Every logger supports the config option below. See the docs for a particular logger for the other options it supports. π
log_level
Tells which log messages should actually get logged. Possible values are core, info, debug, warning or error.
coreβ all messages are logged, including some from Dancer2 itselfdebugβ all messages are loggedinfoβ only info, warning and error messages are loggedwarningβ only warning and error messages are loggederrorβ only error messages are logged
During development you'll probably want debug so you can see your own debug messages, and core if you need to see what Dancer2 is doing behind the scenes. In production you'll likely want error or warning only, for less-chatty logs. Nobody wants a wall of text at 3am. π
π Session engine π
The session engine lives in the engines section too:
session: Simple
engines:
session:
Simple:
cookie_name: dance.set
cookie_duration: '24 hours'
cookie_same_site: Lax
is_secure: 1
is_http_only: 1
See Dancer2::Core::Role::SessionFactory for the more detailed docs on these options, or the particular session engine for other supported options. β¨
cookie_name
The name of the cookie the session ID gets stored in. Defaults to dancer.session. Certain session engines can override this.
cookie_domain
The domain of the cookie. By default there is no domain defined for the cookie.
cookie_path
The path of the cookie. By default there is no path defined for the cookie.
cookie_duration
The session expiry time in seconds, or as e.g. 2 hours (see expires in Dancer2::Core::Cookie). By default there's no specific expiry time.
cookie_same_site
Restricts the session cookie to a first-party or same-site context. Valid values are Strict, Lax, or None.
Refer to RFC6265bis (https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site) for the further details about same-site context.
is_secure
Your user's session ID lives in a cookie. If is_secure is set to a true value, the cookie gets marked as secure, meaning it should only be sent over HTTPS connections. π
is_http_only
This one defaults to 1 and tells the session cookie to be created with the HttpOnly option active β meaning JavaScript won't be able to access its value. Iconic protection behaviour. π‘οΈ
π¦ auto_page (boolean) π¦
For simple pages where you're not doing anything dynamic but still want the template engine for headers and stuff, auto_page saves you from making a route for literally every page. Main character efficiency.
With auto_page on, if the requested path doesn't match any specific route, Dancer2 checks the views directory for a matching template and uses it to satisfy the request if it finds one.
Just enable it in your config:
auto_page: 1
Then if you request /foo/bar, Dancer2 looks in the views dir for /foo/bar.tt. π
Dancer2 will honour your before_template_render code and all the default variables. They'll be accessible and interpolated on automatically served pages too. No crumbs left behind.
β dsl_class β
For complex applications that need extended DSL keywords or other functionality, you can specify the DSL class at import time or in the config settings.
dsl_class: 'My::DSL'
This is the same as specifying
use Dancer2 dsl => 'My::DSL'
in your module. dsl_class defaults to Dancer2::Core::DSL if you don't specify it. π
π Environment variables π
DANCER_CONFDIR
Sets the configuration directory. This correlates to the confdir config option.
DANCER_ENVDIR
Sets the environment directory. This correlates to the envdir config option.
PLACK_ENV
Sets the given environment. This can be overridden by DANCER_ENVIRONMENT.
DANCER_ENVIRONMENT
Sets the given environment. This takes higher precedence over PLACK_ENV.
If neither PLACK_ENV nor DANCER_ENVIRONMENT is set, the environment defaults to development.
DANCER_APPHANDLER
The DANCER_APPHANDLER configuration controls what the dance keyword does.
- If it's set to
PSGI(which gets set automatically wheneverPLACK_ENVis set),dancewill return the PSGI application coderef. - Otherwise β and this is the default,
Standaloneβ it runs the Plack standalone server with the application.
DANCER_PORT
Sets the port that'll be used by the development server (if not run by plackup).
DANCER_SERVER
Sets the host the development server will be used by the development server (if not run by plackup). π
Note: this might change in the future. π
DANCER_STARTUP_INFO
Controls whether to display start up info.
DANCER_NO_SERVER_TOKENS
Controls whether to display the server tokens.
DANCER_PUBLIC
Sets the public directory location.
DANCER_TRACES
Sets the tracing flag, which sets Carp's $Verbose flag.
DANCER_VIEWS
Sets the views (templates) directory.
DANCER_LOGGER
Sets the logger engine.
DANCER_CHARSET
Sets the default charset.
DANCER_CONTENT_TYPE
Sets the default content type.
If it's not set, it defaults to text/html.
π₯ SEE ALSO π₯
Dancer2 β go read it, bestie, you'll need it.
π AUTHOR π
Dancer Core Developers β legends, every one of them.
π COPYRIGHT AND LICENSE π
This software is copyright (c) 2024 by Alexis Sukrieh.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
That's the whole page, diva. π Written by the Dancer Core Developers, shipped with perl v5.42.0, dated 2024-12-12, and living at Dancer2::Config(3) β go configure something gorgeous. πβ¨π¦
π¦ where this page comes from
- opensuse-leap 16.0: perl-Dancer2 1.1.2-bp160.1.11 Β· Artistic-1.0 OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms