initial test checkins
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Response.pm
CommitLineData
fc7ec1d9 1package Catalyst::Response;
2
059c085b 3use Moose;
6680c772 4use HTTP::Headers;
faa02805 5use Moose::Util::TypeConstraints;
6use namespace::autoclean;
fc7ec1d9 7
531f1ab6 8with 'MooseX::Emulate::Class::Accessor::Fast';
9
faa02805 10has _response_cb => (
11 is => 'ro',
12 isa => 'CodeRef',
13 writer => '_set_response_cb',
14 clearer => '_clear_response_cb',
15 predicate => '_has_response_cb',
16);
17
18subtype 'Catalyst::Engine::Types::Writer',
19 as duck_type([qw(write close)]);
20
21has _writer => (
22 is => 'ro',
23 isa => 'Catalyst::Engine::Types::Writer',
24 writer => '_set_writer',
25 clearer => '_clear_writer',
26 predicate => '_has_writer',
27);
28
e37f92f5 29has write_fh => (
30 is=>'ro',
31 predicate=>'has_write_fh',
eb1f4b49 32 lazy=>1,
1f2a8069 33 builder=>'_build_write_fh',
34);
35
36sub _build_write_fh {
37 my $self = shift;
38 $self->_context->finalize_headers unless
39 $self->finalized_headers;
40 $self->_writer;
41};
e37f92f5 42
43sub DEMOLISH {
44 my $self = shift;
45 return if $self->has_write_fh;
46 if($self->_has_writer) {
47 $self->_writer->close
48 }
49}
faa02805 50
6680c772 51has cookies => (is => 'rw', default => sub { {} });
ffb43803 52has body => (is => 'rw', default => undef);
53sub has_body { defined($_[0]->body) }
99a543ee 54
059c085b 55has location => (is => 'rw');
6680c772 56has status => (is => 'rw', default => 200);
57has finalized_headers => (is => 'rw', default => 0);
059c085b 58has headers => (
59 is => 'rw',
9c331634 60 isa => 'HTTP::Headers',
059c085b 61 handles => [qw(content_encoding content_length content_type header)],
6680c772 62 default => sub { HTTP::Headers->new() },
63 required => 1,
64 lazy => 1,
059c085b 65);
258733f1 66has _context => (
67 is => 'rw',
68 weak_ref => 1,
69 clearer => '_clear_context',
70);
fc7ec1d9 71
059c085b 72sub output { shift->body(@_) }
73
aa9e8261 74sub code { shift->status(@_) }
75
9c4288ea 76sub write {
77 my ( $self, $buffer ) = @_;
78
79 # Finalize headers if someone manually writes output
89ba65d5 80 $self->_context->finalize_headers unless $self->finalized_headers;
9c4288ea 81
82 $buffer = q[] unless defined $buffer;
83
84 my $len = length($buffer);
85 $self->_writer->write($buffer);
86
87 return $len;
88}
89
9c4288ea 90sub finalize_headers {
91 my ($self) = @_;
92
93 # This is a less-than-pretty hack to avoid breaking the old
94 # Catalyst::Engine::PSGI. 5.9 Catalyst::Engine sets a response_cb and
95 # expects us to pass headers to it here, whereas Catalyst::Enngine::PSGI
96 # just pulls the headers out of $ctx->response in its run method and never
97 # sets response_cb. So take the lack of a response_cb as a sign that we
98 # don't need to set the headers.
99
100 return unless $self->_has_response_cb;
101
102 # If we already have a writer, we already did this, so don't do it again
103 return if $self->_has_writer;
104
105 my @headers;
106 $self->headers->scan(sub { push @headers, @_ });
107
108 my $writer = $self->_response_cb->([ $self->status, \@headers ]);
109 $self->_set_writer($writer);
110 $self->_clear_response_cb;
111
112 return;
113}
114
e67f0874 115sub from_psgi_response {
116 my ($self, $psgi_res) = @_;
117 if(ref $psgi_res eq 'ARRAY') {
118 my ($status, $headers, $body) = @$psgi_res;
119 $self->status($status);
120 $self->headers($headers);
121 if(ref $body eq 'ARRAY') {
122 $self->body(join '', grep defined, @$body);
123 } else {
124 $self->body($body);
125 }
126 } elsif(ref $psgi_res eq 'CODE') {
127 $psgi_res->(sub {
128 my ($status, $headers, $maybe_body) = @_;
129 $self->status($status);
130 $self->headers($headers);
131 if($maybe_body) {
132 if(ref $maybe_body eq 'ARRAY') {
133 $self->body(join '', grep defined, @$maybe_body);
134 } else {
135 $self->body($maybe_body);
136 }
137 } else {
138 return $self->write_fh;
139 }
140 });
141 } else {
142 die "You can't set a Catalyst response from that, expect a valid PSGI response";
143 }
144}
145
fc7ec1d9 146=head1 NAME
147
910410b8 148Catalyst::Response - stores output responding to the current client request
fc7ec1d9 149
150=head1 SYNOPSIS
151
fbcc39ad 152 $res = $c->response;
153 $res->body;
aa9e8261 154 $res->code;
fbcc39ad 155 $res->content_encoding;
156 $res->content_length;
157 $res->content_type;
158 $res->cookies;
fbcc39ad 159 $res->header;
160 $res->headers;
161 $res->output;
162 $res->redirect;
163 $res->status;
164 $res->write;
b22c6668 165
fc7ec1d9 166=head1 DESCRIPTION
167
910410b8 168This is the Catalyst Response class, which provides methods for responding to
46372e65 169the current client request. The appropriate L<Catalyst::Engine> for your environment
170will turn the Catalyst::Response into a HTTP Response and return it to the client.
b22c6668 171
172=head1 METHODS
fc7ec1d9 173
08a2c908 174=head2 $res->body( $text | $fh | $iohandle_object )
e060fe05 175
176 $c->response->body('Catalyst rocks!');
06e1b616 177
46372e65 178Sets or returns the output (text or binary data). If you are returning a large body,
2f381252 179you might want to use a L<IO::Handle> type of object (Something that implements the read method
46372e65 180in the same fashion), or a filehandle GLOB. Catalyst
181will write it piece by piece into the response.
06e1b616 182
02570318 183=head2 $res->has_body
184
185Predicate which returns true when a body has been set.
186
aa9e8261 187=head2 $res->code
188
189Alias for $res->status.
190
b5ecfcf0 191=head2 $res->content_encoding
b5176d9e 192
910410b8 193Shortcut for $res->headers->content_encoding.
b5176d9e 194
b5ecfcf0 195=head2 $res->content_length
b5176d9e 196
910410b8 197Shortcut for $res->headers->content_length.
b5176d9e 198
b5ecfcf0 199=head2 $res->content_type
b5176d9e 200
910410b8 201Shortcut for $res->headers->content_type.
b5176d9e 202
87e9f9ab 203This value is typically set by your view or plugin. For example,
204L<Catalyst::Plugin::Static::Simple> will guess the mime type based on the file
205it found, while L<Catalyst::View::TT> defaults to C<text/html>.
206
b5ecfcf0 207=head2 $res->cookies
fc7ec1d9 208
910410b8 209Returns a reference to a hash containing cookies to be set. The keys of the
210hash are the cookies' names, and their corresponding values are hash
7e743798 211references used to construct a L<CGI::Simple::Cookie> object.
fc7ec1d9 212
213 $c->response->cookies->{foo} = { value => '123' };
214
7e743798 215The keys of the hash reference on the right correspond to the L<CGI::Simple::Cookie>
910410b8 216parameters of the same name, except they are used without a leading dash.
217Possible parameters are:
ac965e92 218
b0ad47c1 219=over
ac965e92 220
71453caf 221=item value
ac965e92 222
71453caf 223=item expires
ac965e92 224
71453caf 225=item domain
ac965e92 226
71453caf 227=item path
228
229=item secure
230
b21bc468 231=item httponly
232
71453caf 233=back
ac965e92 234
b5ecfcf0 235=head2 $res->header
fbcc39ad 236
910410b8 237Shortcut for $res->headers->header.
fbcc39ad 238
b5ecfcf0 239=head2 $res->headers
fc7ec1d9 240
910410b8 241Returns an L<HTTP::Headers> object, which can be used to set headers.
fc7ec1d9 242
243 $c->response->headers->header( 'X-Catalyst' => $Catalyst::VERSION );
244
b5ecfcf0 245=head2 $res->output
fc7ec1d9 246
910410b8 247Alias for $res->body.
fc7ec1d9 248
b5ecfcf0 249=head2 $res->redirect( $url, $status )
fc7ec1d9 250
2f381252 251Causes the response to redirect to the specified URL. The default status is
252C<302>.
fc7ec1d9 253
73a52566 254 $c->response->redirect( 'http://slashdot.org' );
255 $c->response->redirect( 'http://slashdot.org', 307 );
256
2f381252 257This is a convenience method that sets the Location header to the
258redirect destination, and then sets the response status. You will
ee24f3a8 259want to C< return > or C<< $c->detach() >> to interrupt the normal
2f381252 260processing flow if you want the redirect to occur straight away.
261
824a5eb0 262B<Note:> do not give a relative URL as $url, i.e: one that is not fully
263qualified (= C<http://...>, etc.) or that starts with a slash
264(= C</path/here>). While it may work, it is not guaranteed to do the right
265thing and is not a standard behaviour. You may opt to use uri_for() or
266uri_for_action() instead.
267
73a52566 268=cut
269
270sub redirect {
271 my $self = shift;
fbcc39ad 272
273 if (@_) {
73a52566 274 my $location = shift;
f1bbebac 275 my $status = shift || 302;
73a52566 276
277 $self->location($location);
278 $self->status($status);
279 }
280
281 return $self->location;
282}
fc7ec1d9 283
059c085b 284=head2 $res->location
285
286Sets or returns the HTTP 'Location'.
287
b5ecfcf0 288=head2 $res->status
fc7ec1d9 289
910410b8 290Sets or returns the HTTP status.
fc7ec1d9 291
292 $c->response->status(404);
aa9e8261 293
294$res->code is an alias for this, to match HTTP::Response->code.
b0ad47c1 295
b5ecfcf0 296=head2 $res->write( $data )
fbcc39ad 297
298Writes $data to the output stream.
299
e37f92f5 300=head2 $res->write_fh
301
302Returns a PSGI $writer object that has two methods, write and close. You can
303close over this object for asynchronous and nonblocking applications. For
304example (assuming you are using a supporting server, like L<Twiggy>
305
306 package AsyncExample::Controller::Root;
307
308 use Moose;
309
310 BEGIN { extends 'Catalyst::Controller' }
311
312 sub prepare_cb {
313 my $write_fh = pop;
314 return sub {
315 my $message = shift;
316 $write_fh->write("Finishing: $message\n");
317 $write_fh->close;
318 };
319 }
320
321 sub anyevent :Local :Args(0) {
322 my ($self, $c) = @_;
323 my $cb = $self->prepare_cb($c->res->write_fh);
324
325 my $watcher;
326 $watcher = AnyEvent->timer(
327 after => 5,
328 cb => sub {
329 $cb->(scalar localtime);
330 undef $watcher; # cancel circular-ref
331 });
332 }
333
e4cc83b2 334=head2 $res->print( @data )
335
336Prints @data to the output stream, separated by $,. This lets you pass
337the response object to functions that want to write to an L<IO::Handle>.
338
8738b8fe 339=head2 $self->finalize_headers($c)
340
341Writes headers to response if not already written
342
e67f0874 343=head2 from_psgi_response
344
345Given a PSGI response (either three element ARRAY reference OR coderef expecting
346a $responder) set the response from it.
347
348Properly supports streaming and delayed response and / or async IO if running
349under an expected event loop.
350
351Example:
352
353 package MyApp::Web::Controller::Test;
354
355 use base 'Catalyst::Controller';
356 use Plack::App::Directory;
357
358
359 my $app = Plack::App::Directory->new({ root => "/path/to/htdocs" })
360 ->to_app;
361
362 sub myaction :Local Args {
363 my ($self, $c) = @_;
364 $c->res->from_psgi_response($app->($self->env));
365 }
366
367Please note this does not attempt to map or nest your PSGI application under
368the Controller and Action namespace or path.
369
faa02805 370=head2 DEMOLISH
371
372Ensures that the response is flushed and closed at the end of the
373request.
374
375=head2 meta
376
377Provided by Moose
378
e4cc83b2 379=cut
380
381sub print {
382 my $self = shift;
383 my $data = shift;
384
385 defined $self->write($data) or return;
386
387 for (@_) {
388 defined $self->write($,) or return;
389 defined $self->write($_) or return;
390 }
fe3083a8 391 defined $self->write($\) or return;
b0ad47c1 392
e4cc83b2 393 return 1;
394}
395
910410b8 396=head1 AUTHORS
fc7ec1d9 397
2f381252 398Catalyst Contributors, see Catalyst.pm
fc7ec1d9 399
400=head1 COPYRIGHT
401
b0ad47c1 402This library is free software. You can redistribute it and/or modify
61b1e958 403it under the same terms as Perl itself.
fc7ec1d9 404
405=cut
406
e5ecd5bc 407__PACKAGE__->meta->make_immutable;
408
fc7ec1d9 4091;