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