http

package
v1.2.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2025 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Overview

Package http provides HTTP client utilities for CloudZero Agent external API integrations.

Package http provides HTTP client utilities for CloudZero Agent external API integrations.

Package http provides HTTP client utilities for CloudZero Agent external API integrations. This package implements reusable HTTP communication patterns used across CloudZero Agent for integrating with external services including the CloudZero platform, Kubernetes APIs, and other monitoring systems.

The HTTP client utilities provide consistent error handling, timeout management, and request configuration patterns that ensure reliable communication with external dependencies while maintaining observability and operational resilience.

Key capabilities:

  • Request configuration: Headers, query parameters, and body handling
  • Timeout management: Configurable timeouts with context cancellation support
  • Error classification: Network error categorization for retry and alerting logic
  • User agent management: Consistent CloudZero Agent identification
  • Response handling: Status code processing and error mapping

Integration patterns:

  • CloudZero API: Metric upload and authentication requests
  • Kubernetes API: Custom resource and admission webhook calls
  • Monitoring systems: Health checks and metric collection
  • Service discovery: Dynamic endpoint resolution and validation

The client utilities maintain separation between HTTP transport concerns and business logic, enabling reuse across different CloudZero Agent components while providing consistent operational behavior and error handling patterns.

Index

Constants

View Source
const (
	// HeaderAccept specifies the media types acceptable for HTTP response content.
	// CloudZero Agent uses this header to negotiate response formats with external APIs,
	// enabling support for JSON, protobuf, and other content types based on integration requirements.
	HeaderAccept = "Accept"

	// HeaderUserAgent identifies CloudZero Agent in HTTP requests to external services.
	// This header enables external services to identify CloudZero Agent requests for logging,
	// rate limiting, and compatibility purposes while providing version information for debugging.
	HeaderUserAgent = "User-Agent"

	// HeaderAuthorization carries authentication credentials for CloudZero platform and API integrations.
	// This header transmits API keys, bearer tokens, and other authentication data required
	// for secure communication with external services including the CloudZero platform.
	HeaderAuthorization = "Authorization"

	// HeaderContentEncoding specifies the encoding applied to HTTP request/response bodies.
	// CloudZero Agent uses this header to indicate compression formats (gzip, snappy)
	// for efficient data transmission with external services, particularly for metric uploads.
	HeaderContentEncoding = "Content-Encoding"

	// HeaderContentType indicates the media type of HTTP request/response body content.
	// This header enables proper serialization/deserialization of data exchanged with
	// external APIs, supporting JSON, protobuf, and other formats used by CloudZero integrations.
	HeaderContentType = "Content-Type"

	// HeaderAcceptEncoding specifies the content encodings acceptable for HTTP responses.
	// CloudZero Agent uses this header to indicate compression support (gzip, deflate)
	// to external services, enabling bandwidth optimization for large data transfers.
	HeaderAcceptEncoding = "Accept-Encoding"
)
View Source
const (
	// ContentTypeGzip identifies gzip-compressed content in HTTP communications.
	// CloudZero Agent uses this encoding type for compressing metric data uploads
	// to the CloudZero platform, reducing bandwidth usage and improving transfer efficiency.
	ContentTypeGzip = "gzip"

	// ContentTypeProtobuf specifies Protocol Buffer serialized content for binary data exchange.
	// This content type is used for Prometheus remote_write protocol communications
	// and other high-efficiency binary data transfers between CloudZero Agent and external services.
	ContentTypeProtobuf = "application/x-protobuf"

	// ContentTypeJSON indicates JSON-formatted content for structured data exchange.
	// CloudZero Agent uses JSON for CloudZero platform API communications, configuration
	// management, and human-readable data formats across various integrations.
	ContentTypeJSON = "application/json"

	// ContentTypeValueBin specifies binary octet-stream content for raw data transfers.
	// This content type supports file uploads, binary metric data, and other unstructured
	// binary content exchanged with external services.
	ContentTypeValueBin = "application/octet-stream"

	// ContentTypeValueTxt indicates plain text content for human-readable communications.
	// CloudZero Agent uses text content types for logging, debugging outputs,
	// and simple string-based API interactions.
	ContentTypeValueTxt = "text/plain"

	// ContentTypeValueYAML specifies YAML-formatted content for configuration and structured data.
	// This content type supports Kubernetes YAML resources, configuration files,
	// and human-readable structured data exchange.
	ContentTypeValueYAML = "text/yaml"

	// ContentTypeValueCSV indicates comma-separated values format for tabular data.
	// CloudZero Agent may use CSV format for data exports, reporting,
	// and structured data exchange with external analytics systems.
	ContentTypeValueCSV = "text/csv"
)
View Source
const (
	QueryParamClusterName = "cluster_name"
	QueryParamAccountID   = "cloud_account_id"
	QueryParamRegion      = "region"
)

Variables

View Source
var (
	ErrStatusBadRequest                    = errors.New("badrequest error")
	ErrStatusUnauthorized                  = errors.New("unauthorized error")
	ErrStatusPaymentRequired               = errors.New("paymentrequired error")
	ErrStatusForbidden                     = errors.New("forbidden error")
	ErrStatusNotFound                      = errors.New("not found error")
	ErrStatusMethodNotAllowed              = errors.New("method not allowed error")
	ErrStatusNotAcceptable                 = errors.New("not acceptable error")
	ErrStatusProxyAuthRequired             = errors.New("proxy authrequired error")
	ErrStatusRequestTimeout                = errors.New("request timeout error")
	ErrStatusConflict                      = errors.New("conflict error")
	ErrStatusGone                          = errors.New("gone error")
	ErrStatusLengthRequired                = errors.New("length required error")
	ErrStatusPreconditionFailed            = errors.New("precondition failed error")
	ErrStatusRequestEntityTooLarge         = errors.New("requestentity too large error")
	ErrStatusRequestURITooLong             = errors.New("request uri too long error")
	ErrStatusUnsupportedMediaType          = errors.New("unsupported media type error")
	ErrStatusRequestedRangeNotSatisfiable  = errors.New("requested range not satisfiable error")
	ErrStatusExpectationFailed             = errors.New("expectation failed error")
	ErrStatusTeapot                        = errors.New("teapot error")
	ErrStatusMisdirectedRequest            = errors.New("misdirected request error")
	ErrStatusUnprocessableEntity           = errors.New("unprocessable entity error")
	ErrStatusLocked                        = errors.New("locked error")
	ErrStatusFailedDependency              = errors.New("failed dependency error")
	ErrStatusTooEarly                      = errors.New("too early error")
	ErrStatusUpgradeRequired               = errors.New("upgrade required error")
	ErrStatusPreconditionRequired          = errors.New("precondition required error")
	ErrStatusTooManyRequests               = errors.New("too many requests error")
	ErrStatusRequestHeaderFieldsTooLarge   = errors.New("request header fields too large error")
	ErrStatusInternalServerError           = errors.New("internal server error")
	ErrStatusNotImplemented                = errors.New("not implemented error")
	ErrStatusBadGateway                    = errors.New("bad gateway error")
	ErrStatusServiceUnavailable            = errors.New("service unavailable error")
	ErrStatusGatewayTimeout                = errors.New("gateway timeout error")
	ErrStatusHTTPVersionNotSupported       = errors.New("http version not supported error")
	ErrStatusVariantAlsoNegotiates         = errors.New("variant also negotiates error")
	ErrStatusInsufficientStorage           = errors.New("insufficient storage error")
	ErrStatusLoopDetected                  = errors.New("loop detected error")
	ErrStatusNotExtended                   = errors.New("not extended error")
	ErrStatusNetworkAuthenticationRequired = errors.New("network authentication required error")
)

HTTP error variables provide typed error representations for all standard HTTP status codes. These errors enable CloudZero Agent components to handle HTTP failures with appropriate business logic, retry strategies, and error reporting patterns.

Error categorization supports:

  • Client errors (4xx): Request issues requiring caller correction
  • Server errors (5xx): Remote service issues enabling retry logic
  • Authentication errors: Credential and authorization failures
  • Rate limiting errors: Request throttling requiring backoff

These typed errors enable consistent error handling across CloudZero Agent HTTP integrations while providing clear error classification for monitoring and alerting systems.

Functions

func Do

func Do(
	ctx context.Context,
	client *http.Client,
	method string,
	headers map[string]string,
	queryParams map[string]string,
	uri string,
	body io.Reader,
) (int, error)

Do executes HTTP requests with comprehensive configuration and error handling for CloudZero Agent integrations. This function provides a standardized HTTP client interface that handles common patterns across CloudZero Agent external service communications while maintaining observability and reliability.

Request configuration:

  • Method: HTTP verb (GET, POST, PUT, DELETE) for the request
  • Headers: Custom headers including authentication and content type
  • Query parameters: URL parameters with proper encoding
  • Body: Request payload with streaming support
  • Context: Request context for cancellation and timeout management

Operational features:

  • Timeout management: Automatic 15-second timeout with context cancellation
  • User agent setting: Consistent CloudZero Agent identification
  • Error classification: Network error categorization for retry logic
  • Response processing: Status code extraction and error mapping
  • Request logging: Structured logging for debugging and monitoring

Error handling:

  • Network errors: Classified and wrapped with context information
  • HTTP errors: Status code-based error mapping
  • Timeout errors: Context cancellation and deadline exceeded handling
  • Connection errors: DNS, connection refused, and transport failures

This function serves as the foundation for CloudZero Agent HTTP communications, ensuring consistent behavior across all external service integrations while providing comprehensive error handling and operational visibility.

Returns the HTTP status code and any error encountered during request processing.

func ToError

func ToError(code int) error

ToError converts HTTP status codes to typed error values for consistent error handling. This function maps standard HTTP status codes to corresponding error types, enabling CloudZero Agent components to handle HTTP responses with appropriate business logic.

Error mapping approach:

  • Client errors (4xx): Map to specific client-side error types
  • Server errors (5xx): Map to server-side error types
  • Success codes (2xx): Return nil (no error)
  • Informational (1xx): Return nil (no error)
  • Redirection (3xx): Return nil (no error, handled by HTTP client)

Usage patterns:

  • API integration: Determine retry strategies based on error type
  • Authentication: Identify credential and authorization failures
  • Rate limiting: Detect throttling conditions requiring backoff
  • Service health: Monitor external service availability and performance

This conversion enables CloudZero Agent to implement sophisticated error handling strategies that distinguish between different types of HTTP failures and respond appropriately with retry logic, alerting, and graceful degradation.

Returns the corresponding error type for the status code, or nil for success codes.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL