1Catalyst::Response(3) User Contributed Perl DocumentationCatalyst::Response(3)
2
3
4

NAME

6       Catalyst::Response - stores output responding to the current client
7       request
8

SYNOPSIS

10           $res = $c->response;
11           $res->body;
12           $res->code;
13           $res->content_encoding;
14           $res->content_length;
15           $res->content_type;
16           $res->cookies;
17           $res->header;
18           $res->headers;
19           $res->output;
20           $res->redirect;
21           $res->status;
22           $res->write;
23

DESCRIPTION

25       This is the Catalyst Response class, which provides methods for
26       responding to the current client request. The appropriate
27       Catalyst::Engine for your environment will turn the Catalyst::Response
28       into a HTTP Response and return it to the client.
29

METHODS

31   $res->body( $text | $fh | $iohandle_object )
32           $c->response->body('Catalyst rocks!');
33
34       Sets or returns the output (text or binary data). If you are returning
35       a large body, you might want to use a IO::Handle type of object
36       (Something that implements the getline method in the same fashion), or
37       a filehandle GLOB. These will be passed down to the PSGI handler you
38       are using and might be optimized using server specific abilities (for
39       example Twiggy will attempt to server a real local file in a non
40       blocking manner).
41
42       If you are using a filehandle as the body response you are responsible
43       for making sure it conforms to the PSGI specification with regards to
44       content encoding.  Unlike with scalar body values or when using the
45       streaming interfaces we currently do not attempt to normalize and
46       encode your filehandle.  In general this means you should be sure to be
47       sending bytes not UTF8 decoded multibyte characters.
48
49       Most of the time when you do:
50
51           open(my $fh, '<:raw', $path);
52
53       You should be fine.  If you open a filehandle with a PerlIO layer you
54       probably are not fine.  You can usually fix this by explicitly using
55       binmode to set the IOLayer to :raw.  Its possible future versions of
56       Catalyst will try to 'do the right thing'.
57
58       When using a IO::Handle type of object and no content length has been
59       already set in the response headers Catalyst will make a reasonable
60       attempt to determine the size of the Handle. Depending on the
61       implementation of your handle object, setting the content length may
62       fail. If it is at all possible for you to determine the content length
63       of your handle object, it is recommended that you set the content
64       length in the response headers yourself, which will be respected and
65       sent by Catalyst in the response.
66
67       Please note that the object needs to implement "getline", not just
68       "read".  Older versions of Catalyst expected your filehandle like
69       objects to do read.  If you have code written for this expectation and
70       you cannot change the code to meet the PSGI specification, you can try
71       the following middleware Plack::Middleware::AdaptFilehandleRead which
72       will attempt to wrap your object in an interface that so conforms.
73
74       Starting from version 5.90060, when using an IO::Handle object, you may
75       want to use Plack::Middleware::XSendfile, to delegate the actual
76       serving to the frontend server. To do so, you need to pass to "body" an
77       IO object with a "path" method. This can be achieved in two ways.
78
79       Either using Plack::Util:
80
81         my $fh = IO::File->new($file, 'r');
82         Plack::Util::set_io_path($fh, $file);
83
84       Or using IO::File::WithPath
85
86         my $fh = IO::File::WithPath->new($file, 'r');
87
88       And then passing the filehandle to body and setting headers, if needed.
89
90         $c->response->body($fh);
91         $c->response->headers->content_type('text/plain');
92         $c->response->headers->content_length(-s $file);
93         $c->response->headers->last_modified((stat($file))[9]);
94
95       Plack::Middleware::XSendfile can be loaded in the application so:
96
97        __PACKAGE__->config(
98            psgi_middleware => [
99                'XSendfile',
100                # other middlewares here...
101               ],
102        );
103
104       Beware that loading the middleware without configuring the webserver to
105       set the request header "X-Sendfile-Type" to a supported type
106       ("X-Accel-Redirect" for nginx, "X-Sendfile" for Apache and Lighttpd),
107       could lead to the disclosure of private paths to malicious clients
108       setting that header.
109
110       Nginx needs the additional X-Accel-Mapping header to be set in the
111       webserver configuration, so the middleware will replace the absolute
112       path of the IO object with the internal nginx path. This is also useful
113       to prevent a buggy app to server random files from the filesystem, as
114       it's an internal redirect.
115
116       An nginx configuration for FastCGI could look so:
117
118        server {
119            server_name example.com;
120            root /my/app/root;
121            location /private/repo/ {
122                internal;
123                alias /my/app/repo/;
124            }
125            location /private/staging/ {
126                internal;
127                alias /my/app/staging/;
128            }
129            location @proxy {
130                include /etc/nginx/fastcgi_params;
131                fastcgi_param SCRIPT_NAME '';
132                fastcgi_param PATH_INFO   $fastcgi_script_name;
133                fastcgi_param HTTP_X_SENDFILE_TYPE X-Accel-Redirect;
134                fastcgi_param HTTP_X_ACCEL_MAPPING /my/app=/private;
135                fastcgi_pass  unix:/my/app/run/app.sock;
136           }
137        }
138
139       In the example above, passing filehandles with a local path matching
140       /my/app/staging or /my/app/repo will be served by nginx. Passing paths
141       with other locations will lead to an internal server error.
142
143       Setting the body to a filehandle without the "path" method bypasses the
144       middleware completely.
145
146       For Apache and Lighttpd, the mapping doesn't apply and setting the
147       X-Sendfile-Type is enough.
148
149   $res->has_body
150       Predicate which returns true when a body has been set.
151
152   $res->code
153       Alias for $res->status.
154
155   $res->content_encoding
156       Shortcut for $res->headers->content_encoding.
157
158   $res->content_length
159       Shortcut for $res->headers->content_length.
160
161   $res->content_type
162       Shortcut for $res->headers->content_type.
163
164       This value is typically set by your view or plugin. For example,
165       Catalyst::Plugin::Static::Simple will guess the mime type based on the
166       file it found, while Catalyst::View::TT defaults to "text/html".
167
168   $res->content_type_charset
169       Shortcut for $res->headers->content_type_charset;
170
171   $res->cookies
172       Returns a reference to a hash containing cookies to be set. The keys of
173       the hash are the cookies' names, and their corresponding values are
174       hash references used to construct a CGI::Simple::Cookie object.
175
176           $c->response->cookies->{foo} = { value => '123' };
177
178       The keys of the hash reference on the right correspond to the
179       CGI::Simple::Cookie parameters of the same name, except they are used
180       without a leading dash.  Possible parameters are:
181
182       value
183       expires
184       domain
185       path
186       secure
187       httponly
188
189   $res->header
190       Shortcut for $res->headers->header.
191
192   $res->headers
193       Returns an HTTP::Headers object, which can be used to set headers.
194
195           $c->response->headers->header( 'X-Catalyst' => $Catalyst::VERSION );
196
197   $res->output
198       Alias for $res->body.
199
200   $res->redirect( $url, $status )
201       Causes the response to redirect to the specified URL. The default
202       status is 302.
203
204           $c->response->redirect( 'http://slashdot.org' );
205           $c->response->redirect( 'http://slashdot.org', 307 );
206
207       This is a convenience method that sets the Location header to the
208       redirect destination, and then sets the response status.  You will want
209       to " return " or "$c->detach()" to interrupt the normal processing flow
210       if you want the redirect to occur straight away.
211
212       Note: do not give a relative URL as $url, i.e: one that is not fully
213       qualified (= "http://...", etc.) or that starts with a slash (=
214       "/path/here"). While it may work, it is not guaranteed to do the right
215       thing and is not a standard behaviour. You may opt to use uri_for() or
216       uri_for_action() instead.
217
218       Note: If $url is an object that does ->as_string (such as URI, which is
219       what you get from ->uri_for) we automatically call that to stringify.
220       This should ease the common case usage
221
222           return $c->res->redirect( $c->uri_for(...));
223
224   $res->location
225       Sets or returns the HTTP 'Location'.
226
227   $res->status
228       Sets or returns the HTTP status.
229
230           $c->response->status(404);
231
232       $res->code is an alias for this, to match HTTP::Response->code.
233
234   $res->write( $data )
235       Writes $data to the output stream.  Calling this method will finalize
236       your headers and send the headers and status code response to the
237       client (so changing them afterwards is a waste... be sure to set your
238       headers correctly first).
239
240       You may call this as often as you want throughout your response cycle.
241       You may even set a 'body' afterward.  So for example you might write
242       your HTTP headers and the HEAD section of your document and then set
243       the body from a template driven from a database.  In some cases this
244       can seem to the client as if you had a faster overall response (but
245       note that unless your server support chunked body your content is
246       likely to get queued anyway (Starman and most other http 1.1 webservers
247       support this).
248
249       If there is an encoding set, we encode each line of the response (the
250       default encoding is UTF-8).
251
252   $res->unencoded_write( $data )
253       Works just like ->write but we don't apply any content encoding to
254       $data.  Use this if you are already encoding the $data or the data is
255       arriving from an encoded storage.
256
257   $res->write_fh
258       Returns an instance of Catalyst::Response::Writer, which is a
259       lightweight decorator over the PSGI $writer object (see
260       PSGI.pod\Delayed-Response-and-Streaming-Body).
261
262       In addition to proxying the "write" and "close" method from the
263       underlying PSGI writer, this proxy object knows any application wide
264       encoding, and provides a method "write_encoded" that will properly
265       encode your written lines based upon your encoding settings.  By
266       default in Catalyst responses are UTF-8 encoded and this is the
267       encoding used if you respond via "write_encoded".  If you want to
268       handle encoding yourself, you can use the "write" method directly.
269
270       Encoding only applies to content types for which it matters.  Currently
271       the following content types are assumed to need encoding: text
272       (including HTML), xml and javascript.
273
274       We provide access to this object so that you can properly close over it
275       for use in asynchronous and nonblocking applications.  For example
276       (assuming you are using a supporting server, like Twiggy:
277
278           package AsyncExample::Controller::Root;
279
280           use Moose;
281
282           BEGIN { extends 'Catalyst::Controller' }
283
284           sub prepare_cb {
285             my $write_fh = pop;
286             return sub {
287               my $message = shift;
288               $write_fh->write("Finishing: $message\n");
289               $write_fh->close;
290             };
291           }
292
293           sub anyevent :Local :Args(0) {
294             my ($self, $c) = @_;
295             my $cb = $self->prepare_cb($c->res->write_fh);
296
297             my $watcher;
298             $watcher = AnyEvent->timer(
299               after => 5,
300               cb => sub {
301                 $cb->(scalar localtime);
302                 undef $watcher; # cancel circular-ref
303               });
304           }
305
306       Like the 'write' method, calling this will finalize headers. Unlike
307       'write' when you can this it is assumed you are taking control of the
308       response so the body is never finalized (there isn't one anyway) and
309       you need to call the close method.
310
311   $res->print( @data )
312       Prints @data to the output stream, separated by $,.  This lets you pass
313       the response object to functions that want to write to an IO::Handle.
314
315   $res->finalize_headers()
316       Writes headers to response if not already written
317
318   from_psgi_response
319       Given a PSGI response (either three element ARRAY reference OR coderef
320       expecting a $responder) set the response from it.
321
322       Properly supports streaming and delayed response and / or async IO if
323       running under an expected event loop.
324
325       If passed an object, will expect that object to do a method "as_psgi".
326
327       Example:
328
329           package MyApp::Web::Controller::Test;
330
331           use base 'Catalyst::Controller';
332           use Plack::App::Directory;
333
334
335           my $app = Plack::App::Directory->new({ root => "/path/to/htdocs" })
336             ->to_app;
337
338           sub myaction :Local Args {
339             my ($self, $c) = @_;
340             $c->res->from_psgi_response($app->($c->req->env));
341           }
342
343           sub streaming_body :Local {
344             my ($self, $c) = @_;
345             my $psgi_app = sub {
346                 my $respond = shift;
347                 my $writer = $respond->([200,["Content-Type" => "text/plain"]]);
348                 $writer->write("body");
349                 $writer->close;
350             };
351             $c->res->from_psgi_response($psgi_app);
352           }
353
354       Please note this does not attempt to map or nest your PSGI application
355       under the Controller and Action namespace or path. You may wish to
356       review 'PSGI Helpers' under Catalyst::Utils for help in properly
357       nesting applications.
358
359       NOTE If your external PSGI application returns a response that has a
360       character set associated with the content type (such as "text/html;
361       charset=UTF-8") we set $c->clear_encoding to remove any additional
362       content type encoding processing later in the application (this is done
363       to avoid double encoding issues).
364
365       NOTE If your external PSGI application is streaming, we assume you
366       completely handle the entire jobs (including closing the stream).  This
367       will also bypass the output finalization methods on Catalyst (such as
368       'finalize_body' which gets called but then skipped when it finds that
369       output is already finished.)  Its possible this might cause issue with
370       some plugins that want to do 'things' during those finalization
371       methods.  Just understand what is happening.
372
373   encodable_content_type
374       This is a regular expression used to determine of the current content
375       type should be considered encodable.  Currently we apply default
376       encoding (usually UTF8) to text type contents.  Here's the default
377       regular expression:
378
379       This would match content types like:
380
381           text/plain
382           text/html
383           text/xml
384           application/javascript
385           application/xml
386           application/vnd.user+xml
387
388       NOTE: We don't encode JSON content type responses by default since most
389       of the JSON serializers that are commonly used for this task will do so
390       automatically and we don't want to double encode.  If you are not using
391       a tool like JSON to produce JSON type content, (for example you are
392       using a template system, or creating the strings manually) you will
393       need to either encoding the body yourself:
394
395           $c->response->body( $c->encoding->encode( $body, $c->_encode_check ) );
396
397       Or you can alter the regular expression using this attribute.
398
399   encodable_response
400       Given a Catalyst::Response return true if its one that can be encoded.
401
402            make sure there is an encoding set on the response
403            make sure the content type is encodable
404            make sure no content type charset has been already set to something different from the global encoding
405            make sure no content encoding is present.
406
407       Note this does not inspect a body since we do allow automatic encoding
408       on streaming type responses.
409
410   DEMOLISH
411       Ensures that the response is flushed and closed at the end of the
412       request.
413
414   meta
415       Provided by Moose
416

AUTHORS

418       Catalyst Contributors, see Catalyst.pm
419
421       This library is free software. You can redistribute it and/or modify it
422       under the same terms as Perl itself.
423
424
425
426perl v5.34.0                      2021-07-22             Catalyst::Response(3)
Impressum