Skip to content

Instantly share code, notes, and snippets.

@scottchiefbaker
Last active November 13, 2015 00:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottchiefbaker/809378ab4c590d439bd2 to your computer and use it in GitHub Desktop.
Save scottchiefbaker/809378ab4c590d439bd2 to your computer and use it in GitHub Desktop.
package JSON::RPC::Client::Lite;
use HTTP::Tiny;
use vars '$AUTOLOAD';
use JSON;
#use Data::Dump::Color;
sub new {
my ($class,$url,$opts) = @_;
my $version = 0.1;
my $attrs = {
'agent' => "JSON::RPC::Client::Lite version $version",
'timeout' => 3,
};
my $self = {
"version" => $version,
"api_url" => $url,
"opts" => $opts,
"http" => HTTP::Tiny->new(%$attrs),
"breadcrumbs" => [],
};
bless $self, $class;
return $self;
}
sub _call {
my ($self,$method,@params) = @_;
my $url = $self->{api_url};
if (!$url || !$method) {
return undef;
}
if (!@params) {
@params = undef;
}
my $json = $self->create_request($method,@params);
my $debug = $self->{opts}->{debug};
if ($debug) {
print "Server URL: $url\n";
print "Sending : " . $json . "\n";
}
my $opts = {
content => $json,
headers => { 'Content-Type' => 'application/json;charset=UTF-8' },
};
my $resp = $self->{http}->post($url,$opts);
my $status = $resp->{status};
my $json_resp = $resp->{content};
if ($debug) {
print "Received : " . $json_resp . "\n\n";
}
if ($status != 200) {
return undef;
}
my $ret = decode_json($json_resp);
return $ret->{result};
}
sub create_request {
my ($self,$method,@params) = @_;
my $hash = {
"method" => $method,
"version" => 1.1,
"id" => 1,
"params" => \@params,
};
my $json = encode_json($hash);
return $json;
}
sub AUTOLOAD {
my ($self,@params) = @_;
my $func = $AUTOLOAD;
# Remove the class name, we just want the function that was called
my $str = __PACKAGE__ . "::";
$func =~ s/$str//;
# Store the method name in the breadcrumb trail
push(@{$self->{breadcrumbs}},$func);
# If there are params it's the final function call not an intermediate
# Note: this requires that a method be called with SOME params
if (@params) {
my $method = join(".",@{$self->{breadcrumbs}});
my $ret = $self->_call($method,@params);
$self->{breadcrumbs} = []; # Reset the trail
return $ret;
}
return $self;
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment