Mojo::Transaction::HTTP

简介

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事务的容器。

事件

Mojo::Transaction::HTTP继承了Mojo::Transaction中的所有事件,并实现了以下事件。

request

$tx->on(request => sub {
  my $tx = shift;
  ...
});

当一个请求准备好需要发起时触发此事件。

$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;
  ...
});

当事务重新启动时触发。

unexpected

$tx->on(unexpected => sub {
  my ($tx, $res) = @_;
  ...
});

当有 1xx 状态的响应返回,且被忽略的情况触发此事件。

$tx->on(unexpected => sub {
  my $tx = shift;
  $tx->res->on(finish => sub { say 'Follow-up response is finished.' });
});

属性

Mojo::Transaction::HTTP 继承了Mojo::Tranaction中的所有属性,并实现了previous属性。

my $previous = $tx->previous;
$tx          = $tx->previous(Mojo::Transaction::HTTP->new);

返回或设置触发当前事务的那个事务,通常是一个Mojo::Transaction::HTTP对象。

方法

Mojo::Transaction::HTTP继承了Mojo::Transaction中的所有方法,并实现了以下方法。

client_read

$tx->client_read($bytes);

作为客户端读取数据,用于实现诸如Mojo::UserAgent之类的用户代理。

client_write

my $bytes = $tx->client_write;

作为客户端写数据,用于实现诸如Mojo::UserAgent之类的用户代理。

is_empty

my $bool = $tx->is_empty;

对事务进行检查,如果是满足条件(HEAD 请求,返回的状态是1xx、204、304)则返回true,否则返回false。

keep_alive

my $bool = $tx->keep_alive;

检查连接是否可以 kept alive。

redirects

my $redirects = $tx->redirects;

返回一个数组的引用,里面包含了所有重定向到当前事务之前的事务。

# Paths of all previous requests
say $_->req->url->path for @{$tx->redirects};

resume

$tx = $tx->resume;

恢复事务。

server_read

$tx->server_read($bytes);

作为服务器读取数据,用于实现Web服务器,如Mojo::Server::Daemon。

server_write

my $bytes = $tx->server_write;

作为服务器写数据,用于实现Web服务器,如Mojo::Server::Daemon。

你可能感兴趣的:(Mojo::Transaction::HTTP)