WWW-Hetzner
view release on metacpan or search on metacpan
lib/WWW/Hetzner/Role/HTTP.pm view on Meta::CPAN
return $self->_request('DELETE', $path);
}
sub _set_auth {
my ($self, $headers) = @_;
$headers->{Authorization} = 'Bearer ' . $self->token;
}
sub _content_type { 'application/json' }
sub _encode_body {
my ($self, $body) = @_;
return encode_json($body);
}
sub _build_request {
my ($self, $method, $path, %opts) = @_;
my $url = $self->base_url . $path;
# Add query params for GET
if ($method eq 'GET' && $opts{params}) {
my @pairs;
for my $key (keys %{$opts{params}}) {
my $value = $opts{params}{$key};
my @values = ref $value eq 'ARRAY' ? @$value : ($value);
for my $value (@values) {
next unless defined $value;
push @pairs, URI::Escape::uri_escape_utf8($key) . '=' .
URI::Escape::uri_escape_utf8($value);
}
}
$url .= '?' . join('&', @pairs) if @pairs;
}
$log->debug("$method $url");
my %headers;
$self->_set_auth(\%headers);
$headers{'Content-Type'} = $self->_content_type;
my %req_args = (
method => $method,
url => $url,
headers => \%headers,
);
if ($opts{body}) {
$req_args{content} = $self->_encode_body($opts{body});
$log->debugf("Body: %s", $self->_encode_body($self->_mask_body($opts{body})));
}
return WWW::Hetzner::HTTPRequest->new(%req_args);
}
my @SECRET_KEYS = qw(password private_key user_data);
sub _mask_body {
my ($self, $body) = @_;
return $body unless ref $body eq 'HASH';
my %copy = %$body;
for my $key (@SECRET_KEYS) {
$copy{$key} = '********' if defined $copy{$key};
}
return \%copy;
}
sub _parse_response {
my ($self, $response, $method, $path) = @_;
$log->debugf("Response: %s", $response->status);
my $data;
if ($response->content && $response->content =~ /^\s*[\{\[]/) {
$data = decode_json($response->content);
}
unless ($response->status >= 200 && $response->status < 300) {
my $error = (ref $data eq 'HASH' && ref $data->{error} eq 'HASH'
? $data->{error}{message} : undef);
unless (defined $error) {
$error = $response->status;
my $text = $response->content // '';
$text =~ s/<[^>]*>/ /g;
$text =~ s/\s+/ /g;
$text =~ s/^ //; $text =~ s/ $//;
$text = substr($text, 0, 200) . '...' if length $text > 200;
$error .= " $text" if length $text;
}
$log->errorf("API error: %s", $error);
croak "Hetzner API error: $error";
}
$log->infof("%s %s -> %s", $method, $path, $response->status);
return $data;
}
sub _request {
my ($self, $method, $path, %opts) = @_;
croak "No API token configured" unless $self->token;
my $req = $self->_build_request($method, $path, %opts);
my $response = $self->io->call($req);
return $self->_parse_response($response, $method, $path);
}
1;
__END__
=pod
=encoding UTF-8
=head1 NAME
WWW::Hetzner::Role::HTTP - HTTP client role for Hetzner API clients
=head1 VERSION
version 0.102
=head1 SYNOPSIS
package WWW::Hetzner::Cloud;
use Moo;
has token => ( is => 'ro' );
has base_url => ( is => 'ro', default => 'https://api.hetzner.cloud/v1' );
with 'WWW::Hetzner::Role::HTTP';
=head1 DESCRIPTION
This role provides HTTP methods (GET, POST, PUT, DELETE) for Hetzner API
clients. It handles client-specific request-body encoding, JSON response
decoding, authentication, and error handling. Request bodies use JSON by
default; L<WWW::Hetzner::Robot> uses
C<application/x-www-form-urlencoded> instead.
A client with a different body format overrides L</_content_type> and
L</_encode_body>.
HTTP transport is delegated to a pluggable L<WWW::Hetzner::Role::IO> backend
(default: L<WWW::Hetzner::LWPIO>), making it possible to use async HTTP
clients.
Uses L<Log::Any> for logging HTTP requests and responses. The debug log of a
request body masks the top-level keys C<password>, C<private_key> and
C<user_data>; the request itself is sent unchanged.
Non-2xx responses croak with C<Hetzner API error: ...>: the API's error
message if the body carries one, otherwise the status code followed by the
(tag-stripped, truncated) body text.
=head1 REQUIRED ATTRIBUTES
Classes consuming this role must provide:
=over 4
=item * C<token> - API authentication token
=item * C<base_url> - Base URL for the API
=back
=head2 io
Pluggable HTTP backend implementing L<WWW::Hetzner::Role::IO>.
Defaults to L<WWW::Hetzner::LWPIO>.
# Use a custom IO backend
my $cloud = WWW::Hetzner::Cloud->new(
token => $token,
io => My::AsyncIO->new,
);
=head2 sleeper
Injectable sleep function, C<sub ($seconds) { ... }>, called with the poll
interval. Defaults to C<sleep>. Declared C<rw> so a test can swap in a
non-blocking counting closure after construction, without rebuilding the
client. Used by L<WWW::Hetzner::Action/wait> between polls, via the
client the action holds a reference to.
=head2 get
my $data = $self->get('/path', params => { key => 'value' });
Perform a GET request.
=head2 post
my $data = $self->post('/path', { key => 'value' });
Perform a POST request whose body is encoded by L</_encode_body> with the
media type from L</_content_type>. JSON is the default; the Robot client uses
form encoding.
=head2 put
my $data = $self->put('/path', { key => 'value' });
Perform a PUT request whose body is encoded by L</_encode_body> with the
media type from L</_content_type>. JSON is the default; the Robot client uses
form encoding.
=head2 delete
( run in 0.846 second using v1.01-cache-2.11-cpan-8379b9b8ec2 )