我怎么能写在Perl一个简单的HTTP代理?(How can I write a simple HT

2019-10-21 09:40发布

我不想因为我想倾倒了一对夫妇的请求使用HTTP代理::包。 我的一个班轮看起来是这样,但休息对试图通过标题中:

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);
    }
  }
}#'

所以我不能只是传递的要求,因为我需要改变主机,我不能只传递似乎头...所以我应该怎么做,以保持短。

所以,任何人都可以做出更好的单行?

Answer 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->new耶...所以它的工作原理,它的速度慢一点点。 不过没关系



Answer 2:

为什么你如此努力写一行程序? 是有一些原因,你不能保存程序的文件? 我只是好奇,是什么情况。



文章来源: How can I write a simple HTTP proxy in Perl?