1 package HTTP
::AnyUA
::Backend
::Mojo
::UserAgent
;
2 # ABSTRACT: A unified programming interface for Mojo::UserAgent
6 This module adds support for the HTTP client L<Mojo::UserAgent> to be used with the unified
7 programming interface provided by L<HTTP::AnyUA>.
12 * The C<url> field in the response has the auth portion (if any) removed from the URL.
17 * L<HTTP::AnyUA::Backend>
24 our $VERSION = '9999.999'; # VERSION
26 use parent
'HTTP::AnyUA::Backend';
32 sub response_is_future
{ 1 }
36 my ($method, $url, $args) = @_;
38 my $future = Future-
>new;
40 my $tx = $self->_munge_request(@_);
42 $self->ua->start($tx => sub {
46 my $resp = $self->_munge_response($tx, $args->{data_callback
});
48 if ($resp->{success
}) {
66 my $headers = $args->{headers
} || {};
67 my $content = $args->{content
};
73 for my $header (keys %$headers) {
74 if (lc($header) eq 'content-length') {
75 $content_length = $headers->{$header};
80 # if we don't know the length we have to just read it all in
81 $content = HTTP
::AnyUA
::Util
::coderef_content_to_string
($content) if !$content_length;
83 push @content, $content if ref($content) ne 'CODE';
86 my $tx = $self->ua->build_tx($method => $url => $headers => @content);
88 if (ref($content) eq 'CODE') {
89 $tx->req->headers->content_length($content_length);
94 my $chunk = $content->() || '';
95 undef $drain if !$chunk;
96 $body->write($chunk, $drain);
98 $tx->req->content->$drain;
101 if (my $data_cb = $args->{data_callback
}) {
102 # stream the response
104 Scalar
::Util
::weaken
($tx_copy);
105 $tx->res->content->unsubscribe('read')->on(read => sub {
106 my ($content, $bytes) = @_;
107 my $resp = $self->_munge_response($tx_copy, undef);
108 $data_cb->($bytes, $resp);
115 sub _munge_response
{
122 success
=> !!$tx->res->is_success,
123 url
=> $tx->req->url->to_string,
124 status
=> $tx->res->code,
125 reason
=> $tx->res->message,
129 # lowercase header keys
130 my $headers = $tx->res->headers->to_hash;
131 for my $header (keys %$headers) {
132 $resp->{headers
}{lc($header)} = delete $headers->{$header};
135 my $version = $tx->res->version;
136 $resp->{protocol
} = "HTTP/$version" if $version;
139 for my $redirect (@{$tx->redirects}) {
140 push @{$resp->{redirects
} ||= []}, $self->_munge_response($redirect, undef, 1);
144 my $err = $tx->error;
145 if ($err && !$err->{code
}) {
146 return HTTP
::AnyUA
::Util
::internal_exception
($err->{message
}, $resp);
149 my $body = $tx->res->body;
150 $resp->{content
} = $body if $body && !$data_cb;