httpclient

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2025 License: MIT Imports: 3 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidName         = errors.New("client name cannot be empty")
	ErrInvalidBaseURL      = errors.New("base URL cannot be empty")
	ErrInvalidTimeout      = errors.New("timeout must be greater than 0")
	ErrInvalidMaxRetries   = errors.New("max retries cannot be negative")
	ErrInvalidMultiplier   = errors.New("multiplier must be greater than 0")
	ErrInvalidFailureRatio = errors.New("failure ratio must be between 0.0 and 1.0")
)

Functions

This section is empty.

Types

type AuthConfig

type AuthConfig struct {
	Type     AuthType `json:"type"`
	Username string   `json:"username,omitempty"`
	Password string   `json:"password,omitempty"`
	Token    string   `json:"token,omitempty"`
	APIKey   string   `json:"api_key,omitempty"`
	Header   string   `json:"header,omitempty"` // Para API key custom header
}

AuthConfig configura la autenticación

type AuthType

type AuthType string

AuthType define el tipo de autenticación

const (
	AuthNone   AuthType = "none"
	AuthBasic  AuthType = "basic"
	AuthBearer AuthType = "bearer"
	AuthAPIKey AuthType = "api_key"
	AuthCustom AuthType = "custom"
)

type CircuitBreakerConfig

type CircuitBreakerConfig struct {
	MaxRequests             uint32        `json:"max_requests"`
	Interval                time.Duration `json:"interval"`
	Timeout                 time.Duration `json:"timeout"`
	FailureThreshold        uint32        `json:"failure_threshold"`
	FailureRatio            float64       `json:"failure_ratio"`
	MinimumRequestThreshold uint32        `json:"minimum_request_threshold"`
}

CircuitBreakerConfig configura el circuit breaker

type Config

type Config struct {
	// Name es el nombre del cliente para logs y métricas
	Name string `json:"name"`

	// BaseURL es la URL base para todas las requests
	BaseURL string `json:"base_url"`

	// Timeout es el timeout total para requests
	Timeout time.Duration `json:"timeout"`

	// RetryConfig configura el comportamiento de retry
	RetryConfig RetryConfig `json:"retry_config"`

	// CircuitBreakerEnabled habilita circuit breaker
	CircuitBreakerEnabled bool `json:"circuit_breaker_enabled"`

	// CircuitBreakerConfig configuración del circuit breaker
	CircuitBreakerConfig CircuitBreakerConfig `json:"circuit_breaker_config"`

	// Headers por defecto para todas las requests
	DefaultHeaders map[string]string `json:"default_headers"`

	// UserAgent personalizado
	UserAgent string `json:"user_agent"`

	// TLS Configuration
	InsecureSkipVerify bool `json:"insecure_skip_verify"`

	// Connection pooling
	MaxIdleConns        int           `json:"max_idle_conns"`
	MaxIdleConnsPerHost int           `json:"max_idle_conns_per_host"`
	IdleConnTimeout     time.Duration `json:"idle_conn_timeout"`

	// Timeouts específicos
	DialTimeout           time.Duration `json:"dial_timeout"`
	KeepAlive             time.Duration `json:"keep_alive"`
	TLSHandshakeTimeout   time.Duration `json:"tls_handshake_timeout"`
	ResponseHeaderTimeout time.Duration `json:"response_header_timeout"`
	ExpectContinueTimeout time.Duration `json:"expect_continue_timeout"`

	// Logging
	LogRequests  bool `json:"log_requests"`
	LogResponses bool `json:"log_responses"`
	LogBody      bool `json:"log_body"`

	// Metrics
	EnableMetrics bool `json:"enable_metrics"`

	// Authentication
	AuthConfig AuthConfig `json:"auth_config"`
}

Config define la configuración de un HTTP client resiliente

func DefaultConfig

func DefaultConfig(name, baseURL string) *Config

DefaultConfig retorna configuración por defecto

func ExternalServiceConfig

func ExternalServiceConfig(name, baseURL string) *Config

ExternalServiceConfig retorna configuración para servicios externos

func FastConfig

func FastConfig(name, baseURL string) *Config

FastConfig retorna configuración optimizada para velocidad

func InternalServiceConfig

func InternalServiceConfig(name, baseURL string) *Config

InternalServiceConfig retorna configuración para servicios internos

func ResilientConfig

func ResilientConfig(name, baseURL string) *Config

ResilientConfig retorna configuración optimizada para resiliencia

func (*Config) Validate

func (c *Config) Validate() error

Validate valida la configuración

func (*Config) WithAuth

func (c *Config) WithAuth(authType AuthType, credentials map[string]string) *Config

WithAuth configura autenticación

func (*Config) WithCircuitBreaker

func (c *Config) WithCircuitBreaker(enabled bool) *Config

WithCircuitBreaker habilita/deshabilita circuit breaker

func (*Config) WithHeaders

func (c *Config) WithHeaders(headers map[string]string) *Config

WithHeaders añade headers por defecto

func (*Config) WithLogging

func (c *Config) WithLogging(requests, responses, body bool) *Config

WithLogging configura logging

func (*Config) WithRetries

func (c *Config) WithRetries(maxRetries int) *Config

WithRetries configura número de retries

func (*Config) WithTimeout

func (c *Config) WithTimeout(timeout time.Duration) *Config

WithTimeout configura timeout

type RetryConfig

type RetryConfig struct {
	Enabled     bool          `json:"enabled"`
	MaxRetries  int           `json:"max_retries"`
	InitialWait time.Duration `json:"initial_wait"`
	MaxWait     time.Duration `json:"max_wait"`
	Multiplier  float64       `json:"multiplier"`
	Jitter      bool          `json:"jitter"`

	// RetryableStatusCodes códigos de estado que permiten retry
	RetryableStatusCodes []int `json:"retryable_status_codes"`

	// RetryableErrors errores que permiten retry
	RetryableErrors []string `json:"retryable_errors"`

	// OnRetry callback ejecutado en cada retry
	OnRetry func(attempt int, err error) `json:"-"`
}

RetryConfig configura el comportamiento de retry

Jump to

Keyboard shortcuts

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