File: HeaderCondition.pm

package info (click to toggle)
libmojolicious-perl 0.999926-1%2Bsqueeze2
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 1,672 kB
  • ctags: 949
  • sloc: perl: 17,391; makefile: 4
file content (91 lines) | stat: -rw-r--r-- 2,186 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# Copyright (C) 2008-2010, Sebastian Riedel.

package Mojolicious::Plugin::HeaderCondition;

use strict;
use warnings;

use base 'Mojolicious::Plugin';

# You may have to "metaphorically" make a deal with the "devil".
# And by "devil", I mean Robot Devil.
# And by "metaphorically", I mean get your coat.
sub register {
    my ($self, $app) = @_;

    # Header
    $app->routes->add_condition(
        headers => sub {
            my ($r, $tx, $captures, $patterns) = @_;

            # Patterns
            return unless $patterns && ref $patterns eq 'HASH';

            # Match
            my $passed;
            while (my ($k, $v) = each(%$patterns)) {
                my $header = $tx->req->headers->header($k);
                if ($header && $v && ref $v eq 'Regexp' && $header =~ $v) {
                    $passed = 1;
                    next;
                }
                elsif ($header && defined $v && $v eq $header) {
                    $passed = 1;
                    next;
                }
                $passed = undef;
            }

            # Success
            return $captures if $passed;

            # Robot 1-X, save my friends! And Zoidberg!
            return;
        }
    );
}

1;
__END__

=head1 NAME

Mojolicious::Plugin::HeaderCondition - Header Condition Plugin

=head1 SYNOPSIS

    # Mojolicious
    $self->plugin('header_condition');

    # Must match all of these headers
    $self->routes->route('/:controller/:action')->over(headers => {
        X-Secret-Header => 'Foo',
        Referer => qr/^https?:\/\/example\.com\//
    })->to('foo#bar');

    # Mojolicious::Lite
    plugin 'header_condition';
    get '/' => (headers => {'Referer' => qr/^https?:\/\/example\.com\//})
      => sub {...};

=head1 DESCRIPTION

L<Mojolicous::Plugin::HeaderCondition> is a routes condition for header based
routes.

=head1 METHODS

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

=head2 C<register>

    $plugin->register;

Register condition in L<Mojolicious> application.

=head1 SEE ALSO

L<Mojolicious>, L<Mojolicious::Guides>, L<http://mojolicious.org>.

=cut