From f577d50acdb2efb5005c2bfa4c176934db2ffbd3 Mon Sep 17 00:00:00 2001 From: JT Smith Date: Sun, 16 Jan 2011 09:07:38 -0600 Subject: [PATCH] added JSON RPC Client --- lib/Lacuna/JRC.pm | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 lib/Lacuna/JRC.pm diff --git a/lib/Lacuna/JRC.pm b/lib/Lacuna/JRC.pm new file mode 100644 index 00000000..59e26b69 --- /dev/null +++ b/lib/Lacuna/JRC.pm @@ -0,0 +1,45 @@ +package Lacuna::JRC; + +use Moose; +use utf8; +no warnings qw(uninitialized); +use LWP::UserAgent; +use JSON qw(to_json from_json); +use Time::HiRes qw(usleep); + +has ua => ( + is => 'ro', + lazy => 1, + default => sub { my $ua = LWP::UserAgent->new; $ua->timeout(30); return $ua; }, +); + + +sub post { + my ($self, $url, $method, $params) = @_; + my $content = { + jsonrpc => '2.0', + id => 1, + method => $method, + params => $params, + }; + my $response; + foreach my $retry (1..5) { + $response = $self->ua->post(Lacuna->config->get('server_url').$url, + Content_Type => 'application/json', + Content => to_json($content), + Accept => 'application/json', + ); + last if $response->is_success; + usleep((4 ** $retry) * 100_000); + } + confess [$response->code, 'Could not connect to JSON RPC server.'] unless $response->is_success; + my $result = from_json($response->content); + if (exists $result->{error}) { + confess [$result->{error}{code}, $result->{error}{message}, $result->{error}{data}]; + } + return $result->{result}; +} + + +no Moose; +__PACKAGE__->meta->make_immutable; -- 2.51.2