Documentation
¶
Overview ¶
Package httpclient provides an HTTP client for Dynatrace APIs.
It wraps resty with Dynatrace-specific defaults: automatic retry of requests that are safe to resend (see IsRetryable), Bearer/Api-Token auth scheme selection, User-Agent with AI agent detection, gzip, and redacted verbose logging.
Constructor ¶
Use New with functional Option values:
client, err := httpclient.New("https://abc.apps.dynatrace.com",
httpclient.WithToken("dt0c01.xxx"),
httpclient.WithUserAgent("myapp/1.0"),
)
Errors ¶
API errors are returned as *APIError and can be inspected with errors.As. Sentinel errors (ErrUnauthorized, ErrNotFound, etc.) support errors.Is for common status codes.
Index ¶
- Variables
- func CheckRequestPath(reqPath string) error
- func CheckResponse(resp *resty.Response) error
- func ExtractSubdomain(environmentURL string) (string, error)
- func GuardRequestPaths(rc *resty.Client) *resty.Client
- func IsRetryable(r *resty.Response, err error) bool
- func PathSegment(v string) string
- type APIError
- type Client
- type Logger
- type Option
- func WithHTTPProxy(proxyURL string) Option
- func WithLogger(l Logger) Option
- func WithRetry(maxRetries int, waitTime, maxWaitTime time.Duration) Option
- func WithTimeout(d time.Duration) Option
- func WithToken(token string) Option
- func WithTransport(rt http.RoundTripper) Option
- func WithUserAgent(ua string) Option
- type PaginationParams
- type PaginationStyle
Constants ¶
This section is empty.
Variables ¶
var ( ErrBadRequest = errors.New("bad request") ErrForbidden = errors.New("forbidden") ErrNotFound = errors.New("not found") ErrConflict = errors.New("conflict") ErrRateLimited = errors.New("rate limited") ErrServerError = errors.New("server error") )
Sentinel errors for common HTTP status codes. Use errors.Is to check for these.
Functions ¶
func CheckRequestPath ¶
CheckRequestPath reports whether reqPath addresses what it spells.
Resource ids reach dtctl as command-line arguments and as fields in applied files, and every API handler interpolates them into a request path. A value carrying a character that has meaning in a URL then addresses a *different* resource than the caller named -- and the request succeeds against it:
dtctl delete slo "<id>#x" -> DELETE /platform/slo/v1/slos/<id>
because net/http drops the fragment before the request goes out. The caller is told the id they typed was deleted; the object that was deleted is the one they did not type.
Handlers escape every interpolated value with net/url.PathEscape, which turns such a value into a 404 and leaves the decision to the API. This check is the other half, and the reason the first half cannot be quietly dropped: it runs on every request the SDK makes, so a handler written tomorrow without the escape fails loudly here instead of acting on the wrong object.
It deliberately does not reject '?'. `dtctl exec api` passes a caller-written path through to the environment, where a query string is legitimate, and pkg/resources/api.CanonicalRequestPath vets that spelling on its own terms. An unescaped '?' arriving from a resource id is caught by the escape at the call site, not here.
func CheckResponse ¶
CheckResponse inspects a resty response and returns a structured *APIError if the HTTP status code indicates an error (4xx/5xx). Returns nil for successful responses.
It attempts to parse the Dynatrace error response body for a human-readable message. If parsing fails, the raw response body is included as details.
func ExtractSubdomain ¶
ExtractSubdomain extracts the first subdomain (typically the environment or org ID) from a Dynatrace environment URL. For example, given "https://abc12345.apps.dynatrace.com" it returns "abc12345".
The URL must include a scheme (e.g. "https://"). Bare hostnames like "abc12345.apps.dynatrace.com" are not supported and will return an error.
func GuardRequestPaths ¶
GuardRequestPaths installs CheckRequestPath on rc, so that no request it sends can be retargeted by an unescaped resource id. Both SDK client constructors call it; a hand-built resty client should too.
The hook is registered with OnBeforeRequest rather than SetPreRequestHook for two reasons: resty keeps only one pre-request hook (the SDK's verbose logging owns it), and OnBeforeRequest runs before resty's own parseRequestURL, so Request.URL is still the literal path the handler passed -- which is the string that has to be vetted, since url.Parse would have already split the fragment off into a field nobody looks at.
func IsRetryable ¶
IsRetryable reports whether a request that ended in r and err is safe to send again automatically. It is the retry condition New installs, and the session client in sdk/session uses it too.
A request is resent only when sending it twice cannot do twice the work:
- 429 Too Many Requests, for any method: the server turned the request away without processing it.
- 503 Service Unavailable carrying a Retry-After header, for any method: the server is explicitly asking to be called again later.
- A connection that could not be established (a dial error), for any method: the request never reached the server.
- Any other 5xx, or any other transport error, only for idempotent methods (GET, HEAD, OPTIONS, TRACE, PUT, DELETE; RFC 9110 section 9.2.2).
A POST or PATCH that fails with a 500, a 502, a 504 or a dropped connection is not resent: the server may already have acted on it, and a second attempt could start a second workflow run, create a duplicate object, or run (and bill) a DQL query twice.
A request that never produced a response (r or r.Request is nil) is never retried, and neither is one whose context was cancelled or timed out.
func PathSegment ¶
PathSegment escapes v for use as one complete segment of a request path.
It is net/url.PathEscape plus the colon. PathEscape leaves ':' intact, and several Dynatrace collections spell an action as a suffix on the resource segment -- "/analyzers/%s:poll", "/bucket-definitions/%s:truncate". An id carrying a colon therefore names an *operation* rather than a resource:
dtctl describe analyzer "foo:poll" -> GET /analyzers/foo:poll
which polls the analyzer "foo" instead of looking up the one that was named. That is the same retargeting as '/', '?' and '#', and it is invisible for the same reason: the request succeeds, against something else.
Escaping the colon costs nothing, because an action suffix is a literal in the format string and never passes through here -- only the interpolated value does. The other characters PathEscape leaves alone ('$', '&', '+', '-', '.', '=', '@', '_', '~') route nothing in a path segment: '?' and '#' are already escaped, so '&' and '=' cannot begin a query, and ".." is refused by CheckRequestPath. They stay readable on the wire.
A value that is a path by design does not belong here. sdk/api/appengine escapes a nested function name part by part instead.
Types ¶
type APIError ¶
type APIError struct {
// StatusCode is the HTTP status code.
StatusCode int
// Message is a human-readable error description.
Message string
// Details contains additional error information from the API response body.
Details string
// contains filtered or unexported fields
}
APIError represents an error response from a Dynatrace API.
func NewAPIError ¶
NewAPIError creates a new API error with the appropriate sentinel.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is an HTTP client for Dynatrace APIs.
func New ¶
New creates a new Dynatrace HTTP client.
The baseURL is required (e.g. "https://abc.apps.dynatrace.com"). At minimum, provide WithToken to authenticate requests.
Retries are on by default: up to 3 retries, with jittered exponential backoff from 1s up to 10s between attempts. Use WithRetry to change that, or WithRetry(0, 0, 0) for a single attempt.
Only requests that are safe to send again are retried (see IsRetryable): idempotent methods (GET, HEAD, OPTIONS, TRACE, PUT, DELETE) on a 5xx or a transport error, and any method on a 429, on a 503 with Retry-After, or when the connection could not be established. A POST or PATCH that fails with any other 5xx or transport error is returned to the caller after one attempt, because the server may already have acted on it.
func Wrap ¶
Wrap creates a Client that wraps an already-configured *resty.Client. This is useful when integrating the SDK into an existing application that already manages its own HTTP client (e.g., the dtctl CLI).
The caller is responsible for configuring auth, retries, timeouts, etc. on the resty client before passing it in.
func (*Client) EnableVerboseLogging ¶
EnableVerboseLogging enables request/response debug logging. Level 1: summary. Level 2+: full headers and body (sensitive headers redacted).
type Logger ¶
type Logger interface {
Debugf(format string, args ...interface{})
}
Logger is the interface accepted by the HTTP client for debug output. Implementations must be safe for concurrent use.
type Option ¶
type Option func(*Client)
Option configures a Client.
func WithHTTPProxy ¶
WithHTTPProxy sets an HTTP proxy URL.
func WithLogger ¶
WithLogger sets the logger for debug output. A nil logger is ignored.
func WithRetry ¶
WithRetry sets how often, and with what backoff, a failed request is retried. maxRetries is the number of attempts after the first; 0 disables retries entirely. waitTime and maxWaitTime bound the jittered exponential backoff between attempts.
WithRetry changes only the budget, not which requests qualify: a request is retried only when IsRetryable says it is safe to send again, so a POST or PATCH that fails with a 5xx or a dropped connection is never resent, however high maxRetries is. To retry one specific non-idempotent request anyway, add a request-level condition with resty's Request.AddRetryCondition; it is consulted before the client's.
func WithToken ¶
WithToken sets the authentication token. The auth scheme (Bearer vs Api-Token) is determined automatically from the token prefix.
func WithTransport ¶
func WithTransport(rt http.RoundTripper) Option
WithTransport sets a custom http.RoundTripper, useful for injecting OpenTelemetry or other middleware.
func WithUserAgent ¶
WithUserAgent sets the User-Agent header prefix. AI agent detection suffix is appended automatically.
type PaginationParams ¶
type PaginationParams struct {
Style PaginationStyle
PageKeyParam string
PageSizeParam string
NextPageKey string
PageSize int64
Filters map[string]string
}
PaginationParams configures how pagination query parameters are applied.
func (PaginationParams) QueryParams ¶
func (p PaginationParams) QueryParams() url.Values
QueryParams returns the query parameters to apply for the current page. This is a pure function with no resty dependency, suitable for any HTTP client.
type PaginationStyle ¶
type PaginationStyle int
PaginationStyle controls how page-key and page-size interact.
Dynatrace APIs have three distinct pagination behaviors:
- Default: page-size must NOT be sent with page-key.
- DocumentAPI: page-size CAN be sent with page-key.
- SettingsAPI: when nextPageKey is present, NO other params may be sent.
const ( // PaginationDefault is the standard style used by most Dynatrace APIs. PaginationDefault PaginationStyle = iota // PaginationDocumentAPI is used by the Document API. PaginationDocumentAPI // PaginationSettingsAPI is used by the Settings API. PaginationSettingsAPI )