Champlain
view release on metacpan or search on metacpan
examples/capitals.pl view on Meta::CPAN
$self->http($http);
}
sub http {
my $self = shift;
if (@_) {
$self->{http} = $_[0];
}
return $self->{http};
}
sub to_uri {
my ($uri) = @_;
return $uri if ref($uri) && $uri->isa('URI');
return URI->new($uri);
}
#
# Performs an HTTP GET request asynchronously.
#
sub do_get {
my $self = shift;
my ($uri, $callback, $data) = @_;
$uri = to_uri($uri);
# Note that this is not asynchronous!
$self->http->write_request(GET => $uri->path_query);
my ($code, $message, %headers);
my $content = "";
Glib::IO->add_watch($self->http->fileno, ['in'], sub {
my (undef, $condition) = @_;
# Read the headers
if (!$code) {
eval {
($code, $message, %headers) = $self->http->read_response_headers();
};
if (my $error = $@) {
# The server closed the socket reconnect and resume the HTTP GET
$self->connect();
$self->do_get($uri, $callback, $data);
# We abort this I/O watch since another download will be started
return FALSE;
}
# We return and continue when the server will have more data
return TRUE;
}
# Read the content
my $line;
my $n = $self->http->read_entity_body($line, 1024);
$content .= $line;
if ($self->http->keep_alive) {
# In the case where the HTTP request has keep-alive we need to see if the
# content has all arrived as read_entity_body() will not tell when the end
# of the content has been reached.
return TRUE unless length($content) == $headers{'Content-Length'};
}
elsif ($n) {
# There's still data to read
return TRUE;
}
# End of the document
my $response = HTTP::Response->new($code, $message, [%headers], $content);
$callback->($self, $uri, $response, $data);
return FALSE;
});
}
# A true value
1;
( run in 1.949 second using v1.01-cache-2.11-cpan-39bf76dae61 )