| 1 |
package apiclient; |
|---|
| 2 |
|
|---|
| 3 |
use WWW::Curl::Easy; |
|---|
| 4 |
|
|---|
| 5 |
sub new { |
|---|
| 6 |
my $class = shift; |
|---|
| 7 |
my $host = shift; |
|---|
| 8 |
my $port = shift; |
|---|
| 9 |
my $curl = WWW::Curl::Easy->new(); |
|---|
| 10 |
$curl->setopt(CURLOPT_SSL_VERIFYPEER, 0); |
|---|
| 11 |
$curl->setopt(CURLOPT_CAINFO, '../test-ca.crt'); |
|---|
| 12 |
$curl->setopt(CURLOPT_SSLKEY, '../client.key'); |
|---|
| 13 |
$curl->setopt(CURLOPT_SSLCERT, '../client.crt'); |
|---|
| 14 |
$curl->setopt(CURLOPT_TIMEOUT, 35); |
|---|
| 15 |
return bless { curl => $curl, host => $host, port => $port }, $class; |
|---|
| 16 |
} |
|---|
| 17 |
sub do { |
|---|
| 18 |
my $self = shift; |
|---|
| 19 |
my $method = shift; |
|---|
| 20 |
my $uri = shift; |
|---|
| 21 |
if (@_) { |
|---|
| 22 |
my $payload = shift; |
|---|
| 23 |
$self->{curl}->setopt(CURLOPT_UPLOAD, 1); |
|---|
| 24 |
open (my $fh, "<", \$payload); |
|---|
| 25 |
$self->{curl}->setopt(CURLOPT_INFILE, $fh); |
|---|
| 26 |
$self->{curl}->setopt(CURLOPT_INFILESIZE, length($payload)); |
|---|
| 27 |
} |
|---|
| 28 |
$self->{curl}->setopt(CURLOPT_CUSTOMREQUEST, $method); |
|---|
| 29 |
$self->{curl}->setopt(CURLOPT_URL, "https://$self->{host}:$self->{port}$uri"); |
|---|
| 30 |
|
|---|
| 31 |
my $response_body; |
|---|
| 32 |
|
|---|
| 33 |
open (my $fileb, ">", \$response_body); |
|---|
| 34 |
$self->{curl}->setopt(CURLOPT_WRITEDATA, $fileb); |
|---|
| 35 |
|
|---|
| 36 |
my $retcode = $self->{curl}->perform(); |
|---|
| 37 |
my $response_code = $self->{curl}->getinfo(CURLINFO_HTTP_CODE); |
|---|
| 38 |
if ($retcode == 0) { |
|---|
| 39 |
return ($response_code, $response_body); |
|---|
| 40 |
} |
|---|
| 41 |
die $self->{curl}->strerror($retcode); |
|---|
| 42 |
} |
|---|
| 43 |
sub get { shift->do('GET', @_); } |
|---|
| 44 |
sub post { shift->do('POST', @_); } |
|---|
| 45 |
sub put { shift->do('PUT', @_); } |
|---|
| 46 |
sub delete { shift->do('DELETE', @_); } |
|---|
| 47 |
|
|---|
| 48 |
1; |
|---|