Mojolicious-Plugin-Host

 view release on metacpan or  search on metacpan

lib/Mojolicious/Plugin/Host.pm  view on Meta::CPAN

package Mojolicious::Plugin::Host;
use Mojo::Base 'Mojolicious::Plugin';
use Carp ();
use Mojo::Util ();

our $VERSION = '0.01';

sub register {
    my (undef, $app, $config) = @_;

    my ($helper, $www) = _parse_and_validate_config($config);
    my $sub;
    if (not defined $www) {
        $sub = sub { $_[0]->req->url->to_abs->host };
    } elsif ($www eq 'always') {
        $sub = sub {
            my $host = $_[0]->req->url->to_abs->host;
            if (index($host, 'www.') != 0) {
                $host = "www.$host";
            }

            return $host;
        };
    } elsif ($www eq 'never') {
        $sub = sub {
            my $host = $_[0]->req->url->to_abs->host;
            if (index($host, 'www.') == 0) {
                substr $host, 0, 4, '';
            }

            return $host;
        };
    } else {
        Carp::croak qq{unknown value provided for www: '$www'};
    }

    $app->helper($helper => $sub);
}

sub _parse_and_validate_config {
    my ($config) = @_;

    my $helper;
    if (exists $config->{helper}) {
        $helper = delete $config->{helper};

        my $ref = ref $helper;
        Carp::croak qq{helper must be a string, but was '$ref'} if $ref;
        Carp::croak 'helper must be non-empty' if not defined $helper or $helper eq '';
    } else {
        $helper = 'host';
    }

    my $www;
    if (exists $config->{www}) {
        $www = delete $config->{www};

        my $ref = ref $www;
        Carp::croak qq{www must be a string, but was '$ref'} if $ref;
        Carp::croak 'www must be non-empty' if not defined $www or $www eq '';
        Carp::croak qq{www must be either 'always' or 'never', but was '$www'}
            unless grep { $www eq $_ } 'always', 'never';
    }

    Carp::croak 'unknown keys/values: ' . Mojo::Util::dumper $config if %$config;

    return $helper, $www;
}

1;
__END__

=encoding utf-8

=head1 NAME

Mojolicious::Plugin::Host - Easily get the host for the current request

=head1 STATUS

=for html <a href="https://travis-ci.org/srchulo/Mojolicious-Plugin-Host"><img src="https://travis-ci.org/srchulo/Mojolicious-Plugin-Host.svg?branch=master"></a> <a href='https://coveralls.io/github/srchulo/Mojolicious-Plugin-Host?branch=master'><img...

=head1 SYNOPSIS

  # Mojolicious::Lite
  plugin 'Host';

  # Mojolicious
  $app->plugin('Host');

  # remove www. from all hosts
  $app->plugin(Host => { www => 'never' });

  # add www. to all hosts
  $app->plugin(Host => { www => 'always' });

  # provide your own helper name and use different host helpers
  $app->plugin(Host => { helper => 'host' }); # default
  $app->plugin(Host => { helper => 'www_host', www => 'always' });
  $app->plugin(Host => { helper => 'no_www_host', www => 'never' });



( run in 0.725 second using v1.01-cache-2.11-cpan-39bf76dae61 )