Skip to content

Instantly share code, notes, and snippets.

@anazawa
Created November 8, 2012 20:10
Show Gist options
  • Select an option

  • Save anazawa/4041229 to your computer and use it in GitHub Desktop.

Select an option

Save anazawa/4041229 to your computer and use it in GitHub Desktop.
Yet another implementation of CGI::PSGI::psgi_header()

Although it's not intended to send a pull request to the repository, CGI::PSGI, I believe it's worth trying this kind of solutions.

There is more than one way to do it.

For instance, CGI::Emulate::PSGI uses HTTP::Response to parse CGI response headers. This module captures STDOUT and parses it using regular expressions to generate PSGI response headers array.

CGI::PSGI implements psgi_header() method which was literally copied from CGI.pm and rearranged properly to satisfy PSGI specification.

CGI::Header is a subclass of Hash because CGI::header() behaves like a hash. Though the data structure is different from PSGI headers, it's easy to convert a hash to an array. In fact, this module provides flatten() method which can be used to generate PSGI response headers array.

CGI::Header will be yet another solution to adapt CGI applications to the PSGI protocol.

package CGI::PSGI;
use strict;
use warnings;
use parent 'CGI';
use CGI::Util;
use CGI::Header;
sub psgi_header {
my ( $self, @args ) = @_;
my ( $result, $leftover ) = CGI::Util::_rearrange_params([
[qw/TYPE CONTENT_TYPE CONTENT-TYPE/],
[qw/COOKIE COOKIES/],
], @args);
my %header;
@header{qw/-type -cookie/} = @{ $result };
@header{ map { "-$_" } keys %{$leftover} } = values %{ $leftover };
$header{-charset} = $self->charset( $header{-charset} );
my $header = CGI::Header->new( \%header );
$header->set( 'Pragma' => 'no-cache' ) if $self->cache;
$header->nph( 0 ); # do not return the Server header
my $status = $header->delete( 'Status' ) || '200 OK';
$status =~ s/\D*$//;
return $status, [ $header->flatten ];
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment