Documentation
¶
Overview ¶
Package netutil provides network utilities:
- Port availability: IsPortAvailable, FindAvailablePort, FreePort
- IP address helpers: LocalIPs, PublicIP, IsPrivateIP, IsLoopback
- HTTP client with retry, timeout, and circuit breaker
- TCP/UDP utilities: dial, listen, ping, forward
Quick start ¶
// Check if a port is available
ok := netutil.IsPortAvailable("tcp", 8080)
// Get local IP
ip := netutil.LocalIP()
// HTTP client with retry
client := netutil.NewHTTPClient(netutil.HTTPClientConfig{
Timeout: 10 * time.Second,
MaxRetries: 3,
RetryInterval: time.Second,
})
resp, err := client.Get("https://example.com")
Index ¶
- func AllIPs() []string
- func FindAvailablePort(start, end int) (int, error)
- func FindAvailablePorts(start, n int) ([]int, error)
- func FreePort() (int, error)
- func FreeUDPPort() (int, error)
- func IPRange(cidr string) (start, end string, err error)
- func InterfaceIPs(name string) ([]string, error)
- func Interfaces() ([]string, error)
- func IsLoopback(ipStr string) bool
- func IsPortAvailable(network string, port int) bool
- func IsPrivateIP(ipStr string) bool
- func IsPublicIP(ipStr string) bool
- func IsTCPPortAvailable(port int) bool
- func IsTCPReachable(addr string, timeout time.Duration) bool
- func IsUDPPortAvailable(port int) bool
- func LocalIP() string
- func LocalIPs() []string
- func LocalIPv6s() []string
- func LookupCNAME(hostname string) (string, error)
- func LookupHost(hostname string) ([]string, error)
- func LookupMX(domain string) ([]*net.MX, error)
- func LookupTXT(domain string) ([]string, error)
- func MACAddress(name string) (string, error)
- func NewStandardHTTPClient(cfg HTTPClientConfig) *http.Client
- func OutboundIP(target string) (string, error)
- func PublicIP() string
- func PublicIPWithProvider(url string) string
- func ResolveIP(hostname string) string
- func TCPConnect(addr string, timeout time.Duration) error
- func TCPExchange(addr string, data []byte, timeout time.Duration) ([]byte, error)
- func TCPForward(dst, src net.Conn) error
- func TCPPing(addr string, timeout time.Duration) (time.Duration, error)
- func UDPExchange(addr string, data []byte, timeout time.Duration) ([]byte, error)
- func UDPSend(addr string, data []byte) error
- type CircuitBreaker
- type CircuitState
- type HTTPClient
- func (c *HTTPClient) Do(req *http.Request) (*http.Response, error)
- func (c *HTTPClient) Get(url string) (*http.Response, error)
- func (c *HTTPClient) GetWithContext(ctx context.Context, url string) (*http.Response, error)
- func (c *HTTPClient) Post(url, contentType string, body io.Reader) (*http.Response, error)
- func (c *HTTPClient) PostWithContext(ctx context.Context, url, contentType string, body io.Reader) (*http.Response, error)
- type HTTPClientConfig
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AllIPs ¶
func AllIPs() []string
AllIPs returns all IP addresses (v4 and v6) including loopback.
func FindAvailablePort ¶
FindAvailablePort finds the first available TCP port starting from start. Returns an error if no port is found within [start, end].
func FindAvailablePorts ¶
FindAvailablePorts finds n available TCP ports starting from start.
func FreePort ¶
FreePort returns a free TCP port provided by the OS. The port is not reserved; another process may grab it.
func FreeUDPPort ¶
FreeUDPPort returns a free UDP port provided by the OS.
func IPRange ¶
IPRange returns the start and end IPs of a CIDR range. Returns an error if the CIDR is invalid.
func InterfaceIPs ¶
InterfaceIPs returns all IP addresses for the named interface.
func Interfaces ¶
Interfaces returns all network interface names.
func IsLoopback ¶
IsLoopback returns true if the IP is a loopback address.
func IsPortAvailable ¶
IsPortAvailable checks if a TCP/UDP port is available on localhost.
func IsPrivateIP ¶
IsPrivateIP returns true if the IP is in a private range. Private ranges: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7.
func IsPublicIP ¶
IsPublicIP returns true if the IP is not private and not loopback.
func IsTCPPortAvailable ¶
IsTCPPortAvailable checks if a TCP port is available.
func IsTCPReachable ¶
IsTCPReachable returns true if a TCP address is reachable.
func IsUDPPortAvailable ¶
IsUDPPortAvailable checks if a UDP port is available.
func LocalIP ¶
func LocalIP() string
LocalIP returns the first non-loopback IPv4 address of the machine. Returns "" if no non-loopback address is found.
func LocalIPs ¶
func LocalIPs() []string
LocalIPs returns all non-loopback IPv4 addresses of the machine.
func LocalIPv6s ¶
func LocalIPv6s() []string
LocalIPv6s returns all non-loopback IPv6 addresses of the machine.
func LookupCNAME ¶
LookupCNAME resolves the CNAME record for a hostname.
func LookupHost ¶
LookupHost resolves a hostname to IP addresses.
func MACAddress ¶
MACAddress returns the MAC address of the named interface. Returns "" if the interface has no MAC address.
func NewStandardHTTPClient ¶ added in v0.2.0
func NewStandardHTTPClient(cfg HTTPClientConfig) *http.Client
NewStandardHTTPClient returns a plain *http.Client configured with timeout, transport, redirect policy and cookie jar from cfg. Unlike NewHTTPClient it does NOT wrap the client with retry or circuit-breaker logic — useful for callers (e.g. security scanners) that need to observe raw responses without retry masking.
func OutboundIP ¶
OutboundIP returns the local IP address used to reach the given target. If target is empty, it uses "8.8.8.8:80" as a public target.
func PublicIP ¶
func PublicIP() string
PublicIP fetches the public IP address using an external service. Uses https://api.ipify.org by default. Returns "" on error.
func PublicIPWithProvider ¶
PublicIPWithProvider fetches the public IP using the given provider URL. The response body should be just the IP address.
func ResolveIP ¶
ResolveIP resolves a hostname to a single IPv4 address. Returns "" if no IPv4 address is found.
func TCPConnect ¶
TCPConnect attempts to connect to a TCP address with a timeout. Returns nil if connection succeeds.
func TCPExchange ¶
TCPExchange connects to a TCP address, sends data, and reads the response. Returns the response bytes.
func TCPForward ¶
TCPForward forwards data between two TCP connections (bidirectional). Blocks until either connection is closed.
func TCPPing ¶
TCPPing checks if a TCP address is reachable within the timeout. Returns the round-trip duration.
func UDPExchange ¶
UDPExchange sends data to a UDP address and reads the response.
Types ¶
type CircuitBreaker ¶
type CircuitBreaker struct {
// contains filtered or unexported fields
}
CircuitBreaker implements a simple circuit breaker.
func NewCircuitBreaker ¶
func NewCircuitBreaker(threshold int, timeout time.Duration) *CircuitBreaker
NewCircuitBreaker creates a circuit breaker that opens after threshold consecutive failures and stays open for timeout before entering half-open.
func (*CircuitBreaker) Allow ¶
func (cb *CircuitBreaker) Allow() bool
Allow returns true if a request is allowed through.
func (*CircuitBreaker) Failures ¶
func (cb *CircuitBreaker) Failures() int
Failures returns the current failure count.
func (*CircuitBreaker) RecordFailure ¶
func (cb *CircuitBreaker) RecordFailure()
RecordFailure records a failed request.
func (*CircuitBreaker) RecordSuccess ¶
func (cb *CircuitBreaker) RecordSuccess()
RecordSuccess records a successful request.
func (*CircuitBreaker) Reset ¶
func (cb *CircuitBreaker) Reset()
Reset resets the circuit breaker to closed state.
func (*CircuitBreaker) State ¶
func (cb *CircuitBreaker) State() CircuitState
State returns the current circuit breaker state.
type CircuitState ¶
type CircuitState int
CircuitState represents the state of a circuit breaker.
const ( CircuitClosed CircuitState = iota // normal operation CircuitOpen // rejecting requests CircuitHalfOpen // testing if service is back )
type HTTPClient ¶
type HTTPClient struct {
// contains filtered or unexported fields
}
HTTPClient wraps http.Client with retry and circuit breaker support.
func NewHTTPClient ¶
func NewHTTPClient(cfg HTTPClientConfig) *HTTPClient
NewHTTPClient creates a new retry-enabled HTTP client.
func (*HTTPClient) Get ¶
func (c *HTTPClient) Get(url string) (*http.Response, error)
Get sends a GET request.
func (*HTTPClient) GetWithContext ¶
GetWithContext sends a GET request with context.
type HTTPClientConfig ¶
type HTTPClientConfig struct {
Timeout time.Duration // total request timeout (default 30s)
MaxRetries int // max retry attempts (default 3)
RetryInterval time.Duration // base interval between retries (default 1s)
RetryMaxWait time.Duration // max wait between retries (default 30s)
RetryableStatus map[int]bool // status codes that trigger retry (default 429, 500, 502, 503, 504)
Transport *http.Transport // custom transport (optional)
CircuitBreaker *CircuitBreaker // optional circuit breaker
CheckRedirect func(req *http.Request, via []*http.Request) error // optional redirect policy
Jar http.CookieJar // optional cookie jar
}
HTTPClientConfig configures the retry HTTP client.