root/lang/perl/HTTP-Engine/trunk/lib/HTTP/Engine/Request.pm @ 11629

Revision 11629, 9.2 kB (checked in by tokuhirom, 5 years ago)

added stopwords

Line 
1package HTTP::Engine::Request;
2use Moose;
3
4use Carp;
5use HTTP::Headers;
6use HTTP::Body;
7use HTTP::Engine::Types::Core qw( Uri Header );
8use HTTP::Request;
9use IO::Socket qw[AF_INET inet_aton];
10
11# the IP address of the client
12has address => (
13    is  => 'rw',
14    isa => 'Str',
15);
16
17has context => (
18    is       => 'rw',
19    isa      => 'HTTP::Engine::Context',
20    weak_ref => 1,
21);
22
23has cookies => (
24    is      => 'rw',
25    isa     => 'HashRef',
26    default => sub { {} },
27);
28
29has method => (
30    is  => 'rw',
31    # isa => 'Str',
32);
33
34has protocol => (
35    is  => 'rw',
36    # isa => 'Str',
37);
38
39has query_parameters => (
40    is      => 'rw',
41    isa     => 'HashRef',
42    default => sub { {} },
43);
44
45# https or not?
46has secure => (
47    is      => 'rw',
48    isa     => 'Bool',
49    default => 0,
50);
51
52has uri => (
53    is     => 'rw',
54    isa    => 'Uri',
55    coerce => 1,
56);
57
58has user => ( is => 'rw', );
59
60has raw_body => (
61    is      => 'rw',
62    isa     => 'Str',
63    default => '',
64);
65
66has headers => (
67    is      => 'rw',
68    isa     => 'Header',
69    coerce  => 1,
70    default => sub { HTTP::Headers->new },
71    handles => [ qw(content_encoding content_length content_type header referer user_agent) ],
72);
73
74# Contains the URI base. This will always have a trailing slash.
75# If your application was queried with the URI C<http://localhost:3000/some/path> then C<base> is C<http://localhost:3000/>.
76has base => (
77    is      => 'rw',
78    isa     => 'URI',
79    trigger => sub {
80        my $self = shift;
81
82        if ( $self->uri ) {
83            $self->path; # clear cache.
84        }
85    },
86);
87
88has hostname => (
89    is      => 'rw',
90    isa     => 'Str',
91    lazy    => 1,
92    default => sub {
93        my $self = shift;
94        $ENV{REMOTE_HOST} || gethostbyaddr( inet_aton( $self->address ), AF_INET );
95    },
96);
97
98has http_body => (
99    is      => 'rw',
100    isa     => 'HTTP::Body',
101    handles => {
102        body_parameters => 'param',
103        body            => 'body',
104    },
105);
106
107# contains body_params and query_params
108has parameters => (
109    is      => 'rw',
110    isa     => 'HashRef',
111    default => sub { +{} },
112);
113
114has uploads => (
115    is      => 'rw',
116    isa     => 'HashRef',
117    default => sub { +{} },
118);
119
120no Moose;
121
122# aliases
123*body_params  = \&body_parameters;
124*input        = \&body;
125*params       = \&parameters;
126*query_params = \&query_parameters;
127*path_info    = \&path;
128
129sub cookie {
130    my $self = shift;
131
132    return keys %{ $self->cookies } if @_ == 0;
133
134    if (@_ == 1) {
135        my $name = shift;
136        return undef unless exists $self->cookies->{$name}; ## no critic.
137        return $self->cookies->{$name};
138    }
139}
140
141sub param {
142    my $self = shift;
143
144    return keys %{ $self->parameters } if @_ == 0;
145
146    if (@_ == 1) {
147        my $param = shift;
148        return wantarray ? () : undef unless exists $self->parameters->{$param};
149
150        if ( ref $self->parameters->{$param} eq 'ARRAY' ) {
151            return (wantarray)
152              ? @{ $self->parameters->{$param} }
153                  : $self->parameters->{$param}->[0];
154        } else {
155            return (wantarray)
156              ? ( $self->parameters->{$param} )
157                  : $self->parameters->{$param};
158        }
159    } elsif (@_ > 1) {
160        my $field = shift;
161        $self->parameters->{$field} = [@_];
162    }
163}
164
165
166sub path {
167    my ($self, $params) = @_;
168
169    if ($params) {
170        $self->uri->path($params);
171    } else {
172        return $self->{path} if $self->{path};
173    }
174
175    my $path     = $self->uri->path;
176    my $location = $self->base->path;
177    $path =~ s/^(\Q$location\E)?//;
178    $path =~ s/^\///;
179    $self->{path} = $path;
180
181    return $path;
182}
183
184sub upload {
185    my $self = shift;
186
187    return keys %{ $self->uploads } if @_ == 0;
188
189    if (@_ == 1) {
190        my $upload = shift;
191        return wantarray ? () : undef unless exists $self->uploads->{$upload};
192
193        if (ref $self->uploads->{$upload} eq 'ARRAY') {
194            return (wantarray)
195              ? @{ $self->uploads->{$upload} }
196          : $self->uploads->{$upload}->[0];
197        } else {
198            return (wantarray)
199              ? ( $self->uploads->{$upload} )
200          : $self->uploads->{$upload};
201        }
202    }
203
204    if (@_ > 1) {
205        while ( my($field, $upload) = splice(@_, 0, 2) ) {
206            if ( exists $self->uploads->{$field} ) {
207                for ( $self->uploads->{$field} ) {
208                    $_ = [$_] unless ref($_) eq "ARRAY";
209                    push(@{ $_ }, $upload);
210                }
211            } else {
212                $self->uploads->{$field} = $upload;
213            }
214        }
215    }
216}
217
218sub uri_with {
219    my($self, $args) = @_;
220   
221    carp( 'No arguments passed to uri_with()' ) unless $args;
222
223    for my $value (values %{ $args }) {
224        next unless defined $value;
225        for ( ref $value eq 'ARRAY' ? @{ $value } : $value ) {
226            $_ = "$_";
227            utf8::encode( $_ );
228        }
229    };
230   
231    my $uri = $self->uri->clone;
232   
233    $uri->query_form( {
234        %{ $uri->query_form_hash },
235        %{ $args },
236    } );
237    return $uri;
238}
239
240sub as_http_request {
241    my $self = shift;
242    HTTP::Request->new( $self->method, $self->uri, $self->headers, $self->raw_body );
243}
244
245sub absolute_url {
246    my ($self, $location) = @_;
247
248    unless ($location =~ m!^https?://!) {
249        my $base = $self->base;
250        my $url = sprintf '%s://%s', $base->scheme, $base->host;
251        unless (($base->scheme eq 'http' && $base->port eq '80') ||
252               ($base->scheme eq 'https' && $base->port eq '443')) {
253            $url .= ':' . $base->port;
254        }
255        $url .= $base->path;
256        $location = URI->new_abs($location, $url);
257    }
258    $location;
259}
260
261__PACKAGE__->meta->make_immutable;
262
2631;
264__END__
265
266=for stopwords Stringifies URI http https param CGI.pm-compatible referer uri IP hostname
267
268=head1 NAME
269
270HTTP::Engine::Request - http request object
271
272=head1 SYNOPSIS
273
274    $c->req
275
276=head1 ATTRIBUTES
277
278=over 4
279
280=item address
281
282Returns the IP address of the client.
283
284=item context
285
286Returns the HTTP::Context(internal use only)
287
288=item cookies
289
290Returns a reference to a hash containing the cookies
291
292=item method
293
294Contains the request method (C<GET>, C<POST>, C<HEAD>, etc).
295
296=item protocol
297
298Returns the protocol (HTTP/1.0 or HTTP/1.1) used for the current request.
299
300=item query_parameters
301
302Returns a reference to a hash containing query string (GET) parameters. Values can                                                   
303be either a scalar or an arrayref containing scalars.
304
305=item secure
306
307Returns true or false, indicating whether the connection is secure (https).
308
309=item uri
310
311Returns a URI object for the current request. Stringifies to the URI text.
312
313=item user
314
315Returns REMOTE_USER.
316
317=item raw_body
318
319Returns string containing body(POST).
320
321=item headers
322
323Returns an L<HTTP::Headers> object containing the headers for the current request.
324
325=item base
326
327Contains the URI base. This will always have a trailing slash.
328
329=item hostname
330
331Returns the hostname of the client.
332
333=item http_body
334
335Returns an L<HTTP::Body> object.
336
337=item parameters
338
339Returns a reference to a hash containing GET and POST parameters. Values can
340be either a scalar or an arrayref containing scalars.
341
342=item uploads
343
344Returns a reference to a hash containing uploads. Values can be either a
345L<HTTP::Engine::Request::Upload> object, or an arrayref of
346L<HTTP::Engine::Request::Upload> objects.
347
348=item content_encoding
349
350Shortcut to $req->headers->content_encoding.
351
352=item content_length
353
354Shortcut to $req->headers->content_length.
355
356=item content_type
357
358Shortcut to $req->headers->content_type.
359
360=item header
361
362Shortcut to $req->headers->header.
363
364=item referer
365
366Shortcut to $req->headers->referer.
367
368=item user_agent
369
370Shortcut to $req->headers->user_agent.
371
372=item cookie
373
374A convenient method to access $req->cookies.
375
376    $cookie  = $c->request->cookie('name');
377    @cookies = $c->request->cookie;
378
379=item param
380
381Returns GET and POST parameters with a CGI.pm-compatible param method. This
382is an alternative method for accessing parameters in $c->req->parameters.
383
384    $value  = $c->request->param( 'foo' );
385    @values = $c->request->param( 'foo' );
386    @params = $c->request->param;
387
388Like L<CGI>, and B<unlike> earlier versions of Catalyst, passing multiple
389arguments to this method, like this:
390
391    $c->request->param( 'foo', 'bar', 'gorch', 'quxx' );
392
393will set the parameter C<foo> to the multiple values C<bar>, C<gorch> and
394C<quxx>. Previously this would have added C<bar> as another value to C<foo>
395(creating it if it didn't exist before), and C<quxx> as another value for
396C<gorch>.
397
398=item path
399
400Returns the path, i.e. the part of the URI after $req->base, for the current request.
401
402=item upload
403
404A convenient method to access $req->uploads.
405
406    $upload  = $c->request->upload('field');
407    @uploads = $c->request->upload('field');
408    @fields  = $c->request->upload;
409
410    for my $upload ( $c->request->upload('field') ) {
411        print $upload->filename;
412    }
413
414
415=item uri_with
416
417Returns a rewritten URI object for the current request. Key/value pairs
418passed in will override existing parameters. Unmodified pairs will be
419preserved.
420
421=item as_http_request
422
423convert HTTP::Engine::Request to HTTP::Request.
424
425=item $req->absolute_url($location)
426
427convert $location to absolute uri.
428
429=back
430
431=head1 AUTHORS
432
433Kazuhiro Osawa and HTTP::Engine Authors.
434
435=head1 SEE ALSO
436
437L<HTTP::Request>, L<Catalyst::Request>
438
Note: See TracBrowser for help on using the browser.