Documentation ¶
Overview ¶
httpclient/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.
httpclient/client_configuration.go Description: This file contains functions to load and validate configuration values from a JSON file or environment variables.
httprequest/multipartrequest.go
httpclient_ping.go
http_request.go
Index ¶
- Constants
- func DetermineAuthMethod(authConfig AuthConfig) (string, error)
- type AuthConfig
- type Client
- func (c *Client) DoMultipartRequest(method, endpoint string, fields map[string]string, files map[string]string, ...) (*http.Response, error)
- func (c *Client) DoPing(host string, timeout time.Duration) error
- func (c *Client) DoPole(method, endpoint string, body, out interface{}) (*http.Response, error)
- func (c *Client) DoRequest(method, endpoint string, body, out interface{}) (*http.Response, error)
- type ClientConfig
- type ClientOptions
- type EnvironmentConfig
Constants ¶
const ( DefaultLogLevel = logger.LogLevelInfo DefaultMaxRetryAttempts = 3 DefaultEnableDynamicRateLimiting = true DefaultMaxConcurrentRequests = 5 DefaultTokenBufferPeriod = 5 * time.Minute DefaultTotalRetryDuration = 5 * time.Minute DefaultTimeout = 10 * time.Second FollowRedirects = true MaxRedirects = 10 ConfigFileExtension = ".json" )
Variables ¶
This section is empty.
Functions ¶
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.
Types ¶
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 Client ¶
type Client struct { AuthMethod string // Specifies the authentication method: "bearer" or "oauth" Token string // Authentication Token Expiry time.Time // Expiry time set for the auth token Logger logger.Logger // Logger for logging messages ConcurrencyHandler *concurrency.ConcurrencyHandler // ConcurrencyHandler for managing concurrent requests APIHandler apihandler.APIHandler // APIHandler interface used to define which API handler to use AuthTokenHandler *authenticationhandler.AuthTokenHandler // AuthTokenHandler for managing authentication // 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) DoMultipartRequest ¶
func (c *Client) DoMultipartRequest(method, endpoint string, fields map[string]string, files map[string]string, out interface{}) (*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.
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.
func LoadConfigFromEnv ¶ added in v0.0.75
func LoadConfigFromEnv(config *ClientConfig) (*ClientConfig, error)
LoadConfigFromEnv populates the ClientConfig structure with values from environment variables. It updates the configuration for authentication, environment specifics, and client options based on the presence of environment variables. For each configuration option, if an environment variable is set, its value is used; otherwise, the existing value in the ClientConfig structure is retained. It also sets default values if necessary and validates the final configuration, returning an error if the configuration is incomplete.
func LoadConfigFromFile ¶ added in v0.0.77
func LoadConfigFromFile(filePath string) (*ClientConfig, error)
LoadConfigFromFile loads configuration values from a JSON file into the ClientConfig struct. This function opens the specified configuration file, reads its content, and unmarshals the JSON data into the ClientConfig struct. It's designed to initialize the client configuration with values from a file, complementing or overriding defaults and environment variable settings.
type ClientOptions ¶ added in v0.0.12
type ClientOptions struct { EnableCookieJar bool // Field to enable or disable cookie jar 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 LogConsoleSeparator string // Field for defining the separator in console output format. LogExportPath string // Field for specifying the path to output logs to. 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 FollowRedirects bool // Flag to enable/disable following redirects MaxRedirects int // Maximum number of redirects to follow TokenRefreshBufferPeriod time.Duration TotalRetryDuration time.Duration CustomTimeout time.Duration }
ClientOptions holds optional configuration options for the HTTP Client.
type EnvironmentConfig ¶ added in v0.0.5
type EnvironmentConfig struct { APIType string `json:"APIType,omitempty"` // APIType specifies the type of API integration to use InstanceName string `json:"InstanceName,omitempty"` // Website Instance name without the root domain OverrideBaseDomain string `json:"OverrideBaseDomain,omitempty"` // Base domain override used when the default in the api handler isn't suitable TenantID string `json:"TenantID,omitempty"` // TenantID is the unique identifier for the tenant TenantName string `json:"TenantName,omitempty"` // TenantName is the name of the tenant }
EnvironmentConfig represents the structure to read authentication details from a JSON configuration file.