2008-11-07 49 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

爲什麼你很難寫出一個單線?有沒有理由不能將程序保存在文件中?我只是好奇,情況是什麼。