let you not finalize a request when you wish to jailbreak psgi
[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   sub _build_write_fh {
36     my $self = shift;
37     $self->_context->finalize_headers unless
38       $self->finalized_headers;
39     $self->_writer;
40   };
41
42 sub DEMOLISH {
43   my $self = shift;
44   return if $self->has_write_fh;
45   if($self->_has_writer) {
46     $self->_writer->close
47   }
48 }
49
50 has cookies   => (is => 'rw', default => sub { {} });
51 has body      => (is => 'rw', default => undef);
52 sub has_body { defined($_[0]->body) }
53
54 has location  => (is => 'rw');
55 has status    => (is => 'rw', default => 200);
56 has finalized_headers => (is => 'rw', default => 0);
57 has headers   => (
58   is      => 'rw',
59   isa => 'HTTP::Headers',
60   handles => [qw(content_encoding content_length content_type header)],
61   default => sub { HTTP::Headers->new() },
62   required => 1,
63   lazy => 1,
64 );
65 has _context => (
66   is => 'rw',
67   weak_ref => 1,
68   clearer => '_clear_context',
69 );
70
71 sub output { shift->body(@_) }
72
73 sub code   { shift->status(@_) }
74
75 sub write {
76     my ( $self, $buffer ) = @_;
77
78     # Finalize headers if someone manually writes output
79     $self->_context->finalize_headers unless $self->finalized_headers;
80
81     $buffer = q[] unless defined $buffer;
82
83     my $len = length($buffer);
84     $self->_writer->write($buffer);
85
86     return $len;
87 }
88
89 sub finalize_headers {
90     my ($self) = @_;
91
92     # This is a less-than-pretty hack to avoid breaking the old
93     # Catalyst::Engine::PSGI. 5.9 Catalyst::Engine sets a response_cb and
94     # expects us to pass headers to it here, whereas Catalyst::Enngine::PSGI
95     # just pulls the headers out of $ctx->response in its run method and never
96     # sets response_cb. So take the lack of a response_cb as a sign that we
97     # don't need to set the headers.
98
99     return unless $self->_has_response_cb;
100
101     # If we already have a writer, we already did this, so don't do it again
102     return if $self->_has_writer;
103
104     my @headers;
105     $self->headers->scan(sub { push @headers, @_ });
106
107     my $writer = $self->_response_cb->([ $self->status, \@headers ]);
108     $self->_set_writer($writer);
109     $self->_clear_response_cb;
110
111     return;
112 }
113
114 =head1 NAME
115
116 Catalyst::Response - stores output responding to the current client request
117
118 =head1 SYNOPSIS
119
120     $res = $c->response;
121     $res->body;
122     $res->code;
123     $res->content_encoding;
124     $res->content_length;
125     $res->content_type;
126     $res->cookies;
127     $res->header;
128     $res->headers;
129     $res->output;
130     $res->redirect;
131     $res->status;
132     $res->write;
133
134 =head1 DESCRIPTION
135
136 This is the Catalyst Response class, which provides methods for responding to
137 the current client request. The appropriate L<Catalyst::Engine> for your environment
138 will turn the Catalyst::Response into a HTTP Response and return it to the client.
139
140 =head1 METHODS
141
142 =head2 $res->body( $text | $fh | $iohandle_object )
143
144     $c->response->body('Catalyst rocks!');
145
146 Sets or returns the output (text or binary data). If you are returning a large body,
147 you might want to use a L<IO::Handle> type of object (Something that implements the read method
148 in the same fashion), or a filehandle GLOB. Catalyst
149 will write it piece by piece into the response.
150
151 =head2 $res->has_body
152
153 Predicate which returns true when a body has been set.
154
155 =head2 $res->code
156
157 Alias for $res->status.
158
159 =head2 $res->content_encoding
160
161 Shortcut for $res->headers->content_encoding.
162
163 =head2 $res->content_length
164
165 Shortcut for $res->headers->content_length.
166
167 =head2 $res->content_type
168
169 Shortcut for $res->headers->content_type.
170
171 This value is typically set by your view or plugin. For example,
172 L<Catalyst::Plugin::Static::Simple> will guess the mime type based on the file
173 it found, while L<Catalyst::View::TT> defaults to C<text/html>.
174
175 =head2 $res->cookies
176
177 Returns a reference to a hash containing cookies to be set. The keys of the
178 hash are the cookies' names, and their corresponding values are hash
179 references used to construct a L<CGI::Simple::Cookie> object.
180
181     $c->response->cookies->{foo} = { value => '123' };
182
183 The keys of the hash reference on the right correspond to the L<CGI::Simple::Cookie>
184 parameters of the same name, except they are used without a leading dash.
185 Possible parameters are:
186
187 =over
188
189 =item value
190
191 =item expires
192
193 =item domain
194
195 =item path
196
197 =item secure
198
199 =item httponly
200
201 =back
202
203 =head2 $res->header
204
205 Shortcut for $res->headers->header.
206
207 =head2 $res->headers
208
209 Returns an L<HTTP::Headers> object, which can be used to set headers.
210
211     $c->response->headers->header( 'X-Catalyst' => $Catalyst::VERSION );
212
213 =head2 $res->output
214
215 Alias for $res->body.
216
217 =head2 $res->redirect( $url, $status )
218
219 Causes the response to redirect to the specified URL. The default status is
220 C<302>.
221
222     $c->response->redirect( 'http://slashdot.org' );
223     $c->response->redirect( 'http://slashdot.org', 307 );
224
225 This is a convenience method that sets the Location header to the
226 redirect destination, and then sets the response status.  You will
227 want to C< return > or C<< $c->detach() >> to interrupt the normal
228 processing flow if you want the redirect to occur straight away.
229
230 B<Note:> do not give a relative URL as $url, i.e: one that is not fully
231 qualified (= C<http://...>, etc.) or that starts with a slash
232 (= C</path/here>). While it may work, it is not guaranteed to do the right
233 thing and is not a standard behaviour. You may opt to use uri_for() or
234 uri_for_action() instead.
235
236 =cut
237
238 sub redirect {
239     my $self = shift;
240
241     if (@_) {
242         my $location = shift;
243         my $status   = shift || 302;
244
245         $self->location($location);
246         $self->status($status);
247     }
248
249     return $self->location;
250 }
251
252 =head2 $res->location
253
254 Sets or returns the HTTP 'Location'.
255
256 =head2 $res->status
257
258 Sets or returns the HTTP status.
259
260     $c->response->status(404);
261
262 $res->code is an alias for this, to match HTTP::Response->code.
263
264 =head2 $res->write( $data )
265
266 Writes $data to the output stream.
267
268 =head2 $res->write_fh
269
270 Returns a PSGI $writer object that has two methods, write and close.  You can
271 close over this object for asynchronous and nonblocking applications.  For
272 example (assuming you are using a supporting server, like L<Twiggy>
273
274     package AsyncExample::Controller::Root;
275
276     use Moose;
277
278     BEGIN { extends 'Catalyst::Controller' }
279
280     sub prepare_cb {
281       my $write_fh = pop;
282       return sub {
283         my $message = shift;
284         $write_fh->write("Finishing: $message\n");
285         $write_fh->close;
286       };
287     }
288
289     sub anyevent :Local :Args(0) {
290       my ($self, $c) = @_;
291       my $cb = $self->prepare_cb($c->res->write_fh);
292
293       my $watcher;
294       $watcher = AnyEvent->timer(
295         after => 5,
296         cb => sub {
297           $cb->(scalar localtime);
298           undef $watcher; # cancel circular-ref
299         });
300     }
301
302 =head2 $res->print( @data )
303
304 Prints @data to the output stream, separated by $,.  This lets you pass
305 the response object to functions that want to write to an L<IO::Handle>.
306
307 =head2 $self->finalize_headers($c)
308
309 Writes headers to response if not already written
310
311 =head2 DEMOLISH
312
313 Ensures that the response is flushed and closed at the end of the
314 request.
315
316 =head2 meta
317
318 Provided by Moose
319
320 =cut
321
322 sub print {
323     my $self = shift;
324     my $data = shift;
325
326     defined $self->write($data) or return;
327
328     for (@_) {
329         defined $self->write($,) or return;
330         defined $self->write($_) or return;
331     }
332     defined $self->write($\) or return;
333
334     return 1;
335 }
336
337 =head1 AUTHORS
338
339 Catalyst Contributors, see Catalyst.pm
340
341 =head1 COPYRIGHT
342
343 This library is free software. You can redistribute it and/or modify
344 it under the same terms as Perl itself.
345
346 =cut
347
348 __PACKAGE__->meta->make_immutable;
349
350 1;