The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Dancer2::Plugin::HostSpecificRoute - Allow designating routes to respond only on hostname match

VERSION

version 1.0000

SYNOPSIS

   package MyApp;
   use Dancer2 appname => 'MyApp';
   use Dancer2::Plugin::HostSpecificRoute;

   get '/special_route' => host 'special.host.example' => sub {
      # route code to run only when special.host.example is
      # the request host
   };

   get '/special_route' => sub {
      # default code to run /special_route when host is not 
      # special.host.example
   };

   get '/special_route_2' => host qr/\.funkyhost.example$/ => sub {
      # route code to run only when funkyhost.example is
      # the request host is *.funkyhost.example
   };

   # There is no default route for /special_route_2; it will 404, if you
   # don't address your request to *.funkyhost.example.

DESCRIPTION

It is not difficult to have your Dancer2 application answer to more than one URL or even IP address; just adding server_name directives in your nginx config, or ServerName in Apache, will do the trick nicely.

It may be that you want to have different route code for a given path, depending on which host URL is requested. If that's the case, this plugin will make it trivially easy to do so, without having to add a before hook to adjust the behavior of all your routes.

SUBROUTINES/METHODS

This plugin introduces one new keyword, host, to be used as a predicate for your routes. It will work with any of Dancer2's method/route declaratives (get, put, post, patch, del or any), and can be chained with other predicates, like authorization-plugin directives (e.g. Dancer2::Plugin::Auth::Extensible).

The host predicate takes one parameter, which must be either:

  • A scalar string, the FQDN of a host.

  • A quoted regex that will match the desired FQDNs to which the route should respond.

If you wish to have a second route that can serve as a default, be sure to list it after any matching routes with the predicate. Routes without a host predicate are handled normally.

DEPENDENCIES

BUGS AND LIMITATIONS

None found so far; if you find any, please post an issue on the bug tracker for this module.

ACKNOWLEDGEMENTS

GitHub user xoid suggested this functionality in this discussion. The idea intrigued me, and I'm doing something similar using a hook (which fires on Every Single Request), so here we are.

A small bit of blame goes to Jason Crome for his constant encouragement in this sort of madness.

AUTHOR

D Ruth Holloway <ruth@hiruthie.me>

COPYRIGHT AND LICENSE

This software is copyright (c) 2023 by D Ruth Holloway.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.