1 package HTTP::Request::AsCGI;
5 use base 'Class::Accessor::Fast';
10 __PACKAGE__->mk_accessors( qw[ enviroment request stdin stdout stderr ] );
21 stdin => IO::File->new_tmpfile,
22 stdout => IO::File->new_tmpfile,
23 stderr => IO::File->new_tmpfile
26 $self->{enviroment} = {
27 GATEWAY_INTERFACE => 'CGI/1.1',
28 HTTP_HOST => $request->uri->host_port,
29 QUERY_STRING => $request->uri->query || '',
30 SCRIPT_NAME => $request->uri->path || '/',
31 SERVER_NAME => $request->uri->host,
32 SERVER_PORT => $request->uri->port,
33 SERVER_PROTOCOL => $request->protocol || 'HTTP/1.1',
34 SERVER_SOFTWARE => __PACKAGE__ . "/" . $VERSION,
35 REMOTE_ADDR => '127.0.0.1',
36 REMOTE_HOST => 'localhost',
37 REMOTE_PORT => int( rand(64000) + 1000 ), # not in RFC 3875
38 REQUEST_URI => $request->uri->path || '/', # not in RFC 3875
39 REQUEST_METHOD => $request->method,
43 foreach my $field ( $request->headers->header_field_names ) {
47 $key = 'HTTP_' . $key unless $field =~ /^Content-(Length|Type)$/;
49 unless ( exists $self->{enviroment}->{$key} ) {
50 $self->{enviroment}->{$key} = $request->headers->header($field);
54 return $class->SUPER::new($self);
60 open( my $stdin, '>&', STDIN->fileno )
61 or croak("Can't dup stdin: $!");
63 open( my $stdout, '>&', STDOUT->fileno )
64 or croak("Can't dup stdout: $!");
66 open( my $stderr, '>&', STDERR->fileno )
67 or croak("Can't dup stderr: $!");
76 if ( $self->request->content_length ) {
78 $self->stdin->write( $self->request->content )
79 or croak("Can't write content: $!");
81 seek( $self->stdin, 0, 0 )
82 or croak("Can't seek stdin: $!");
85 %ENV = %{ $self->enviroment };
87 open( STDIN, '<&=', $self->stdin->fileno )
88 or croak("Can't open stdin: $!");
90 open( STDOUT, '>&=', $self->stdout->fileno )
91 or croak("Can't open stdout: $!");
93 open( STDERR, '>&=', $self->stderr->fileno )
94 or croak("Can't open stderr: $!");
102 %ENV = %{ $self->{restore}->{enviroment} };
104 open( STDIN, '>&', $self->{restore}->{stdin} )
105 or croak("Can't restore stdin: $!");
107 open( STDOUT, '>&', $self->{restore}->{stdout} )
108 or croak("Can't restore stdout: $!");
110 open( STDERR, '>&', $self->{restore}->{stderr} )
111 or croak("Can't restore stderr: $!");
118 $self->restore unless $self->{restored};
127 HTTP::Request::AsCGI - Setup a CGI enviroment from a HTTP::Request
133 use HTTP::Request::AsCGI;
135 my $request = HTTP::Request->new( GET => 'http://www.host.com/' );
139 my $c = HTTP::Request::AsCGI->new($request)->setup;
143 $q->start_html('Hello World'),
144 $q->h1('Hello World'),
147 $stdout = $c->stdout;
149 # enviroment and descriptors will automatically be restored when $c is destructed.
152 $stdout->seek( 0, 0 );
154 while ( my $line = $stdout->getline ) {
186 Christian Hansen, C<ch@ngmedia.com>
190 This library is free software. You can redistribute it and/or modify
191 it under the same terms as perl itself.