Documentation
¶
Overview ¶
graph_api_handler.go
------------------------------Summary----------------------------------------
This is a api handler module for the http_client to accommodate specifics of jamf's api(s). It handles the encoding (marshalling) and decoding (unmarshalling) of data. It also sets the correct content headers for the various http methods.
This module integrates with the http_client logger for wrapped error handling for human readable return codes. It also supports the http_client tiered logging functionality for logging support.
The logic of this module is defined as follows: Classic API:
For requests (GET, POST, PUT, DELETE): - Encoding (Marshalling): Use XML format. For responses (GET, POST, PUT): - Decoding (Unmarshalling): Use XML format. For responses (DELETE): - Handle response codes as response body lacks anything useful. Headers - Sets accept headers based on weighting. XML out weighs JSON to ensure XML is returned - Sets content header as application/xml with edge case exceptions based on need.
JamfPro API:
For requests (GET, POST, PUT, DELETE): - Encoding (Marshalling): Use JSON format. For responses (GET, POST, PUT): - Decoding (Unmarshalling): Use JSON format. For responses (DELETE): - Handle response codes as response body lacks anything useful. Headers - Sets accept headers based on weighting. Jamf Pro API doesn't support XML, so MIME type is skipped and returns JSON - Set content header as application/json with edge case exceptions based on need.
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_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_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_concurrency_management.go Package http_client 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_error_handling.go This package provides utility functions and structures for handling and categorizing HTTP error responses.
http_helpers.go
http_logging.go
http_methods.go
http_request.go
sdk_version.go
Index ¶
- Constants
- func CheckDeprecationHeader(resp *http.Response, logger Logger)
- func EnsureHTTPScheme(url string) string
- func GetAuthCredentialsFromEnv() map[string]string
- func GetUserAgentHeader() string
- func LoadUserConfig(filename string) error
- func Min(a, b int) int
- func ParseISO8601Date(dateStr string) (time.Time, error)
- type APIError
- type APIHandler
- type Client
- func (c *Client) AdjustConcurrencyBasedOnMetrics()
- func (c *Client) AverageAcquisitionTime() time.Duration
- func (c *Client) ConstructMSGraphAPIEndpoint(endpointPath string) string
- func (c *Client) Delete(endpoint string, out interface{}) (*http.Response, error)
- 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{}) (*http.Response, error)
- func (c *Client) EvaluateMetricsAndAdjustConcurrency()
- func (c *Client) Get(endpoint string, out interface{}) (*http.Response, error)
- func (c *Client) GetOAuthCredentials() OAuthCredentials
- func (c *Client) GetPerformanceMetrics() *ClientPerformanceMetrics
- func (c *Client) HistoricalAverageAcquisitionTime() time.Duration
- func (c *Client) ObtainOauthTokenWithApp(tenantID, clientID, clientSecret string) (*OAuthResponse, error)
- func (c *Client) ObtainOauthTokenWithCertificate(tenantID, clientID, thumbprint, keyFile string) (*OAuthResponse, error)
- func (c *Client) Patch(endpoint string, body, out interface{}) (*http.Response, error)
- func (c *Client) Post(endpoint string, body, out interface{}) (*http.Response, error)
- func (c *Client) Put(endpoint string, body, out interface{}) (*http.Response, error)
- func (c *Client) SetGraphAuthenticationMethod(creds map[string]string)
- func (c *Client) StartConcurrencyAdjustment()
- func (c *Client) StartMetricEvaluation()
- func (c *Client) ValidAuthTokenCheck() (bool, error)
- type ClientAuthConfig
- type ClientOption
- type ClientPerformanceMetrics
- 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 Config
- type ConfigMap
- type EndpointConfig
- type LogLevel
- type Logger
- type OAuthCredentials
- type OAuthResponse
- type StructuredError
- type TokenResponse
- type UnifiedGraphAPIHandler
- func (u *UnifiedGraphAPIHandler) GetAcceptHeader() string
- func (u *UnifiedGraphAPIHandler) GetContentTypeHeader(endpoint string) string
- func (u *UnifiedGraphAPIHandler) MarshalMultipartRequest(fields map[string]string, files map[string]string) ([]byte, string, error)
- func (u *UnifiedGraphAPIHandler) MarshalRequest(body interface{}, method string, endpoint string) ([]byte, error)
- func (u *UnifiedGraphAPIHandler) SetLogger(logger Logger)
- func (u *UnifiedGraphAPIHandler) UnmarshalResponse(resp *http.Response, out interface{}) error
Constants ¶
const ( DefaultBaseDomain = "graph.microsoft.com" // DefaultBaseDomain: represents the base domain for graph. TokenInvalidateEndpoint = "/api/v1/auth/invalidate-token" // TokenInvalidateEndpoint: The endpoint to invalidate an active token. )
Endpoint constants represent the URL suffixes used for Jamf API token interactions.
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 ( SDKVersion = "0.0.1" UserAgentBase = "go-api-sdk-m365" )
const Authority = "https://login.microsoftonline.com/"
const DefaultTimeout = 10 * time.Second
const Scope = "https://graph.microsoft.com/.default"
Variables ¶
This section is empty.
Functions ¶
func CheckDeprecationHeader ¶
CheckDeprecationHeader checks the response headers for the Deprecation header and logs a warning if present.
func EnsureHTTPScheme ¶
EnsureHTTPScheme prefixes a URL with "http://" it defaults to "https://" doesn't already have an "https://".
func GetAuthCredentialsFromEnv ¶
GetAuthCredentialsFromEnv takes environment variables and maps them to the http client initialization if present.
func GetUserAgentHeader ¶
func GetUserAgentHeader() string
func LoadUserConfig ¶
LoadUserConfig allows users to apply their own configuration by providing a JSON file. The custom configuration will override the default settings previously loaded. It reads the file from the provided filename path and unmarshals its content into the configMap. If reading or unmarshalling fails, an error is returned.
Types ¶
type APIHandler ¶
type APIHandler interface {
MarshalRequest(body interface{}, method string, endpoint string) ([]byte, error)
MarshalMultipartRequest(fields map[string]string, files map[string]string) ([]byte, string, error) // New method for multipart
UnmarshalResponse(resp *http.Response, out interface{}) error
GetContentTypeHeader(method string) string
GetAcceptHeader() string
SetLogger(logger Logger)
}
APIHandler is an interface for encoding, decoding, and determining content types for different API implementations. It encapsulates behavior for encoding and decoding requests and responses.
func GetAPIHandler ¶
func GetAPIHandler(config Config) APIHandler
GetAPIHandler initializes and returns an APIHandler with a configured logger.
type Client ¶
type Client struct {
TenantID string // M365 tenant ID
TenantName string // M365 tenant name
AuthMethod string // Specifies the authentication method: "clientApp" or "clientCertificate"
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
Expiry time.Time // Expiry time set for the auth token
ConcurrencyMgr *ConcurrencyManager
PerfMetrics ClientPerformanceMetrics
// contains filtered or unexported fields
}
Client represents an HTTP client to interact with a specific API.
func NewClient ¶
func NewClient(config Config, clientAuthConfig *ClientAuthConfig, logger Logger, options ...ClientOption) (*Client, error)
NewClient initializes a new http client instance with the given baseURL, logger, concurrency manager and client configuration
If TokenLifespan and BufferPeriod aren't set in the config, they default to 30 minutes and 5 minutes, respectively. If TotalRetryDuration isn't set in the config, it defaults to 1 minute. If no logger is provided, a default logger will be used. Any additional options provided will be applied to the client during initialization. Detect authentication method based on supplied credential type
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) ConstructMSGraphAPIEndpoint ¶
Functions
// GetBaseDomain returns the appropriate base domain for URL construction. // It uses OverrideBaseDomain if set, otherwise falls back to DefaultBaseDomain.
func (c *Client) GetBaseDomain() string {
if c.OverrideBaseDomain != "" {
return c.OverrideBaseDomain
}
return DefaultBaseDomain
}
// ConstructAPIResourceEndpoint returns the full URL for a Jamf API resource endpoint path.
func (c *Client) ConstructAPIResourceEndpoint(endpointPath string) string {
baseDomain := c.GetBaseDomain()
url := fmt.Sprintf("https://%s%s%s", c.TenantName, baseDomain, endpointPath)
c.logger.Info("Request will be made to API Resource URL:", "URL", url)
return url
}
ConstructMSGraphAPIEndpoint constructs the full URL for an MS Graph API endpoint. The function takes version (e.g., "/v1.0" or "/beta") and the specific API path.
func (*Client) Delete ¶
Delete sends a DELETE request to the specified endpoint and unmarshals the response into 'out'. The caller is responsible for closing the response body.
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.
func (*Client) DoRequest ¶
DoRequest constructs and executes a standard HTTP request with support for retry logic. It is intended for operations that can be encoded in a single JSON or XML body such as creating or updating resources. This method includes token validation, concurrency control, performance metrics, dynamic header setting, and structured error handling.
Parameters: - method: The HTTP method to use (e.g., GET, POST, PUT, DELETE, PATCH). - endpoint: The API endpoint to which the request will be sent. - body: The payload to send in the request, which will be marshaled based on the API handler rules. - 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, the response could not be processed, or if retry attempts fail.
The function starts by validating the client's authentication token and managing concurrency using a token system. It then determines the appropriate API handler for marshaling the request body and setting headers. The request is sent to the constructed URL with all necessary headers including authorization, content type, and user agent.
If configured for debug logging, the function logs all request headers before sending. The function then enters a loop to handle retryable HTTP methods, implementing a retry mechanism for transient errors, rate limits, and other retryable conditions based on response status codes.
The function also updates performance metrics to track total request count and cumulative response time. After processing the response, it handles any API errors and unmarshals the response body into the provided 'out' parameter if the response is successful.
Note: The function assumes that retryable HTTP methods have been properly defined in the retryableHTTPMethods map. It is the caller's responsibility to close the response body when the request is successful to avoid resource leaks.
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) Get ¶
Get sends a GET request to the specified endpoint and unmarshals the response into 'out'. The caller is responsible for closing the response body.
func (*Client) GetOAuthCredentials ¶
func (c *Client) GetOAuthCredentials() OAuthCredentials
GetOAuthCredentials retrieves the current OAuth credentials (Client ID and Client Secret) set for the client instance. Used for test cases.
func (*Client) GetPerformanceMetrics ¶
func (c *Client) GetPerformanceMetrics() *ClientPerformanceMetrics
Returns performance metrics from the http client
func (*Client) HistoricalAverageAcquisitionTime ¶
func (*Client) ObtainOauthTokenWithApp ¶
func (c *Client) ObtainOauthTokenWithApp(tenantID, clientID, clientSecret string) (*OAuthResponse, error)
ObtainOauthTokenWithApp fetches an OAuth access token using client credentials.
func (*Client) ObtainOauthTokenWithCertificate ¶
func (c *Client) ObtainOauthTokenWithCertificate(tenantID, clientID, thumbprint, keyFile string) (*OAuthResponse, error)
ObtainOauthTokenWithCertificate fetches an OAuth access token using a certificate.
func (*Client) Patch ¶
Patch sends a PATCH request to the specified endpoint with the provided body and unmarshals the response into 'out'. The caller is responsible for closing the response body.
func (*Client) Post ¶
Post sends a POST request to the specified endpoint with the provided body and unmarshals the response into 'out'. The caller is responsible for closing the response body.
func (*Client) Put ¶
Put sends a PUT request to the specified endpoint with the provided body and unmarshals the response into 'out'. The caller is responsible for closing the response body.
func (*Client) SetGraphAuthenticationMethod ¶
SetGraphAuthenticationMethod interprets and sets the credentials for the HTTP Client.
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 or close to expiry, it tries to obtain a new token.
type ClientAuthConfig ¶
type ClientAuthConfig struct {
TenantID string `json:"tenantID,omitempty"`
TenantName string `json:"tenantName,omitempty"`
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
ClientID string `json:"clientID,omitempty"`
ClientSecret string `json:"clientSecret,omitempty"`
CertificatePath string `json:"certificatePath,omitempty"` // Path to the certificate file
CertificateKeyPath string `json:"certificateKeyPath,omitempty"` // Path to the certificate key file
CertThumbprint string `json:"certThumbprint,omitempty"` // Certificate thumbprint
}
ClientAuthConfig represents the structure to read authentication details from a JSON configuration file.
func LoadClientAuthConfig ¶
func LoadClientAuthConfig(filename string) (*ClientAuthConfig, error)
LoadClientAuthConfig reads a JSON configuration file and decodes it into a ClientAuthConfig struct. It is used to retrieve authentication details like BaseURL, Username, and Password for the client.
type ClientOption ¶
type ClientOption func(*Client)
ClientOption defines a function type for modifying client properties during initialization.
type ClientPerformanceMetrics ¶
type ClientPerformanceMetrics 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 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, 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 Config ¶
type Config struct {
LogLevel LogLevel // Field for defining tiered logging level.
MaxRetryAttempts int // Config item defines the max number of retry request attempts for retryable HTTP methods.
EnableDynamicRateLimiting bool
Logger Logger // Field for the packages initailzed logger
MaxConcurrentRequests int // Field for defining the maximum number of concurrent requests allowed in the semaphore
TokenLifespan time.Duration
TokenRefreshBufferPeriod time.Duration
TotalRetryDuration time.Duration
}
Config holds configuration options for the HTTP Client.
type ConfigMap ¶
type ConfigMap map[string]EndpointConfig
ConfigMap is a map that associates endpoint URL patterns with their corresponding configurations. The map's keys are strings that identify the endpoint, and the values are EndpointConfig structs that hold the configuration for that endpoint.
type EndpointConfig ¶
type EndpointConfig struct {
Accept string `json:"accept"` // Accept specifies the MIME type the endpoint can handle in responses.
ContentType *string `json:"content_type"` // ContentType, if not nil, specifies the MIME type to set for requests sent to the endpoint. A pointer is used to distinguish between a missing field and an empty string.
}
EndpointConfig is a struct that holds configuration details for a specific API endpoint. It includes what type of content it can accept and what content type it should send.
type Logger ¶
type Logger interface {
SetLevel(level LogLevel)
Trace(msg string, keysAndValues ...interface{}) // For very detailed logs
Debug(msg string, keysAndValues ...interface{}) // For development and troubleshooting
Info(msg string, keysAndValues ...interface{}) // Informational messages
Warn(msg string, keysAndValues ...interface{}) // For potentially problematic situations
Error(msg string, keysAndValues ...interface{}) // For errors that might still allow the app to continue running
Fatal(msg string, keysAndValues ...interface{}) // For errors that might prevent the app from continuing
}
Logger is an interface for logging within the SDK.
func NewDefaultLogger ¶
func NewDefaultLogger() Logger
NewDefaultLogger now initializes a defaultLogger with a default log level.
type OAuthCredentials ¶
type OAuthCredentials struct {
ClientID string
ClientSecret string
CertificatePath string
CertificateKeyPath string
CertThumbprint string
}
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 StructuredError ¶
type StructuredError struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
StructuredError represents a structured error response from the API.
type TokenResponse ¶
TokenResponse represents the structure of a token response from the API.
type UnifiedGraphAPIHandler ¶
type UnifiedGraphAPIHandler struct {
// contains filtered or unexported fields
}
UnifiedAPIHandler is a struct that implements the APIHandler interface. It holds a Logger instance to facilitate logging across various API handling methods. This handler is responsible for encoding and decoding request and response data, determining content types, and other API interactions as defined by the APIHandler interface.
func (*UnifiedGraphAPIHandler) GetAcceptHeader ¶
func (u *UnifiedGraphAPIHandler) GetAcceptHeader() string
GetAcceptHeader constructs and returns a weighted Accept header string for HTTP requests. The Accept header indicates the MIME types that the client can process and prioritizes them based on the quality factor (q) parameter. Higher q-values signal greater preference. This function specifies a range of MIME types with their respective weights, ensuring that the server is informed of the client's versatile content handling capabilities while indicating a preference for XML. The specified MIME types cover common content formats like images, JSON, XML, HTML, plain text, and certificates, with a fallback option for all other types.
func (*UnifiedGraphAPIHandler) GetContentTypeHeader ¶
func (u *UnifiedGraphAPIHandler) GetContentTypeHeader(endpoint string) string
GetContentTypeHeader determines the appropriate Content-Type header for a given API endpoint. It attempts to find a content type that matches the endpoint prefix in the global configMap. If a match is found and the content type is defined (not nil), it returns the specified content type. If the content type is nil or no match is found in configMap, it falls back to default behaviors: - For all url endpoints it defaults to "application/json" for the graph beta and V1.0 API's. If the endpoint does not match any of the predefined patterns, "application/json" is used as a fallback. This method logs the decision process at various stages for debugging purposes.
func (*UnifiedGraphAPIHandler) MarshalMultipartRequest ¶
func (u *UnifiedGraphAPIHandler) MarshalMultipartRequest(fields map[string]string, files map[string]string) ([]byte, string, error)
MarshalMultipartFormData takes a map with form fields and file paths and returns the encoded body and content type.
func (*UnifiedGraphAPIHandler) MarshalRequest ¶
func (u *UnifiedGraphAPIHandler) MarshalRequest(body interface{}, method string, endpoint string) ([]byte, error)
MarshalRequest encodes the request body according to the endpoint for the API.
func (*UnifiedGraphAPIHandler) SetLogger ¶
func (u *UnifiedGraphAPIHandler) SetLogger(logger Logger)
SetLogger assigns a Logger instance to the UnifiedAPIHandler. This allows for logging throughout the handler's operations, enabling consistent logging that follows the configuration of the provided Logger.
func (*UnifiedGraphAPIHandler) UnmarshalResponse ¶
func (u *UnifiedGraphAPIHandler) UnmarshalResponse(resp *http.Response, out interface{}) error
UnmarshalResponse decodes the response body from XML or JSON format depending on the Content-Type header.