Newer Older
87 lines | 2.305kb
add files
Yuki Kimoto authored on 2014-03-26
1
package Mojolicious::Plugin::HeaderCondition;
2
use Mojo::Base 'Mojolicious::Plugin';
3

            
4
sub register {
5
  my ($self, $app) = @_;
6

            
7
  $app->routes->add_condition(headers => \&_headers);
8
  $app->routes->add_condition(
9
    agent => sub { _headers(@_[0 .. 2], {'User-Agent' => $_[3]}) });
10
  $app->routes->add_condition(
11
    host => sub { _check($_[1]->req->url->to_abs->host, $_[3]) });
12
}
13

            
14
sub _check {
15
  my ($value, $pattern) = @_;
16
  return 1
17
    if $value && $pattern && ref $pattern eq 'Regexp' && $value =~ $pattern;
18
  return $value && defined $pattern && $pattern eq $value;
19
}
20

            
21
sub _headers {
22
  my ($route, $c, $captures, $patterns) = @_;
23
  return undef unless $patterns && ref $patterns eq 'HASH' && keys %$patterns;
24

            
25
  # All headers need to match
26
  my $headers = $c->req->headers;
27
  while (my ($name, $pattern) = each %$patterns) {
28
    return undef unless _check(scalar $headers->header($name), $pattern);
29
  }
30
  return 1;
31
}
32

            
33
1;
34

            
35
=encoding utf8
36

            
37
=head1 NAME
38

            
39
Mojolicious::Plugin::HeaderCondition - Header condition plugin
40

            
41
=head1 SYNOPSIS
42

            
43
  # Mojolicious
44
  $self->plugin('HeaderCondition');
45
  $self->routes->get('/:controller/:action')
46
    ->over(headers => {Referer => qr/example\.com/});
47

            
48
  # Mojolicious::Lite
49
  plugin 'HeaderCondition';
50
  get '/' => (headers => {Referer => qr/example\.com/}) => sub {...};
51

            
52
  # All headers need to match
53
  $self->routes->get('/:controller/:action')->over(headers => {
54
    'X-Secret-Header' => 'Foo',
55
    Referer => qr/example\.com/
56
  });
57

            
58
  # The "agent" condition is a shortcut for the "User-Agent" header
59
  get '/' => (agent => qr/Firefox/) => sub {...};
60

            
61
  # The "host" condition is a shortcut for the detected host
62
  get '/' => (host => qr/mojolicio\.us/) => sub {...};
63

            
64
=head1 DESCRIPTION
65

            
66
L<Mojolicious::Plugin::HeaderCondition> is a route condition for header based
67
routes.
68

            
69
This is a core plugin, that means it is always enabled and its code a good
70
example for learning to build new plugins, you're welcome to fork it.
71

            
72
=head1 METHODS
73

            
74
L<Mojolicious::Plugin::HeaderCondition> inherits all methods from
75
L<Mojolicious::Plugin> and implements the following new ones.
76

            
77
=head2 register
78

            
79
  $plugin->register(Mojolicious->new);
80

            
81
Register conditions in L<Mojolicious> application.
82

            
83
=head1 SEE ALSO
84

            
85
L<Mojolicious>, L<Mojolicious::Guides>, L<http://mojolicio.us>.
86

            
87
=cut