Acme-Free-API-Geodata-GeoIP

 view release on metacpan or  search on metacpan

lib/Acme/Free/API/Geodata/GeoIP.pm  view on Meta::CPAN

use strict;
use warnings;
use utf8;

our $VERSION = '1.0';

use Data::Dumper;
use WWW::Mechanize;
use JSON::XS qw(decode_json);

sub new($proto, %config) {
    my $class = ref($proto) || $proto;

    my $self = bless \%config, $class;

    my $agent = WWW::Mechanize->new(cookie_jar => {});
    $agent->agent('PerlMonks contest/1 (https://perlmonks.org/?node_id=11161472)');
    $agent->stack_depth(1);
    $self->{agent} = $agent;

    if(!defined($self->{debug})) {
        $self->{debug} = 0;
    }

    return $self;
}

sub lookup($self, $ip) {
    my $url = "http://ip-api.com/json/" . $ip;

    my $content = $self->_fetchURL($url);

    my $ok = 0;
    my $decoded;
    eval {
        $decoded = decode_json($content);
        $ok = 1;
    };

lib/Acme/Free/API/Geodata/GeoIP.pm  view on Meta::CPAN


    #$self->_debuglog(Dumper($decoded));

    return $decoded;
}



# internal helpers
# these are copied from CAVACs vast framework. But we don't want hundreds of dependencies in this example code, only a couple of functions
sub _fetchURL($self, $url) {
    $self->{agent}->get($url);

    if(!$self->{agent}->success()) {
        $self->_debuglog("Network error while fetching URL $url");
        return;
    }

    my $response = $self->{agent}->response();
    if(!defined($response)) {
        $self->_debuglog("Could not get agent response");

lib/Acme/Free/API/Geodata/GeoIP.pm  view on Meta::CPAN

        $self->_debuglog("Could not get response content");
        return;
    }

    #$self->_debuglog(Dumper($content));

    return $content;

}

sub _debuglog($self, $message) {
    if(!$self->{debug}) {
        return;
    }
    print STDERR $message, "\n";
}


1;
__END__



( run in 0.245 second using v1.01-cache-2.11-cpan-65fba6d93b7 )