2008-11-07 20 views
1

我不想使用HTTP :: Proxy包,因为我想转储出几个请求。我的一个班轮看起来是这样,但休息就试图通过在标题:如何在Perl中编写简单的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); 
    } 
    } 
}#' 

所以我不能只是传递的要求,因为我需要改变主机,我不能只传递头像看起来......所以我应该怎么做才能保持它的简短。

所以任何人都可以使这个更好的单线?

回答

7

胡拍,我这个固定:

#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是啊...所以它的工作原理,它的速度慢一点点。但没关系

+0

你可能不想在GET周围使用单引号。它适用于这种情况,但不是因为你认为它起作用的原因(尝试打开严格模式来查看我的意思)。 – 2008-11-07 22:07:05

+0

为什么不使用单引号,我迷失了方向。单引号仅表示“没有可变插值”。事实上,我建议将其他字符串更改为单引号以保持一致。 – 2008-11-07 23:39:46

2

为什么你很难写出一个单线?有没有理由不能将程序保存在文件中?我只是好奇,情况是什么。