1

Basically, my question is similar to How do I access HTTP request headers in HTTP::Server::Simple::CGI?

The answer was to use parse_headers(), but there was no example how to use it properly. I tried to use parse_headers() but I'm not getting any result, it just stops at parse_headers() like the program is stucked. I couldn't add a comment on the question above since I don't have enough rep to do so, so I created this new question.

Below is my sample code, basically the example code from CPAN just added the parse_headers:

#!/usr/bin/perl
{
package MyWebServer;

use HTTP::Server::Simple::CGI;
our @ISA = qw(HTTP::Server::Simple::CGI);
use Data::Dumper;

my %dispatch = (
    '/hello.cgi' => \&resp_hello,
    # ...
);

sub handle_request {
    my $self = shift;
    my $cgi  = shift;

    my $path = $cgi->path_info();
    my $handler = $dispatch{$path};

    my $header = $self->parse_headers();
    open F,qq{>>~/MyWebServer.log};
    my $dump = Data::Dumper->Dump([$header], [qw($header)]);
    print F $dump;
    close F;

    if (ref($handler) eq "CODE") {
        print "HTTP/1.0 200 OK\r\n";
        $handler->($cgi);

    } else {
        print "HTTP/1.0 404 Not found\r\n";
        print $cgi->header,
              $cgi->start_html('Not found'),
              $cgi->h1('Not found'),
              $cgi->end_html;
    }
}

sub resp_hello {
    my $cgi  = shift;   # CGI.pm object
    return if !ref $cgi;

    my $who = $cgi->param('name');

    print $cgi->header,
          $cgi->start_html("Hello"),
          $cgi->h1("Hello $who!"),
          $cgi->end_html;
}

} # end of package MyWebServer

# start the server on port 8080
my $pid = MyWebServer->new(8080)->background();
print "Use 'kill $pid' to stop server.\n";

Only added this part:

    my $header = $self->parse_headers();
    open F,qq{>>~/MyWebServer.log};
    my $dump = Data::Dumper->Dump([$header], [qw($header)]);
    print F $dump;
    close F;

My objective is to get all the headers and dump it into a file.

1 Answer 1

2

Add

sub headers {
    my( $self, $headers ) = @_;
    if( $headers ){
        $self->{__last_headers} = { @$headers };
    }
    return $self->{__last_headers};
}

Then inside handle_request use my $header = $self->headers();

FWIW, i'm curious why you're using HTTP::Server::Simple::CGI instead of Mojolicious or Dancer or even HTTP::Server::Simple::PSGI. https://metacpan.org/pod/PSGI is portability.

Sign up to request clarification or add additional context in comments.

1 Comment

It worked! Thanks a lot! Also, I'll try those you have suggested, first time seeing them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.