first pass $res->from_psgi_response
[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',
24     writer  => '_set_writer',
25     clearer => '_clear_writer',
26     predicate => '_has_writer',
27 );
28
29 has write_fh => (
30   is=>'ro',
31   predicate=>'has_write_fh',
32   lazy=>1,
33   builder=>'_build_write_fh',
34 );
35
36 sub _build_write_fh {
37   my $self = shift;
38   $self->_context->finalize_headers unless
39     $self->finalized_headers;
40   $self->_writer;
41 };
42
43 sub DEMOLISH {
44   my $self = shift;
45   return if $self->has_write_fh;
46   if($self->_has_writer) {
47     $self->_writer->close
48   }
49 }
50
51 has cookies   => (is => 'rw', default => sub { {} });
52 has body      => (is => 'rw', default => undef);
53 sub has_body { defined($_[0]->body) }
54
55 has location  => (is => 'rw');
56 has status    => (is => 'rw', default => 200);
57 has finalized_headers => (is => 'rw', default => 0);
58 has headers   => (
59   is      => 'rw',
60   isa => 'HTTP::Headers',
61   handles => [qw(content_encoding content_length content_type header)],
62   default => sub { HTTP::Headers->new() },
63   required => 1,
64   lazy => 1,
65 );
66 has _context => (
67   is => 'rw',
68   weak_ref => 1,
69   clearer => '_clear_context',
70 );
71
72 sub output { shift->body(@_) }
73
74 sub code   { shift->status(@_) }
75
76 sub write {
77     my ( $self, $buffer ) = @_;
78
79     # Finalize headers if someone manually writes output
80     $self->_context->finalize_headers unless $self->finalized_headers;
81
82     $buffer = q[] unless defined $buffer;
83
84     my $len = length($buffer);
85     $self->_writer->write($buffer);
86
87     return $len;
88 }
89
90 sub 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
115 sub 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
146 =head1 NAME
147
148 Catalyst::Response - stores output responding to the current client request
149
150 =head1 SYNOPSIS
151
152     $res = $c->response;
153     $res->body;
154     $res->code;
155     $res->content_encoding;
156     $res->content_length;
157     $res->content_type;
158     $res->cookies;
159     $res->header;
160     $res->headers;
161     $res->output;
162     $res->redirect;
163     $res->status;
164     $res->write;
165
166 =head1 DESCRIPTION
167
168 This is the Catalyst Response class, which provides methods for responding to
169 the current client request. The appropriate L<Catalyst::Engine> for your environment
170 will turn the Catalyst::Response into a HTTP Response and return it to the client.
171
172 =head1 METHODS
173
174 =head2 $res->body( $text | $fh | $iohandle_object )
175
176     $c->response->body('Catalyst rocks!');
177
178 Sets or returns the output (text or binary data). If you are returning a large body,
179 you might want to use a L<IO::Handle> type of object (Something that implements the read method
180 in the same fashion), or a filehandle GLOB. Catalyst
181 will write it piece by piece into the response.
182
183 =head2 $res->has_body
184
185 Predicate which returns true when a body has been set.
186
187 =head2 $res->code
188
189 Alias for $res->status.
190
191 =head2 $res->content_encoding
192
193 Shortcut for $res->headers->content_encoding.
194
195 =head2 $res->content_length
196
197 Shortcut for $res->headers->content_length.
198
199 =head2 $res->content_type
200
201 Shortcut for $res->headers->content_type.
202
203 This value is typically set by your view or plugin. For example,
204 L<Catalyst::Plugin::Static::Simple> will guess the mime type based on the file
205 it found, while L<Catalyst::View::TT> defaults to C<text/html>.
206
207 =head2 $res->cookies
208
209 Returns a reference to a hash containing cookies to be set. The keys of the
210 hash are the cookies' names, and their corresponding values are hash
211 references used to construct a L<CGI::Simple::Cookie> object.
212
213     $c->response->cookies->{foo} = { value => '123' };
214
215 The keys of the hash reference on the right correspond to the L<CGI::Simple::Cookie>
216 parameters of the same name, except they are used without a leading dash.
217 Possible parameters are:
218
219 =over
220
221 =item value
222
223 =item expires
224
225 =item domain
226
227 =item path
228
229 =item secure
230
231 =item httponly
232
233 =back
234
235 =head2 $res->header
236
237 Shortcut for $res->headers->header.
238
239 =head2 $res->headers
240
241 Returns an L<HTTP::Headers> object, which can be used to set headers.
242
243     $c->response->headers->header( 'X-Catalyst' => $Catalyst::VERSION );
244
245 =head2 $res->output
246
247 Alias for $res->body.
248
249 =head2 $res->redirect( $url, $status )
250
251 Causes the response to redirect to the specified URL. The default status is
252 C<302>.
253
254     $c->response->redirect( 'http://slashdot.org' );
255     $c->response->redirect( 'http://slashdot.org', 307 );
256
257 This is a convenience method that sets the Location header to the
258 redirect destination, and then sets the response status.  You will
259 want to C< return > or C<< $c->detach() >> to interrupt the normal
260 processing flow if you want the redirect to occur straight away.
261
262 B<Note:> do not give a relative URL as $url, i.e: one that is not fully
263 qualified (= 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
265 thing and is not a standard behaviour. You may opt to use uri_for() or
266 uri_for_action() instead.
267
268 =cut
269
270 sub redirect {
271     my $self = shift;
272
273     if (@_) {
274         my $location = shift;
275         my $status   = shift || 302;
276
277         $self->location($location);
278         $self->status($status);
279     }
280
281     return $self->location;
282 }
283
284 =head2 $res->location
285
286 Sets or returns the HTTP 'Location'.
287
288 =head2 $res->status
289
290 Sets or returns the HTTP status.
291
292     $c->response->status(404);
293
294 $res->code is an alias for this, to match HTTP::Response->code.
295
296 =head2 $res->write( $data )
297
298 Writes $data to the output stream.
299
300 =head2 $res->write_fh
301
302 Returns a PSGI $writer object that has two methods, write and close.  You can
303 close over this object for asynchronous and nonblocking applications.  For
304 example (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
334 =head2 $res->print( @data )
335
336 Prints @data to the output stream, separated by $,.  This lets you pass
337 the response object to functions that want to write to an L<IO::Handle>.
338
339 =head2 $self->finalize_headers($c)
340
341 Writes headers to response if not already written
342
343 =head2 from_psgi_response
344
345 Given a PSGI response (either three element ARRAY reference OR coderef expecting
346 a $responder) set the response from it.
347
348 Properly supports streaming and delayed response and / or async IO if running
349 under an expected event loop.
350
351 Example:
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
367 Please note this does not attempt to map or nest your PSGI application under
368 the Controller and Action namespace or path.  
369
370 =head2 DEMOLISH
371
372 Ensures that the response is flushed and closed at the end of the
373 request.
374
375 =head2 meta
376
377 Provided by Moose
378
379 =cut
380
381 sub 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     }
391     defined $self->write($\) or return;
392
393     return 1;
394 }
395
396 =head1 AUTHORS
397
398 Catalyst Contributors, see Catalyst.pm
399
400 =head1 COPYRIGHT
401
402 This library is free software. You can redistribute it and/or modify
403 it under the same terms as Perl itself.
404
405 =cut
406
407 __PACKAGE__->meta->make_immutable;
408
409 1;