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::UserAgent 是一个全功能的非阻塞 I/O HTTP 和 WebSocket 的用户代理,...
    JSON_NULL阅读 1,198评论 0 0
  • 简介 Mojo::Transaction 是一个用于事务的抽象基类,它的子类有:Mojo::Transaction...
    JSON_NULL阅读 647评论 2 2
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,010评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,780评论 18 399
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,974评论 6 342