簡介
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中的所有事件,并實(shí)現(xiàn)了以下事件。
request
$tx->on(request => sub {
my $tx = shift;
...
});
當(dāng)一個(gè)請(qǐng)求準(zhǔn)備好需要發(fā)起時(shí)觸發(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ù)重新啟動(dòng)時(shí)觸發(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中的所有屬性,并實(shí)現(xiàn)了previous屬性。
my $previous = $tx->previous;
$tx = $tx->previous(Mojo::Transaction::HTTP->new);
返回或設(shè)置觸發(fā)當(dāng)前事務(wù)的那個(gè)事務(wù),通常是一個(gè)Mojo::Transaction::HTTP對(duì)象。
方法
Mojo::Transaction::HTTP繼承了Mojo::Transaction中的所有方法,并實(shí)現(xiàn)了以下方法。
client_read
$tx->client_read($bytes);
作為客戶端讀取數(shù)據(jù),用于實(shí)現(xiàn)諸如Mojo::UserAgent之類的用戶代理。
client_write
my $bytes = $tx->client_write;
作為客戶端寫數(shù)據(jù),用于實(shí)現(xiàn)諸如Mojo::UserAgent之類的用戶代理。
is_empty
my $bool = $tx->is_empty;
對(duì)事務(wù)進(jìn)行檢查,如果是滿足條件(HEAD 請(qǐng)求,返回的狀態(tài)是1xx、204、304)則返回true,否則返回false。
keep_alive
my $bool = $tx->keep_alive;
檢查連接是否可以 kept alive。
redirects
my $redirects = $tx->redirects;
返回一個(gè)數(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ù),用于實(shí)現(xiàn)Web服務(wù)器,如Mojo::Server::Daemon。
server_write
my $bytes = $tx->server_write;
作為服務(wù)器寫數(shù)據(jù),用于實(shí)現(xiàn)Web服務(wù)器,如Mojo::Server::Daemon。