【问题标题】:How can I write a simple HTTP proxy in Perl?如何在 Perl 中编写一个简单的 HTTP 代理?
【发布时间】:2010-09-21 09:12:50
【问题描述】:

我不想使用 HTTP::Proxy 包,因为我想转储几个请求。我的一个班轮看起来像这样,但在尝试传递标题时中断:

perl -MData::Dumper -MHTTP::Daemon -MHTTP::Status -MLWP::UserAgent -e 'my $ua = LWP::UserAgent->new;my $d=new HTTP::Daemon(LocalPort=>1999);print "Please contact me at: <", $d->url, ">\n";while (my $c = $d->accept) {while (my $r = $c->get_request) {if ($r->method eq 'GET' and $r->url->path eq "/uploader") {$c->send_response("whatever.");print Dumper($r);}else{$response=$ua->request($r->method,"http://localhost:1996".$r->uri,$r->headers,$r->content);$c->send_response($response);}}}'

格式化,即:

#perl -e '
use Data::Dumper;
use HTTP::Daemon;
use HTTP::Status;
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $d=new HTTP::Daemon(LocalPort=>1999);
print "Please contact me at: < ", $d->url, " >\n";
while (my $c = $d->accept) {
  while (my $r = $c->get_request) {
    if ($r->method eq 'GET' and $r->url->path eq "/uploaded") {
      $c->send_response("whatever.");
      print Dumper($r);
    } else { 
      $response = $ua -> request(
        $r->method, 
        "http://localhost:1996" . $r->uri, 
        $r->headers, 
        $r->content);
      $c->send_response($response);
    }
  }
}#'

所以我不能只传递请求,因为我需要更改主机,而且我不能只传递标头似乎......所以我应该怎么做才能保持简短。

那么任何人都可以使它成为更好的单线吗?

【问题讨论】:

    标签: perl http proxy daemon


    【解决方案1】:

    哎呀,我用这个解决了它:

    #perl -e '
    use Data::Dumper;
    use HTTP::Daemon;
    use HTTP::Status;
    use LWP::UserAgent;
    my $ua = LWP::UserAgent->new;
    my $d=new HTTP::Daemon(LocalPort=>1999);
    print "Please contact me at: < ", $d->url, " >\n";
    while (my $c = $d->accept) {
      while (my $r = $c->get_request) {
        if ($r->method eq "GET" and $r->url->path eq "/uploaded") {
          $c->send_response("whatever.");
          print Dumper($r);
        } else { 
          $response = $ua -> request( HTTP::Request->new(
            $r->method, 
            "http://localhost:1996" . $r->uri, 
            $r->headers, 
            $r->content));
          $c->send_response($response);
        }
      }
    }#'
    

    注意HTTP::Request-&gt;new 是的...所以它起作用了,它有点慢。不过没关系

    【讨论】:

    • 您可能不想在 GET 周围使用单引号。它在这种情况下有效,但不是因为您认为它有效的原因(尝试打开严格模式以了解我的意思)。
    • 我不知道为什么不使用单引号。单引号仅表示“无变量插值”。事实上,我建议将其他字符串更改为单引号以保持一致。
    • 因为他也在命令行上使用它们。幸运的是,这在这种情况下有效,但在其他情况下则不会。
    • 我什至没有注意到 GET 字符串不正确。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2010-11-08
    • 2012-08-24
    • 2013-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多