簡介
use Mojo::Transaction::HTTP;
# Client
my $tx = Mojo::Transaction::HTTP->new;
$tx->req->method('GET');
$tx->req->url->parse('http://example.com');
$tx->req->headers->accept('application/json');
say $tx->res->code;
say $tx->res->headers->content_type;
say $tx->res->body;
say $tx->remote_address;
# Server
my $tx = Mojo::Transaction::HTTP->new;
say $tx->req->method;
say $tx->req->url->to_abs;
say $tx->req->headers->accept;
say $tx->remote_address;
$tx->res->code(200);
$tx->res->headers->content_type('text/plain');
$tx->res->body('Hello World!');
Mojo :: Transaction :: HTTP是基于RFC 7230和RFC 7231的 HTTP事務(wù)的容器。
事件
Mojo::Transaction::HTTP繼承了Mojo::Transaction中的所有事件,并實現(xiàn)了以下事件。
request
$tx->on(request => sub {
my $tx = shift;
...
});
當(dāng)一個請求準(zhǔn)備好需要發(fā)起時觸發(fā)此事件酣胀。
$tx->on(request => sub {
my $tx = shift;
$tx->res->headers->header('X-Bender' => 'Bite my shiny metal ass!');
});
resume
$tx->on(resume => sub {
my $tx = shift;
...
});
當(dāng)事務(wù)重新啟動時觸發(fā)怠李。
unexpected
$tx->on(unexpected => sub {
my ($tx, $res) = @_;
...
});
當(dāng)有 1xx 狀態(tài)的響應(yīng)返回,且被忽略的情況觸發(fā)此事件袱吆。
$tx->on(unexpected => sub {
my $tx = shift;
$tx->res->on(finish => sub { say 'Follow-up response is finished.' });
});
屬性
Mojo::Transaction::HTTP 繼承了Mojo::Tranaction中的所有屬性相恃,并實現(xiàn)了previous屬性辜纲。
my $previous = $tx->previous;
$tx = $tx->previous(Mojo::Transaction::HTTP->new);
返回或設(shè)置觸發(fā)當(dāng)前事務(wù)的那個事務(wù),通常是一個Mojo::Transaction::HTTP對象豆茫。
方法
Mojo::Transaction::HTTP繼承了Mojo::Transaction中的所有方法侨歉,并實現(xiàn)了以下方法。
client_read
$tx->client_read($bytes);
作為客戶端讀取數(shù)據(jù)揩魂,用于實現(xiàn)諸如Mojo::UserAgent之類的用戶代理。
client_write
my $bytes = $tx->client_write;
作為客戶端寫數(shù)據(jù)炮温,用于實現(xiàn)諸如Mojo::UserAgent之類的用戶代理火脉。
is_empty
my $bool = $tx->is_empty;
對事務(wù)進行檢查,如果是滿足條件(HEAD 請求柒啤,返回的狀態(tài)是1xx倦挂、204、304)則返回true担巩,否則返回false方援。
keep_alive
my $bool = $tx->keep_alive;
檢查連接是否可以 kept alive。
redirects
my $redirects = $tx->redirects;
返回一個數(shù)組的引用涛癌,里面包含了所有重定向到當(dāng)前事務(wù)之前的事務(wù)犯戏。
# Paths of all previous requests
say $_->req->url->path for @{$tx->redirects};
resume
$tx = $tx->resume;
恢復(fù)事務(wù)。
server_read
$tx->server_read($bytes);
作為服務(wù)器讀取數(shù)據(jù)拳话,用于實現(xiàn)Web服務(wù)器先匪,如Mojo::Server::Daemon。
server_write
my $bytes = $tx->server_write;
作為服務(wù)器寫數(shù)據(jù)弃衍,用于實現(xiàn)Web服務(wù)器呀非,如Mojo::Server::Daemon。