AnyEvent-HTTP-ScopedClient
view release on metacpan or search on metacpan
lib/AnyEvent/HTTP/ScopedClient.pm view on Meta::CPAN
package AnyEvent::HTTP::ScopedClient;
{
$AnyEvent::HTTP::ScopedClient::VERSION = '0.0.5';
}
# ABSTRACT: L<AnyEvent> based L<https://github.com/technoweenie/node-scoped-http-client>
use Moose;
use namespace::autoclean;
use URI;
use Try::Tiny;
use MIME::Base64;
use HTTP::Request;
use Encode qw/encode_utf8/;
use AnyEvent::HTTP;
use URI::QueryParam;
use URI::Escape;
has 'options' => (
is => 'ro',
isa => 'HashRef',
);
sub request {
my ( $self, $method, $reqBody, $callback ) = @_;
if ( 'CODE' eq ref($reqBody) ) {
$callback = $reqBody;
undef $reqBody;
}
my %options = %{ $self->options };
try {
my %headers = %{ $options{headers} };
if ( 'HASH' eq ref($reqBody) ) {
my @pair;
# push @pair, "$_=$reqBody->{$_}" for ( keys %$reqBody );
push @pair, "$_=" . uri_escape_utf8( $reqBody->{$_} )
for ( keys %$reqBody );
$reqBody = join( '&', @pair );
}
my $sendingData
= ( $method =~ m/^P/ && $reqBody && length $reqBody > 0 ) ? 1 : 0;
$headers{'Content-Length'} = length $reqBody if $sendingData;
$headers{'Content-Type'} = 'application/x-www-form-urlencoded'
if ( $sendingData && !$headers{'Content-Type'} );
if ( $options{auth} ) {
$headers{Authorization}
= 'Basic ' . encode_base64( $options{auth}, '' );
}
if ( $ENV{DEBUG} ) {
print "$method " . $self->options->{url} . "\n";
while ( my ( $k, $v ) = each %headers ) {
print "$k: $v\n";
}
print "\n";
print "$reqBody\n" if $sendingData;
}
http_request(
$method,
$options{url},
headers => \%headers,
body => $sendingData ? encode_utf8($reqBody) : undef,
$callback
);
}
catch {
$callback->($_) if $callback;
};
return $self;
}
sub fullPath {
my ( $self, $p ) = @_;
}
sub scope {
my ( $self, $url, $options, $callback ) = @_;
}
sub join {
my ( $self, $suffix ) = @_;
}
sub path {
my ( $self, $p ) = @_;
}
sub query {
my ( $self, $key, $value ) = @_;
if ( 'HASH' eq ref $key ) {
while ( my ( $k, $v ) = each %$key ) {
$self->options->{url}->query_param( $k => $v );
}
}
else {
$self->options->{url}->query_param( $key => $value );
}
return $self;
}
sub host {
my ( $self, $h ) = @_;
}
sub protocol {
my ( $self, $p ) = @_;
}
sub auth {
my ( $self, $user, $pass ) = @_;
if ( !$user ) {
$self->options->{auth} = undef;
}
elsif ( !$pass && $user =~ m/:/ ) {
$self->options->{auth} = $user;
}
else {
$self->options->{auth} = "$user:$pass";
}
return $self;
( run in 0.893 second using v1.01-cache-2.11-cpan-39bf76dae61 )