【问题标题】:Using HTTP::Server::Simple::CGI, how do I get the headers?使用 HTTP::Server::Simple::CGI,如何获取标头?
【发布时间】:2015-06-03 11:40:55
【问题描述】:

基本上,我的问题类似于 How do I access HTTP request headers in HTTP::Server::Simple::CGI?

答案是使用 parse_headers(),但没有示例如何正确使用它。我尝试使用 parse_headers() 但我没有得到任何结果,它只是停在 parse_headers() 就像程序被卡住一样。我无法对上述问题添加评论,因为我没有足够的代表这样做,所以我创建了这个新问题。

下面是我的示例代码,基本上来自 CPAN 的示例代码只是添加了 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";

只添加了这部分:

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

我的目标是获取所有标题并将其转储到文件中。

【问题讨论】:

    标签: perl


    【解决方案1】:

    添加

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

    然后在handle_request里面使用my $header = $self->headers();

    FWIW,我很好奇您为什么使用 HTTP::Server::Simple::CGI 而不是 Mojolicious 或 Dancer 甚至 HTTP::Server::Simple::PSGI。 https://metacpan.org/pod/PSGI 是可移植性的。

    【讨论】:

    • 成功了!非常感谢!另外,我会尝试您建议的那些,第一次看到它们。
    猜你喜欢
    • 2011-03-06
    • 2011-06-24
    • 2020-08-19
    • 2012-10-25
    • 2017-03-24
    • 1970-01-01
    • 2013-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多