Skip to content

Instantly share code, notes, and snippets.

@zakame
Last active April 2, 2018 10:00
Show Gist options
  • Save zakame/dec66f7350b8cbf5c8b982be0b8adff7 to your computer and use it in GitHub Desktop.
Save zakame/dec66f7350b8cbf5c8b982be0b8adff7 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
use Mojo::Base -strict;
use Mojo::JSON qw(encode_json);
use Mojo::UserAgent;
use Mojo::Util qw(md5_sum steady_time);
my $ua = Mojo::UserAgent->new->tap( sub {
shift->transactor->add_generator(
jsonrpc => sub {
my ( $t, $tx, $method, $params ) = @_;
my $id = md5_sum 'j' . steady_time . rand;
my $obj = { id => $id, jsonrpc => '2.0', method => $method };
$obj->{params} = $params if $params;
$tx->req->body( encode_json($obj) )
->headers->content_type('application/json-rpc');
}
);
} );
# get a key from https://api.random.org/json-rpc/1/
my $key = $ENV{RANDOMORG_API_KEY} || 'my-random-org-beta-key';
my $tx = $ua->post(
'https://api.random.org/json-rpc/1/invoke',
jsonrpc => generateIntegers => {
apiKey => $key,
max => 100,
min => 1,
n => 5
}
);
if ( $tx->success ) {
if ( my $error = $tx->res->json->{error} ) {
die "RPC failed: ", $error->{message}, "\n";
}
say "Your lucky numbers for today are: ",
join ' ' => @{ $tx->res->json->{result}{random}{data} };
}
else {
my $err = $tx->error;
die "Connection to RPC failed: ", $err->{message}, "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment