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