PrePAN

Sign in to PrePAN

Plack::Response::Data Response Content Body Encoder for JSON, XML, YAML, etc.

Good

Synopsis

use Plack::Response::Data;

sub psgi_handler {
    my $env  = shift;
    my $req  = Plack::Request->new($env);

    my $data = { foo => 'bar', qux => [1, 2, 3] };
    my $res  = Plack::Response::Data->new(200)->format('JSON')->data($data);
    return $res->finalize;
}

# Response:

HTTP/1.0 200 OK
Content-Length: 13
Content-Type: application/json

{"foo":"bar","qux":[1,2,3]}

Description

This uses Plack::Response's response content body as a data container to respond a data encoded in JSON, XML, YAML format, etc. This would help you to build an Web API server application in a short code.

Comments

Personally I would prefer the PlackX namespace for that.
All the settings that are in methods would be better placed as arguments of `new`.
Also "use base" -> "use parent".

Anyway, I think that a more generic Plack::Middleware module (that would sniff the request header to detect what the client wants, based on the Accept header, and automatically render based on that) would be more helpful. Does it already exists?
See also Plack::ResponseHelper

Please sign up to post a review.