Merge commit 'toms/master'
[catagits/Catalyst-TraitFor-Request-ProxyBase.git] / lib / Catalyst / TraitFor / Request / ProxyBase.pm
1 package Catalyst::TraitFor::Request::ProxyBase;
2 use Moose::Role;
3 use URI ();
4 use namespace::autoclean;
5
6 our $VERSION = '0.000002';
7
8 requires qw/
9     base
10     secure
11 /;
12
13 around 'base' => sub {
14     my ($orig, $self, @args) = @_;
15     if (my $base = $self->header('X-Request-Base')) {
16         $base .= '/' unless $base =~ m|/$|;
17         @args = (URI->new($base));
18     }
19     $self->$orig(@args);
20 };
21
22 around 'secure' => sub {
23     my ($orig, $self, @args) = @_;
24     if (my $base = $self->header('X-Request-Base')) {
25         return URI->new($base)->scheme eq 'http' ? 0 : 1;
26     }
27     $self->$orig(@args);
28 };
29
30 1;
31
32 __END__
33
34 =head1 NAME
35
36 Catalyst::TraitFor::Request::ProxyBase - Replace request base with value passed by HTTP proxy
37
38 =head1 SYNOPSIS
39
40     package MyApp;
41     use Moose;
42     use namespace::autoclean;
43
44     use Catalyst;
45     use CatalystX::RoleApplicator;
46
47     extends 'Catalyst';
48
49     __PACKAGE__->apply_request_class_roles(qw/
50         Catalyst::TraitFor::Request::ProxyBase
51     /);
52
53     __PACKAGE__->setup;
54
55 =head1 DESCRIPTION
56
57 This module is a L<Moose::Role> which allows you more flexibility in your
58 application's deployment configurations when deployed behind a proxy.
59
60 The problem is that there is no standard way for a proxy to tell a backend
61 server what the original URI for the request was, or if the request was
62 initially SSL. (Yes, I do know about C<< X-Forwarded-Host >>, but they don't
63 do enough)
64
65 This creates an issue for someone wanting to deploy the same cluster of
66 application servers behind various URI endpoints.
67
68 Using this module, the request base (C<< $c->req->base >>)
69 is replaced with the contents of the C<< X-Request-Base >> header,
70 which is expected to be a full URI, for example:
71
72     http://example.com
73     https://example.com
74     http://other.example.com:81/foo/bar/yourapp
75
76 This value will then be used as the base for uris constructed by
77 C<< $c->uri_for >>.
78
79 =head1 REQUIRED METHODS
80
81 =over
82
83 =item base
84
85 =item secure
86
87 =back
88
89 =head1 WRAPPED METHODS
90
91 =over
92
93 =item base
94
95 =item secure
96
97 =back
98
99 =head1 BUGS
100
101 Probably. Patches welcome, please fork from:
102
103     http://github.com/bobtfish/catalyst-traitfor-request-proxybase
104
105 and send a pull request.
106
107 =head1 AUTHOR
108
109 Tomas Doran (t0m) C<< <bobtfish@bobtfish.net> >>
110
111 =head1 COPYRIGHT
112
113 This module is Copyright (c) 2009 Tomas Doran and is licensed under the same
114 terms as perl itself.
115
116 =cut
117