Documentation ¶
Overview ¶
api_handler.go
http_client_bearer_token_auth.go
The http_client_auth package focuses on authentication mechanisms for an HTTP client.
It provides structures and methods for handling both basic and bearer token based authentication
http_client_oauth.go
The http_client_auth package focuses on authentication mechanisms for an HTTP client.
It provides structures and methods for handling OAuth-based authentication
http_client_auth_token_management.go
http_client.go
The `http_client` package provides a configurable HTTP client tailored for interacting with specific APIs.
It supports different authentication methods, including "bearer" and "oauth". The client is designed with a focus on concurrency management, structured error handling, and flexible configuration options. The package offers a default timeout, custom backoff strategies, dynamic rate limiting, and detailed logging capabilities. The main `Client` structure encapsulates all necessary components, like the baseURL, authentication details, and an embedded standard HTTP client.
http_concurrency_management.go package httpclient provides utilities to manage HTTP client interactions, including concurrency control. The Concurrency Manager ensures no more than a certain number of concurrent requests (e.g., 5 for Jamf Pro) are sent at the same time. This is managed using a semaphore
http_helpers.go
http_request.go
sdk_version.go
Index ¶
- Constants
- func CheckDeprecationHeader(resp *http.Response, log logger.Logger)
- func DetermineAuthMethod(authConfig AuthConfig) (string, error)
- func GetUserAgentHeader() string
- func HeadersToString(headers http.Header) string
- func IsValidClientID(clientID string) (bool, string)
- func IsValidClientSecret(clientSecret string) (bool, string)
- func IsValidPassword(password string) (bool, string)
- func IsValidUsername(username string) (bool, string)
- func Min(a, b int) int
- func ParseISO8601Date(dateStr string) (time.Time, error)
- func RedactSensitiveData(client *Client, key string, value string) string
- type APIHandler
- type AuthConfig
- type BearerTokenAuthCredentials
- type Client
- func (c *Client) AdjustConcurrencyBasedOnMetrics()
- func (c *Client) AverageAcquisitionTime() time.Duration
- func (c *Client) DoMultipartRequest(method, endpoint string, fields map[string]string, files map[string]string, ...) (*http.Response, error)
- func (c *Client) DoRequest(method, endpoint string, body, out interface{}, log logger.Logger) (*http.Response, error)
- func (c *Client) EvaluateMetricsAndAdjustConcurrency()
- func (c *Client) GetPerformanceMetrics() *PerformanceMetrics
- func (c *Client) HistoricalAverageAcquisitionTime() time.Duration
- func (c *Client) ObtainOAuthToken(credentials AuthConfig, log logger.Logger) error
- func (c *Client) ObtainToken(log logger.Logger) error
- func (c *Client) RefreshToken(log logger.Logger) error
- func (c *Client) SetBearerTokenAuthCredentials(credentials BearerTokenAuthCredentials)
- func (c *Client) SetOAuthCredentials(credentials OAuthCredentials)
- func (c *Client) StartConcurrencyAdjustment()
- func (c *Client) StartMetricEvaluation()
- func (c *Client) ValidAuthTokenCheck(log logger.Logger) (bool, error)
- type ClientConfig
- type ClientOptions
- type ConcurrencyManager
- func (c *ConcurrencyManager) Acquire(ctx context.Context) (uuid.UUID, error)
- func (c *ConcurrencyManager) AdjustConcurrencyLimit(newLimit int)
- func (c *ConcurrencyManager) AverageAcquisitionTime() time.Duration
- func (c *ConcurrencyManager) HistoricalAverageAcquisitionTime() time.Duration
- func (c *ConcurrencyManager) Release(requestID uuid.UUID)
- type EnvironmentConfig
- type OAuthCredentials
- type OAuthResponse
- type PerformanceMetrics
- type TokenResponse
Constants ¶
const ( MaxConcurrency = 10 // Maximum allowed concurrent requests MinConcurrency = 1 // Minimum allowed concurrent requests EvaluationInterval = 1 * time.Minute // Time interval for evaluating metrics and adjusting concurrency )
const ( DefaultLogLevel = logger.LogLevelInfo DefaultMaxRetryAttempts = 3 DefaultEnableDynamicRateLimiting = true DefaultMaxConcurrentRequests = 5 DefaultTokenBufferPeriod = 5 * time.Minute DefaultTotalRetryDuration = 5 * time.Minute DefaultTimeout = 10 * time.Second )
const ( SDKVersion = "0.0.8" UserAgentBase = "go-api-http-client" )
Variables ¶
This section is empty.
Functions ¶
func CheckDeprecationHeader ¶
CheckDeprecationHeader checks the response headers for the Deprecation header and logs a warning if present.
func DetermineAuthMethod ¶ added in v0.0.9
func DetermineAuthMethod(authConfig AuthConfig) (string, error)
DetermineAuthMethod determines the authentication method based on the provided credentials. It prefers strong authentication methods (e.g., OAuth) over weaker ones (e.g., bearer tokens). It logs an error and returns "unknown" if no valid credentials are provided.
func GetUserAgentHeader ¶
func GetUserAgentHeader() string
func HeadersToString ¶
HeadersToString converts an http.Header map to a single string representation.
func IsValidClientID ¶ added in v0.0.9
IsValidClientID checks if the provided client ID is a valid UUID. Returns true if valid, along with an empty error message; otherwise, returns false with an error message.
func IsValidClientSecret ¶ added in v0.0.9
IsValidClientSecret checks if the provided client secret meets your application's validation criteria. Returns true if valid, along with an empty error message; otherwise, returns false with an error message.
func IsValidPassword ¶ added in v0.0.9
IsValidPassword checks if the provided password meets your application's validation criteria. Returns true if valid, along with an empty error message; otherwise, returns false with an error message.
func IsValidUsername ¶ added in v0.0.9
IsValidUsername checks if the provided username meets your application's validation criteria. Returns true if valid, along with an empty error message; otherwise, returns false with an error message.
func ParseISO8601Date ¶
ParseISO8601Date attempts to parse a string date in ISO 8601 format.
Types ¶
type APIHandler ¶
type APIHandler interface { ConstructAPIResourceEndpoint(instanceName string, endpointPath string, log logger.Logger) string ConstructAPIAuthEndpoint(instanceName string, endpointPath string, log logger.Logger) string MarshalRequest(body interface{}, method string, endpoint string, log logger.Logger) ([]byte, error) MarshalMultipartRequest(fields map[string]string, files map[string]string, log logger.Logger) ([]byte, string, error) UnmarshalResponse(resp *http.Response, out interface{}, log logger.Logger) error GetContentTypeHeader(method string, log logger.Logger) string GetAcceptHeader() string GetDefaultBaseDomain() string GetOAuthTokenEndpoint() string GetBearerTokenEndpoint() string GetTokenRefreshEndpoint() string GetTokenInvalidateEndpoint() string GetAPIBearerTokenAuthenticationSupportStatus() bool GetAPIOAuthAuthenticationSupportStatus() bool GetAPIOAuthWithCertAuthenticationSupportStatus() bool }
APIHandler is an interface for encoding, decoding, and implenting contexual api functions for different API implementations. It encapsulates behavior for encoding and decoding requests and responses.
func LoadAPIHandler ¶
func LoadAPIHandler(apiType string, log logger.Logger) (APIHandler, error)
LoadAPIHandler returns an APIHandler based on the provided API type. 'apiType' parameter could be "jamf" or "graph" to specify which API handler to load.
type AuthConfig ¶
type AuthConfig struct { Username string `json:"Username,omitempty"` Password string `json:"Password,omitempty"` ClientID string `json:"ClientID,omitempty"` ClientSecret string `json:"ClientSecret,omitempty"` }
AuthConfig represents the structure to read authentication details from a JSON configuration file.
type BearerTokenAuthCredentials ¶
BearerTokenAuthCredentials represents the username and password for basic authentication.
type Client ¶
type Client struct { APIHandler APIHandler // APIHandler interface used to define which API handler to use InstanceName string // Website Instance name without the root domain AuthMethod string // Specifies the authentication method: "bearer" or "oauth" Token string // Authentication Token OverrideBaseDomain string // Base domain override used when the default in the api handler isn't suitable OAuthCredentials OAuthCredentials // ClientID / Client Secret BearerTokenAuthCredentials BearerTokenAuthCredentials // Username and Password for Basic Authentication Expiry time.Time // Expiry time set for the auth token Logger logger.Logger ConcurrencyMgr *ConcurrencyManager PerfMetrics PerformanceMetrics // contains filtered or unexported fields }
Client represents an HTTP client to interact with a specific API.
func BuildClient ¶
func BuildClient(config ClientConfig) (*Client, error)
BuildClient creates a new HTTP client with the provided configuration.
func (*Client) AdjustConcurrencyBasedOnMetrics ¶
func (c *Client) AdjustConcurrencyBasedOnMetrics()
AdjustConcurrencyBasedOnMetrics evaluates the current metrics and adjusts the concurrency limit if required. It checks metrics like average token acquisition time and decides on a new concurrency limit. The method ensures that the new limit respects the minimum and maximum allowed concurrency bounds.
func (*Client) AverageAcquisitionTime ¶
Returns the average Acquisition Time to get a token from the semaphore
func (*Client) DoMultipartRequest ¶
func (c *Client) DoMultipartRequest(method, endpoint string, fields map[string]string, files map[string]string, out interface{}, log logger.Logger) (*http.Response, error)
DoMultipartRequest creates and executes a multipart HTTP request. It is used for sending files and form fields in a single request. This method handles the construction of the multipart message body, setting the appropriate headers, and sending the request to the given endpoint.
Parameters: - method: The HTTP method to use (e.g., POST, PUT). - endpoint: The API endpoint to which the request will be sent. - fields: A map of form fields and their values to include in the multipart message. - files: A map of file field names to file paths that will be included as file attachments. - out: A pointer to a variable where the unmarshaled response will be stored.
Returns: - A pointer to the http.Response received from the server. - An error if the request could not be sent or the response could not be processed.
The function first validates the authentication token, then constructs the multipart request body based on the provided fields and files. It then constructs the full URL for the request, sets the required headers (including Authorization and Content-Type), and sends the request.
If debug mode is enabled, the function logs all the request headers before sending the request. After the request is sent, the function checks the response status code. If the response is not within the success range (200-299), it logs an error and returns the response and an error. If the response is successful, it attempts to unmarshal the response body into the 'out' parameter.
Note: The caller should handle closing the response body when successful.
func (*Client) DoRequest ¶
func (c *Client) DoRequest(method, endpoint string, body, out interface{}, log logger.Logger) (*http.Response, error)
DoRequest constructs and executes an HTTP request with optional retry logic based on the request method. This function serves as a comprehensive solution for making HTTP calls, encompassing various features: authentication token validation, concurrency control, dynamic header setting, structured error handling, and conditional retry logic. It is designed to support operations that can be encoded in a single JSON or XML body, such as creating or updating resources.
The function workflow includes:
- Authentication Token Validation: Ensures that the client's authentication token is valid before proceeding with the request.
- Concurrency Control: Manages concurrency using a token system, ensuring that no more than a predefined number of requests are made concurrently, to prevent overwhelming the server.
- Request Preparation: Constructs the HTTP request, including marshaling the request body based on the API handler rules and setting necessary headers like Authorization, Content-Type, and User-Agent.
- Request Execution: Depending on the HTTP method, the request may be executed with or without retry logic. Retryable methods (GET, DELETE, PUT, PATCH) are subject to retry logic in case of transient errors or rate limits, using an exponential backoff strategy. Non-retryable methods are executed once without retries.
- Response Processing: Handles the server response, unmarshals the response body into the provided output parameter if the response is successful, and manages errors using structured error handling.
Parameters: - method: The HTTP method to use (e.g., GET, POST, PUT, DELETE, PATCH). Determines whether retry logic should be applied. - endpoint: The API endpoint to which the request will be sent. Used to construct the full request URL. - body: The payload to send in the request, which will be marshaled according to the specified content type. - out: A pointer to a variable where the unmarshaled response will be stored. This is where the result of a successful request will be placed. - log: A logger instance for recording informational messages and errors encountered during the request execution.
Returns: - A pointer to the http.Response received from the server if the request is successful. - An error if the request could not be sent, the response could not be processed, or if retry attempts for retryable methods fail.
Note: - It is the caller's responsibility to close the response body when the request is successful to avoid resource leaks. - The function adheres to best practices for HTTP communication in Go, ensuring robust error handling and efficient resource management.
func (*Client) EvaluateMetricsAndAdjustConcurrency ¶
func (c *Client) EvaluateMetricsAndAdjustConcurrency()
EvaluateMetricsAndAdjustConcurrency evaluates the performance metrics and makes necessary adjustments to the concurrency limit. The method assesses the average response time and adjusts the concurrency based on how it compares to the historical average acquisition time. If the average response time has significantly increased compared to the historical average, the concurrency limit is decreased, and vice versa. The method ensures that the concurrency limit remains within the bounds defined by the system's best practices.
func (*Client) GetPerformanceMetrics ¶
func (c *Client) GetPerformanceMetrics() *PerformanceMetrics
Returns performance metrics from the http client
func (*Client) HistoricalAverageAcquisitionTime ¶
func (*Client) ObtainOAuthToken ¶
func (c *Client) ObtainOAuthToken(credentials AuthConfig, log logger.Logger) error
ObtainOAuthToken fetches an OAuth access token using the provided OAuthCredentials (Client ID and Client Secret). It updates the client's Token and Expiry fields with the obtained values.
func (*Client) ObtainToken ¶
ObtainToken fetches and sets an authentication token using the stored basic authentication credentials.
func (*Client) RefreshToken ¶
RefreshToken refreshes the current authentication token.
func (*Client) SetBearerTokenAuthCredentials ¶
func (c *Client) SetBearerTokenAuthCredentials(credentials BearerTokenAuthCredentials)
SetBearerTokenAuthCredentials sets the BearerTokenAuthCredentials (Username and Password) for the client instance. These credentials are used for obtaining and refreshing bearer tokens for authentication.
func (*Client) SetOAuthCredentials ¶
func (c *Client) SetOAuthCredentials(credentials OAuthCredentials)
SetOAuthCredentials sets the OAuth credentials (Client ID and Client Secret) for the client instance. These credentials are used for obtaining and refreshing OAuth tokens for authentication.
func (*Client) StartConcurrencyAdjustment ¶
func (c *Client) StartConcurrencyAdjustment()
StartConcurrencyAdjustment launches a periodic checker that evaluates current metrics and adjusts concurrency limits if needed. It uses a ticker to periodically trigger the adjustment logic.
func (*Client) StartMetricEvaluation ¶
func (c *Client) StartMetricEvaluation()
StartMetricEvaluation continuously monitors the client's interactions with the API and adjusts the concurrency limits dynamically. The function evaluates metrics at regular intervals to detect burst activity patterns. If a burst activity is detected (e.g., many requests in a short period), the evaluation interval is reduced for more frequent checks. Otherwise, it reverts to a default interval for regular checks. After each evaluation, the function calls EvaluateMetricsAndAdjustConcurrency to potentially adjust the concurrency based on observed metrics.
The evaluation process works as follows: 1. Sleep for the defined evaluation interval. 2. Check if there's a burst in activity using the isBurstActivity method. 3. If a burst is detected, the evaluation interval is shortened to more frequently monitor and adjust the concurrency. 4. If no burst is detected, it maintains the default evaluation interval. 5. It then evaluates the metrics and adjusts the concurrency accordingly.
func (*Client) ValidAuthTokenCheck ¶
ValidAuthTokenCheck checks if the current token is valid and not close to expiry. If the token is invalid, it tries to refresh it. It returns a boolean indicating the validity of the token and an error if there's a failure.
type ClientConfig ¶ added in v0.0.12
type ClientConfig struct { Auth AuthConfig // User can either supply these values manually or pass from LoadAuthConfig/Env vars Environment EnvironmentConfig // User can either supply these values manually or pass from LoadAuthConfig/Env vars ClientOptions ClientOptions // Optional configuration options for the HTTP Client }
Config holds configuration options for the HTTP Client.
type ClientOptions ¶ added in v0.0.12
type ClientOptions struct { LogLevel string // Field for defining tiered logging level. LogOutputFormat string // Field for defining the output format of the logs. Use "JSON" for JSON format, "console" for human-readable format HideSensitiveData bool // Field for defining whether sensitive fields should be hidden in logs. MaxRetryAttempts int // Config item defines the max number of retry request attempts for retryable HTTP methods. EnableDynamicRateLimiting bool // Field for defining whether dynamic rate limiting should be enabled. MaxConcurrentRequests int // Field for defining the maximum number of concurrent requests allowed in the semaphore TokenRefreshBufferPeriod time.Duration TotalRetryDuration time.Duration CustomTimeout time.Duration }
ClientOptions holds optional configuration options for the HTTP Client.
type ConcurrencyManager ¶
type ConcurrencyManager struct { AcquisitionTimes []time.Duration // contains filtered or unexported fields }
ConcurrencyManager controls the number of concurrent HTTP requests.
func NewConcurrencyManager ¶
func NewConcurrencyManager(limit int, logger logger.Logger, debugMode bool) *ConcurrencyManager
NewConcurrencyManager initializes a new ConcurrencyManager with the given concurrency limit, logger, and debug mode. The ConcurrencyManager ensures no more than a certain number of concurrent requests are made. It uses a semaphore to control concurrency.
func (*ConcurrencyManager) Acquire ¶
Acquire attempts to get a token to allow an HTTP request to proceed. It blocks until a token is available or the context expires. Returns a unique request ID upon successful acquisition.
func (*ConcurrencyManager) AdjustConcurrencyLimit ¶
func (c *ConcurrencyManager) AdjustConcurrencyLimit(newLimit int)
AdjustConcurrencyLimit dynamically modifies the maximum concurrency limit based on the newLimit provided. This function helps in adjusting the concurrency limit in real-time based on observed system performance and other metrics. It transfers the tokens from the old semaphore to the new one, ensuring that there's no loss of tokens during the transition.
func (*ConcurrencyManager) AverageAcquisitionTime ¶
func (c *ConcurrencyManager) AverageAcquisitionTime() time.Duration
AverageAcquisitionTime computes the average time taken to acquire a token from the semaphore. It helps in understanding the contention for tokens and can be used to adjust concurrency limits.
func (*ConcurrencyManager) HistoricalAverageAcquisitionTime ¶
func (c *ConcurrencyManager) HistoricalAverageAcquisitionTime() time.Duration
HistoricalAverageAcquisitionTime computes the average time taken to acquire a token from the semaphore over a historical period (e.g., the last 5 minutes). It helps in understanding the historical contention for tokens and can be used to adjust concurrency limits.
func (*ConcurrencyManager) Release ¶
func (c *ConcurrencyManager) Release(requestID uuid.UUID)
Release returns a token back to the pool, allowing other requests to proceed. It uses the provided requestID for logging and debugging purposes.
type EnvironmentConfig ¶ added in v0.0.5
type EnvironmentConfig struct { InstanceName string `json:"InstanceName,omitempty"` OverrideBaseDomain string `json:"OverrideBaseDomain,omitempty"` APIType string `json:"APIType,omitempty"` }
EnvironmentConfig represents the structure to read authentication details from a JSON configuration file.
type OAuthCredentials ¶
OAuthCredentials contains the client ID and client secret required for OAuth authentication.
type OAuthResponse ¶
type OAuthResponse struct { AccessToken string `json:"access_token"` ExpiresIn int64 `json:"expires_in"` TokenType string `json:"token_type"` RefreshToken string `json:"refresh_token,omitempty"` Error string `json:"error,omitempty"` }
OAuthResponse represents the response structure when obtaining an OAuth access token.
type PerformanceMetrics ¶
type PerformanceMetrics struct { TotalRequests int64 TotalRetries int64 TotalRateLimitErrors int64 TotalResponseTime time.Duration TokenWaitTime time.Duration // contains filtered or unexported fields }
ClientPerformanceMetrics captures various metrics related to the client's interactions with the API, providing insights into its performance and behavior.
type TokenResponse ¶
TokenResponse represents the structure of a token response from the API.
Source Files ¶
- httpclient_api_handler.go
- httpclient_auth_bearer_token.go
- httpclient_auth_oauth.go
- httpclient_auth_token_management.go
- httpclient_auth_validation.go
- httpclient_client.go
- httpclient_concurrency_management.go
- httpclient_defaultconfig.go
- httpclient_headers.go
- httpclient_helpers.go
- httpclient_rate_handler.go
- httpclient_request.go
- httpclient_version.go