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