Add PerlIO methods to Catalyst::Response, so that it more properly
[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
47 sub output { shift->body(@_) }
48
49 sub code   { shift->status(@_) }
50
51 sub write {
52     my ( $self, $buffer ) = @_;
53
54     # Finalize headers if someone manually writes output
55     $self->finalize_headers;
56
57     $buffer = q[] unless defined $buffer;
58
59     my $len = length($buffer);
60     $self->_writer->write($buffer);  # ignore PerlIO's LEN, [OFFSET] params
61
62     return $len;
63 }
64
65 sub finalize_headers {
66     my ($self) = @_;
67
68     # This is a less-than-pretty hack to avoid breaking the old
69     # Catalyst::Engine::PSGI. 5.9 Catalyst::Engine sets a response_cb and
70     # expects us to pass headers to it here, whereas Catalyst::Engine::PSGI
71     # just pulls the headers out of $ctx->response in its run method and never
72     # sets response_cb. So take the lack of a response_cb as a sign that we
73     # don't need to set the headers.
74
75     return unless $self->_has_response_cb;
76
77     # If we already have a writer, we already did this, so don't do it again
78     return if $self->_has_writer;
79
80     my @headers;
81     $self->headers->scan(sub { push @headers, @_ });
82
83     my $writer = $self->_response_cb->([ $self->status, \@headers ]);
84     $self->_set_writer($writer);
85     $self->_clear_response_cb;
86
87     return;
88 }
89
90 =head1 NAME
91
92 Catalyst::Response - stores output responding to the current client request
93
94 =head1 SYNOPSIS
95
96     $res = $c->response;
97     $res->body;
98     $res->code;
99     $res->content_encoding;
100     $res->content_length;
101     $res->content_type;
102     $res->cookies;
103     $res->header;
104     $res->headers;
105     $res->output;
106     $res->redirect;
107     $res->status;
108     $res->write;
109
110 =head1 DESCRIPTION
111
112 This is the Catalyst Response class, which provides methods for responding to
113 the current client request. The appropriate L<Catalyst::Engine> for your environment
114 will turn the Catalyst::Response into a HTTP Response and return it to the client.
115
116 =head1 METHODS
117
118 =head2 $res->body( $text | $fh | $iohandle_object )
119
120     $c->response->body('Catalyst rocks!');
121
122 Sets or returns the output (text or binary data). If you are returning a large body,
123 you might want to use a L<IO::Handle> type of object (Something that implements the read method
124 in the same fashion), or a filehandle GLOB. Catalyst
125 will write it piece by piece into the response.
126
127 =head2 $res->has_body
128
129 Predicate which returns true when a body has been set.
130
131 =head2 $res->code
132
133 Alias for $res->status.
134
135 =head2 $res->content_encoding
136
137 Shortcut for $res->headers->content_encoding.
138
139 =head2 $res->content_length
140
141 Shortcut for $res->headers->content_length.
142
143 =head2 $res->content_type
144
145 Shortcut for $res->headers->content_type.
146
147 This value is typically set by your view or plugin. For example,
148 L<Catalyst::Plugin::Static::Simple> will guess the mime type based on the file
149 it found, while L<Catalyst::View::TT> defaults to C<text/html>.
150
151 =head2 $res->cookies
152
153 Returns a reference to a hash containing cookies to be set. The keys of the
154 hash are the cookies' names, and their corresponding values are hash
155 references used to construct a L<CGI::Simple::Cookie> object.
156
157     $c->response->cookies->{foo} = { value => '123' };
158
159 The keys of the hash reference on the right correspond to the L<CGI::Simple::Cookie>
160 parameters of the same name, except they are used without a leading dash.
161 Possible parameters are:
162
163 =over
164
165 =item value
166
167 =item expires
168
169 =item domain
170
171 =item path
172
173 =item secure
174
175 =item httponly
176
177 =back
178
179 =head2 $res->header
180
181 Shortcut for $res->headers->header.
182
183 =head2 $res->headers
184
185 Returns an L<HTTP::Headers> object, which can be used to set headers.
186
187     $c->response->headers->header( 'X-Catalyst' => $Catalyst::VERSION );
188
189 =head2 $res->output
190
191 Alias for $res->body.
192
193 =head2 $res->redirect( $url, $status )
194
195 Causes the response to redirect to the specified URL. The default status is
196 C<302>.
197
198     $c->response->redirect( 'http://slashdot.org' );
199     $c->response->redirect( 'http://slashdot.org', 307 );
200
201 This is a convenience method that sets the Location header to the
202 redirect destination, and then sets the response status.  You will
203 want to C< return > or C<< $c->detach() >> to interrupt the normal
204 processing flow if you want the redirect to occur straight away.
205
206 B<Note:> do not give a relative URL as $url, i.e: one that is not fully
207 qualified (= C<http://...>, etc.) or that starts with a slash
208 (= C</path/here>). While it may work, it is not guaranteed to do the right
209 thing and is not a standard behaviour. You may opt to use uri_for() or
210 uri_for_action() instead.
211
212 =cut
213
214 sub redirect {
215     my $self = shift;
216
217     if (@_) {
218         my $location = shift;
219         my $status   = shift || 302;
220
221         $self->location($location);
222         $self->status($status);
223     }
224
225     return $self->location;
226 }
227
228 =head2 $res->location
229
230 Sets or returns the HTTP 'Location'.
231
232 =head2 $res->status
233
234 Sets or returns the HTTP status.
235
236     $c->response->status(404);
237
238 $res->code is an alias for this, to match HTTP::Response->code.
239
240 =head2 $res->write( $data )
241
242 Writes $data to the output stream.
243
244 =head2 $self->finalize_headers($c)
245
246 Writes headers to response if not already written
247
248 =head2 DEMOLISH
249
250 Ensures that the response is flushed and closed at the end of the
251 request.
252
253 =head2 meta
254
255 Provided by Moose
256
257 =head1 IO::Handle METHODS
258
259 Certain other methods are provided to ensure (reasonable) compatibility
260 to other functions expecting a L<IO::Handle> object:
261
262     $res->open    # ignores all params and calls $res->finalize_headers
263     $res->close
264     $res->opened  # auto-opens
265     $res->fileno
266     $res->print( ARGS )  # uses $, & $\
267     $res->printf( FMT, [ARGS] )
268     $res->say( ARGS )
269     $res->printflush( ARGS )
270     
271     # these are checked for similar methods within the writer
272     $res->autoflush( [BOOL] )  # echos BOOL or 0 if method not found
273     $res->blocking( [BOOL] )   # echos BOOL or 1 if method not found
274     $res->binmode( [BOOL] )    # echos BOOL or 1 if method not found
275     $res->error                # returns $! if method not found
276     $res->clearerr             # clears $! and returns 0 if method not found
277     $res->sync                 # tries $res->flush if method not found
278     $res->flush                # returns "0 but true" if method not found
279
280 =for Pod::Coverage open(ed)?|close|fileno|print(f?|flush)|say
281
282 =cut
283
284 sub open   {
285     # We are just going to blissfully ignore the params
286     my ($self) = shift;
287     
288     $self->finalize_headers;
289     return 1;
290 }
291 sub close  { return shift->_has_writer && shift->_writer->close(); }
292 sub opened { return shift->open(); }          # if it's asking, just open up the writer
293 sub fileno { return scalar shift->_writer; }  # scalar reference comparison should be good enough
294 sub print  {
295     my ($self, @data) = (shift, @_);
296     
297     # (var usage per Perl print docs)
298     @data = map { ($_, $,) } @data;       # poor man's "array join"
299     splice(@data, -1, 1, $\) if (@data);  # remove trailing sep + add $\
300     
301     for (@data) { defined $self->write($_) or return; }
302     
303     return 1;
304 }
305 sub printf {
306     my ($self) = shift;
307     return $self->write( sprintf(@_) );  # per docs, printf doesn't use $/
308 }
309 sub say {
310     my ($self) = shift;
311     local $\ = "\n";
312     return $self->print(@_);
313 }
314 sub printflush {
315     my ($self) = shift;
316     my $af  = $self->autoflush(1);
317     my $ret = $self->print(@_);
318     $self->autoflush($af);
319     return $ret;
320 }
321
322 # I/O method checking
323 sub _attempt {
324    my ($self, $method, $default, @data) = @_;
325    no strict 'refs';  # no complainy at CODEREFs
326
327     return $self->_has_writer && $self->_writer->can($method) ?
328         $self->_writer->$method(@data) :
329         ref $default eq 'CODE' ?
330             &$default($self) :  # (kinda janky, but $self->$default isn't right either)
331             defined $data[0] ? $data[0] : $default  # can't tell, but don't error on it, either (default action for booleans)
332    ;
333 }   
334    
335 foreach my $pair (
336     [autoflush => 0],
337     [blocking  => 1],
338     [binmode   => 1],
339     [error     => sub { $!             }],
340     [clearerr  => sub { undef $! || 0  }],  # 0 = don't error
341     [sync      => sub { shift->flush() }],  # fallback
342     [flush     => sub { "0 but true"   }],  # don't error (but don't echo either, hence a CODEREF)
343 )                                #  $method           $self           @([$method, $default]), @data 
344     { __PACKAGE__->meta->add_method($pair->[0], sub { shift->_attempt(@$pair, @_); }); }
345
346 =head1 AUTHORS
347
348 Catalyst Contributors, see Catalyst.pm
349
350 =head1 COPYRIGHT
351
352 This library is free software. You can redistribute it and/or modify
353 it under the same terms as Perl itself.
354
355 =cut
356
357 __PACKAGE__->meta->make_immutable;
358
359 1;