Documentation
¶
Overview ¶
Package dns_mapper provides custom DNS hostname mapping and dialer functionality for HTTP clients.
This package allows overriding DNS resolution by mapping hostnames to specific IP addresses, enabling use cases such as testing, development environments, and custom routing without modifying system DNS or /etc/hosts files.
Key features:
- Hostname-to-IP mapping with wildcard support
- Automatic cache management with configurable cleanup
- Custom dialer for net.Conn operations
- Seamless http.Transport integration
- Thread-safe concurrent operations
- TLS configuration support
Basic usage:
import (
"context"
dnsmapper "github.com/nabbar/golib/httpcli/dns-mapper"
)
// Create DNS mapper
cfg := &dnsmapper.Config{
DNSMapper: map[string]string{
"api.example.com:443": "192.168.1.100:8443",
},
}
mapper := dnsmapper.New(context.Background(), cfg, nil, nil)
defer mapper.Close()
// Create HTTP client with custom DNS
client := mapper.DefaultClient()
resp, _ := client.Get("https://api.example.com")
Index ¶
Constants ¶
const ( ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgHttpCliDNSMapper // 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 DNS mapper operations. These errors are registered with the golib/errors package for consistent error handling.
Variables ¶
This section is empty.
Functions ¶
func DefaultConfig ¶
DefaultConfig generates a default DNS mapper configuration in JSON format. The returned configuration includes sensible defaults for all settings and can be used as a template for custom configurations.
Parameters:
- indent: String to use for JSON indentation (e.g., " " for 2 spaces)
Returns a byte slice containing the JSON-formatted default configuration.
Default settings include:
- Example DNS mapping (localhost → 127.0.0.1)
- 3-minute cache cleanup interval
- 50 max idle connections
- 30-second timeouts
- HTTP/2 enabled
Example:
config := DefaultConfig(" ")
fmt.Println(string(config))
func GetRootCaCert ¶ added in v1.17.0
GetRootCaCert parses and combines multiple root CA certificates into a single Cert object. This utility function is used to aggregate root CA certificates for TLS configuration.
Parameters:
- fct: Function that returns a slice of PEM-encoded root CA certificates
Returns a combined Cert object containing all parsed certificates, or nil if the function returns an empty slice.
Types ¶
type Config ¶
type Config struct {
DNSMapper map[string]string `json:"dns-mapper,omitempty" yaml:"dns-mapper,omitempty" toml:"dns-mapper,omitempty" mapstructure:"dns-mapper,omitempty"`
TimerClean libdur.Duration `json:"timer-clean,omitempty" yaml:"timer-clean,omitempty" toml:"timer-clean,omitempty" mapstructure:"timer-clean,omitempty"`
Transport TransportConfig `json:"transport,omitempty" yaml:"transport,omitempty" toml:"transport,omitempty" mapstructure:"transport,omitempty"`
TLSConfig *tls.Config `json:"tls-config,omitempty" yaml:"tls-config,omitempty" toml:"tls-config,omitempty" mapstructure:"tls-config,omitempty"`
}
Config holds the complete DNS mapper configuration. This structure combines DNS hostname mappings with HTTP transport settings and cache management options.
All fields support JSON, YAML, TOML, and Viper configuration through struct tags.
func (Config) New ¶
func (o Config) New(ctx context.Context, fct libtls.FctRootCACert, msg FuncMessage) DNSMapper
New creates a new DNSMapper instance from this configuration. This is a convenience method that calls the package-level New function with this configuration.
Parameters:
- ctx: Context for lifecycle management and cancellation
- fct: Function to retrieve root CA certificates for TLS (nil will use empty function)
- msg: Callback function for messages/logging (nil will use no-op function)
Returns a fully initialized DNSMapper instance based on this configuration.
Example:
cfg := Config{
DNSMapper: map[string]string{
"api.example.com:443": "192.168.1.100:8443",
},
}
mapper := cfg.New(context.Background(), nil, nil)
defer mapper.Close()
func (Config) Validate ¶
Validate checks if the Config is valid according to struct tag constraints. It uses the validator package to verify all fields meet their specified requirements.
Returns a liberr.Error containing all validation errors, or nil if validation succeeds. The error includes detailed information about which fields failed validation.
Example:
cfg := Config{
DNSMapper: map[string]string{
"api.example.com:443": "192.168.1.100:8443",
},
}
if err := cfg.Validate(); err != nil {
log.Fatal("Invalid configuration:", err)
}
type DNSMapper ¶
type DNSMapper interface {
// Add registers a new DNS mapping from hostname:port to IP:port.
// Supports wildcards: "*.example.com:*" or "api.example.com:*"
Add(from, to string)
// Get retrieves the mapped address for a given hostname:port.
// Returns empty string if no mapping exists.
Get(from string) string
// Del removes a DNS mapping.
Del(from string)
// Len returns the number of active DNS mappings.
Len() int
// Walk iterates over all DNS mappings, calling the provided function for each.
// If the function returns false, iteration stops.
Walk(func(from, to string) bool)
// Clean parses an endpoint string into hostname and port components.
// Returns host, port, and error if parsing fails.
Clean(endpoint string) (host string, port string, err error)
// Search resolves an endpoint using DNS mappings without caching.
// Returns the mapped address or the original endpoint if no mapping exists.
Search(endpoint string) (string, error)
// SearchWithCache resolves an endpoint using DNS mappings with caching.
// Cached results improve performance for repeated lookups.
SearchWithCache(endpoint string) (string, error)
// DialContext creates a network connection using custom DNS resolution.
// This is the custom dialer function used by HTTP transports.
DialContext(ctx context.Context, network, address string) (net.Conn, error)
// Transport creates a custom HTTP transport with the given configuration.
Transport(cfg TransportConfig) *http.Transport
// TransportWithTLS creates a custom HTTP transport with TLS configuration.
TransportWithTLS(cfg TransportConfig, ssl *tls.Config) *http.Transport
// Client creates an HTTP client with custom transport configuration.
Client(cfg TransportConfig) *http.Client
// DefaultTransport returns the default HTTP transport for this DNS mapper.
DefaultTransport() *http.Transport
// DefaultClient returns the default HTTP client for this DNS mapper.
DefaultClient() *http.Client
// GetConfig returns the current DNS mapper configuration.
GetConfig() Config
// RegisterTransport registers a custom HTTP transport for the DNS mapper to use.
RegisterTransport(t *http.Transport)
// TimeCleaner starts a background goroutine that periodically cleans the cache.
// The cleanup runs at the specified duration interval until the context is cancelled.
TimeCleaner(ctx context.Context, dur time.Duration)
// Close stops the cache cleaner and releases resources.
// Should be called when the DNS mapper is no longer needed.
Close() error
}
DNSMapper defines the interface for DNS mapping and HTTP client creation. All methods are thread-safe and can be called concurrently.
func New ¶
func New(ctx context.Context, cfg *Config, fct libtls.FctRootCACert, msg FuncMessage) DNSMapper
New creates and initializes a new DNS mapper instance with the given configuration.
This function sets up the DNS mapper with the provided configuration, including:
- Initial DNS hostname mappings
- HTTP transport configuration
- Cache cleanup timer
- Optional root CA certificates for TLS
- Optional message callback for logging
Parameters:
- ctx: Context for lifecycle management and cancellation
- cfg: DNS mapper configuration (nil will use default configuration)
- fct: Function to retrieve root CA certificates for TLS (nil will use empty function)
- msg: Callback function for messages/logging (nil will use no-op function)
Returns a fully initialized DNSMapper instance. The caller should call Close() when done to clean up resources.
Example:
cfg := &Config{
DNSMapper: map[string]string{
"api.example.com:443": "192.168.1.100:8443",
},
TimerClean: libdur.ParseDuration(5 * time.Minute),
}
mapper := New(context.Background(), cfg, nil, func(msg string) {
log.Println("DNS Mapper:", msg)
})
defer mapper.Close()
type FuncMessage ¶ added in v1.13.12
type FuncMessage func(msg string)
FuncMessage is a callback function type for logging or message handling. It receives string messages from the DNS mapper during operations.
type TransportConfig ¶
type TransportConfig struct {
Proxy *url.URL `json:"proxy,omitempty" yaml:"proxy,omitempty" toml:"proxy,omitempty" mapstructure:"proxy,omitempty"`
TLSConfig *libtls.Config `json:"tls-config,omitempty" yaml:"tls-config,omitempty" toml:"tls-config,omitempty" mapstructure:"tls-config,omitempty"`
DisableHTTP2 bool `json:"disable-http2" yaml:"disable-http2" toml:"disable-http2" mapstructure:"disable-http2"`
DisableKeepAlive bool `json:"disable-keepalive" yaml:"disable-keepalive" toml:"disable-keepalive" mapstructure:"disable-keepalive"`
DisableCompression bool `json:"disable-compression" yaml:"disable-compression" toml:"disable-compression" mapstructure:"disable-compression"`
MaxIdleConns int `json:"max-idle-conns" yaml:"max-idle-conns" toml:"max-idle-conns" mapstructure:"max-idle-conns"`
MaxIdleConnsPerHost int `` /* 131-byte string literal not displayed */
MaxConnsPerHost int `json:"max-conns-per-host" yaml:"max-conns-per-host" toml:"max-conns-per-host" mapstructure:"max-conns-per-host"`
TimeoutGlobal libdur.Duration `` /* 135-byte string literal not displayed */
TimeoutKeepAlive libdur.Duration `` /* 127-byte string literal not displayed */
TimeoutTLSHandshake libdur.Duration `` /* 163-byte string literal not displayed */
TimeoutExpectContinue libdur.Duration `` /* 171-byte string literal not displayed */
TimeoutIdleConn libdur.Duration `` /* 147-byte string literal not displayed */
TimeoutResponseHeader libdur.Duration `` /* 172-byte string literal not displayed */
}
TransportConfig defines HTTP transport configuration options. This structure provides fine-grained control over HTTP transport behavior including connection pooling, timeouts, and protocol features.
All fields support JSON, YAML, TOML, and Viper configuration through struct tags.