Documentation
¶
Overview ¶
Package httpcli provides advanced HTTP client management with DNS mapping capabilities.
This package offers a simplified API for creating and configuring HTTP clients with integrated DNS mapping support through the dns-mapper subpackage. It enables custom DNS resolution, TLS configuration, and flexible transport options.
Key features:
- Default HTTP client with sensible configuration
- Custom DNS mapping for hostname resolution override
- TLS/SSL configuration support
- Proxy configuration with authentication
- Thread-safe singleton DNS mapper management
- Automatic resource cleanup and lifecycle management
Basic usage:
import "github.com/nabbar/golib/httpcli"
// Get default HTTP client
client := httpcli.GetClient()
// Make HTTP request
resp, err := client.Get("https://api.example.com")
if err != nil {
panic(err)
}
defer resp.Body.Close()
With custom DNS mapping:
import (
"github.com/nabbar/golib/httpcli"
htcdns "github.com/nabbar/golib/httpcli/dns-mapper"
)
// Create DNS mapper
cfg := &htcdns.Config{
DNSMapper: map[string]string{
"api.example.com:443": "192.168.1.100:8443",
},
}
mapper := htcdns.New(context.Background(), cfg, nil, nil)
defer mapper.Close()
// Set as default
httpcli.SetDefaultDNSMapper(mapper)
// Get client with custom DNS mapping
client := httpcli.GetClient()
Index ¶
Constants ¶
const ( ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgHttpCli // At least one given parameter is empty ErrorParamInvalid // At least one given parameter is invalid ErrorValidatorError // Configuration validation failed ErrorClientTransportHttp2 // HTTP/2 transport configuration error )
Error codes for HTTP client operations. These errors are registered with the golib/errors package for consistent error handling.
const ( // ClientTimeout5Sec is a default timeout constant of 5 seconds for HTTP client operations. ClientTimeout5Sec = 5 * time.Second // nolint )
Variables ¶
This section is empty.
Functions ¶
func DefaultConfig ¶ added in v1.10.0
DefaultConfig returns the default DNS mapper configuration in JSON format. The indent parameter specifies the indentation string for pretty-printing.
This is a convenience function that delegates to the dns-mapper package's DefaultConfig function. The returned JSON can be used as a template for creating custom configurations.
Parameters:
- indent: String to use for indentation (e.g., " " for 2 spaces)
Returns a byte slice containing the JSON-formatted default configuration.
Example:
config := httpcli.DefaultConfig(" ")
fmt.Println(string(config))
func DefaultDNSMapper ¶ added in v1.13.10
DefaultDNSMapper returns the default DNS mapper instance. If no DNS mapper has been set via SetDefaultDNSMapper, this function creates a new one using initDNSMapper with default configuration.
This function is thread-safe and uses atomic operations to ensure concurrent access is handled correctly. The DNS mapper is created only once on first access (lazy initialization).
Returns the global DNS mapper instance that can be used to:
- Add custom hostname-to-IP mappings
- Create HTTP clients with custom DNS resolution
- Configure custom transport options
Example:
mapper := httpcli.DefaultDNSMapper()
mapper.Add("api.example.com:443", "192.168.1.100:8443")
client := httpcli.GetClient()
func GetClient ¶
GetClient returns an HTTP client configured with the default DNS mapper. This is the primary entry point for obtaining HTTP clients in this package.
The returned client includes:
- Custom DNS resolution via the default DNS mapper
- Connection pooling and keep-alive
- Configured transport with timeouts
- HTTP/2 support (if enabled in DNS mapper config)
The client is safe for concurrent use and reuses connections for efficiency. Always reuse the returned client for multiple requests instead of calling GetClient repeatedly.
Example:
client := httpcli.GetClient()
resp, err := client.Get("https://api.example.com")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
func SetDefaultDNSMapper ¶ added in v1.13.10
SetDefaultDNSMapper replaces the default DNS mapper with a custom instance. The previous DNS mapper (if any) is automatically closed to free resources.
This function is thread-safe and uses atomic operations to ensure the swap is performed correctly even under concurrent access.
Parameters:
- d: The new DNS mapper instance to use as default. If nil, the function returns without action.
The old DNS mapper is automatically closed when replaced, ensuring proper cleanup of goroutines, timers, and other resources associated with the old instance.
Example:
// Create custom DNS mapper
cfg := &htcdns.Config{
DNSMapper: map[string]string{
"api.example.com:443": "192.168.1.100:8443",
},
}
customMapper := htcdns.New(context.Background(), cfg, nil, nil)
// Set as default (old mapper is automatically closed)
httpcli.SetDefaultDNSMapper(customMapper)
Types ¶
type FctHttpClient ¶ added in v1.10.0
FctHttpClient is a function type that returns an HTTP client. This type is used for dependency injection and testing purposes.
type FctHttpClientSrv ¶ added in v1.13.10
FctHttpClientSrv is a function type that returns an HTTP client configured for a specific server. The servername parameter can be used to select different client configurations.
type HttpClient ¶ added in v1.13.7
HttpClient defines the minimal interface for HTTP operations. This interface is compatible with *http.Client and can be used for testing with mock clients.
type OptionForceIP ¶ added in v1.9.0
type OptionForceIP struct {
Enable bool `json:"enable" yaml:"enable" toml:"enable" mapstructure:"enable"` // Enable ForceIP feature
Net libptc.NetworkProtocol `json:"net,omitempty" yaml:"net,omitempty" toml:"net,omitempty" mapstructure:"net,omitempty"` // Network protocol (IPv4/IPv6)
IP string `json:"ip,omitempty" yaml:"ip,omitempty" toml:"ip,omitempty" mapstructure:"ip,omitempty"` // Specific IP address to bind to
Local string `json:"local,omitempty" yaml:"local,omitempty" toml:"local,omitempty" mapstructure:"local,omitempty"` // Local address for binding
}
OptionForceIP configures network interface binding for HTTP connections. This allows forcing connections through specific network interfaces or IP addresses, useful for multi-homed systems or testing specific network paths.
type OptionProxy ¶ added in v1.11.3
type OptionProxy struct {
Enable bool `json:"enable" yaml:"enable" toml:"enable" mapstructure:"enable"` // Enable proxy
Endpoint *url.URL `json:"endpoint" yaml:"endpoint" toml:"endpoint" mapstructure:"endpoint"` // Proxy server URL
Username string `json:"username" yaml:"username" toml:"username" mapstructure:"username"` // Proxy authentication username
Password string `json:"password" yaml:"password" toml:"password" mapstructure:"password"` // Proxy authentication password
}
OptionProxy configures HTTP/HTTPS proxy settings with authentication support. Supports both authenticated and unauthenticated proxies.
type OptionTLS ¶ added in v1.9.0
type OptionTLS struct {
Enable bool `json:"enable" yaml:"enable" toml:"enable" mapstructure:"enable"` // Enable TLS/SSL
Config libtls.Config `json:"tls" yaml:"tls" toml:"tls" mapstructure:"tls"` // TLS configuration (certificates, validation, etc.)
}
OptionTLS configures TLS/SSL settings for HTTPS connections. Provides fine-grained control over certificate validation, cipher suites, and other TLS-related parameters.
type Options ¶ added in v1.9.0
type Options struct {
Timeout time.Duration `json:"timeout" yaml:"timeout" toml:"timeout" mapstructure:"timeout"`
DisableKeepAlive bool `json:"disable-keep-alive" yaml:"disable-keep-alive" toml:"disable-keep-alive" mapstructure:"disable-keep-alive"`
DisableCompression bool `json:"disable-compression" yaml:"disable-compression" toml:"disable-compression" mapstructure:"disable-compression"`
Http2 bool `json:"http2" yaml:"http2" toml:"http2" mapstructure:"http2"`
TLS OptionTLS `json:"tls" yaml:"tls" toml:"tls" mapstructure:"tls"`
ForceIP OptionForceIP `json:"force_ip" yaml:"force_ip" toml:"force_ip" mapstructure:"force_ip"`
Proxy OptionProxy `json:"proxy" yaml:"proxy" toml:"proxy" mapstructure:"proxy"`
}
Options defines the complete HTTP client configuration. This structure provides comprehensive control over client behavior including timeouts, protocol options, security settings, and network configuration.
All fields support JSON, YAML, TOML, and Viper configuration formats through struct tags.
func (Options) GetClient ¶ added in v1.9.0
GetClient creates and returns an HTTP client based on the options configuration. Currently, this method returns the default client and ignores the parameters.
Parameters:
- def: Default TLS configuration (currently unused)
- servername: Server name for SNI (currently unused)
Returns the default HTTP client configured with the global DNS mapper, along with a nil error.
Note: This method is provided for interface compatibility and may be enhanced in future versions to use the provided parameters.
func (Options) Validate ¶ added in v1.9.0
Validate checks if the Options configuration is valid. It uses struct tags and the validator package to ensure all fields meet their specified constraints.
Returns a liberr.Error containing all validation errors, or nil if validation succeeds. The error includes detailed information about which fields failed validation and why.
Example:
opts := httpcli.Options{
Timeout: 30 * time.Second,
}
if err := opts.Validate(); err != nil {
log.Fatal("Invalid configuration:", err)
}
Directories
¶
| Path | Synopsis |
|---|---|
|
Package dns_mapper provides custom DNS hostname mapping and dialer functionality for HTTP clients.
|
Package dns_mapper provides custom DNS hostname mapping and dialer functionality for HTTP clients. |