github.com/txn2/txeh
import "github.com/txn2/txeh"
Package txeh provides /etc/hosts file management capabilities. It offers a simple interface for adding, removing, and querying hostname-to-IP mappings with thread-safe operations and cross-platform support (Linux, macOS, Windows).
Constants
Line type constants for HostFileLine.
const (
UNKNOWN = 0 // Unknown line type.
EMPTY = 10 // Empty line.
COMMENT = 20 // Comment line starting with #.
ADDRESS = 30 // Address line with IP and hostnames.
)DefaultMaxHostsPerLineWindows is the default maximum number of hostnames per line on Windows. Windows has a limitation where lines with more than ~9 hostnames may not resolve correctly.
const DefaultMaxHostsPerLineWindows = 9IP address family constants.
const (
IPFamilyV4 IPFamily = iota // IPv4 address family.
IPFamilyV6 // IPv6 address family.
)Functions
func ExecCommandFunc() func(string, ...string) *exec.Cmd
ExecCommandFunc returns the current exec command function. This is intended for test code that needs to save and restore the original.
func FlushDNSCache() error
FlushDNSCache flushes the operating system's DNS cache.
Platform commands (all are OS-provided utilities, not installable dependencies):
- macOS: dscacheutil -flushcache + killall -HUP mDNSResponder (ships with macOS)
- Linux: resolvectl flush-caches (systemd 239+) or systemd-resolve --flush-caches (older systemd). Returns ErrNoResolver if neither binary is found, which typically means the system does not cache DNS locally and hosts file changes take effect immediately.
- Windows: ipconfig /flushdns (ships with Windows)
Returns a *FlushError on failure, or nil on unsupported platforms where no resolver is detected.
func NewHosts(hc *HostsConfig) (*Hosts, error)
NewHosts returns a new hosts object.
func NewHostsDefault() (*Hosts, error)
NewHostsDefault returns a hosts object with default configuration.
func ParseHosts(path string) ([]HostFileLine, error)
ParseHosts reads and parses a hosts file from the given path.
func ParseHostsFromString(input string) ([]HostFileLine, error)
ParseHostsFromString parses hosts file content from a string.
func SetExecCommandFunc(fn func(string, ...string) *exec.Cmd)
SetExecCommandFunc replaces the exec command function. This is intended for test code that needs to mock command execution.
Types
type AddressLocations
AddressLocations maps an address to its location in the HFL.
type AddressLocations map[string]inttype FlushError
FlushError represents a DNS cache flush failure with platform context.
type FlushError struct {
Platform string
Command string
Err error
}Fields
Platform stringCommand stringErr error
func Error) Error() string
Error returns a human-readable error message.
func Unwrap() error
Unwrap returns the underlying error.
type HostFileLine
HostFileLine represents a single line in a hosts file.
type HostFileLine struct {
OriginalLineNum int
LineType int
Address string
Parts []string
Hostnames []string
Raw string
Trimmed string
Comment string
}Fields
OriginalLineNum intLineType intAddress stringParts []stringHostnames []stringRaw stringTrimmed stringComment string
type HostFileLines
HostFileLines is a slice of HostFileLine entries.
type HostFileLines []HostFileLinetype HostLocations
HostLocations maps a hostname to an original line number.
type HostLocations map[string]inttype Hosts
Hosts represents a parsed hosts file with thread-safe operations.
type Hosts struct {
*HostsConfig
// contains filtered or unexported fields
}Fields
*HostsConfig
func AddHost(addressRaw, hostRaw string)
AddHost adds a host to an address and removes the host from any existing address it may be associated with.
func AddHostWithComment(addressRaw, hostRaw, comment string)
AddHostWithComment adds a host to an address with an inline comment. The comment will appear after the hostnames on the line (e.g., "127.0.0.1 host # comment"). If the address already exists with the same comment, the host is appended to that line (respecting MaxHostsPerLine). If the address exists with a different comment, a new line is created with the specified comment.
func AddHosts(address string, hosts []string)
AddHosts adds an array of hosts to the first matching address it finds or creates the address and adds the hosts.
func AddHostsWithComment(address string, hosts []string, comment string)
AddHostsWithComment adds an array of hosts to an address with a comment. All hosts will share the same comment. If the address already exists with the same comment, hosts are appended to that line (respecting MaxHostsPerLine). If the address exists with a different comment, a new line is created.
func GetHostFileLines() HostFileLines
GetHostFileLines returns a copy of all parsed host file lines.
func HostAddressLookup(host string, ipFamily IPFamily) (found bool, address string, idx int)
HostAddressLookup returns true if the host is found, the address string, and the index of the host file line. This is part of the public API for consumers that need direct address lookups by IP family.
func ListAddressesByHost(hostname string, exact bool) [][]string
ListAddressesByHost returns a list of IPs associated with a given hostname.
func ListHostsByCIDR(cidr string) [][]string
ListHostsByCIDR returns a list of IPs and hostnames associated with a given CIDR.
func ListHostsByComment(comment string) []string
ListHostsByComment returns all hostnames on lines with the given comment.
func ListHostsByIP(address string) []string
ListHostsByIP returns a list of hostnames associated with a given IP address.
func Reload() error
Reload re-reads the hosts file from disk and replaces the in-memory state. This is part of the public API for consumers who manage long-lived Hosts instances.
func RemoveAddress(address string)
RemoveAddress removes all entries (lines) with the provided address.
func RemoveAddresses(addresses []string)
RemoveAddresses removes all entries (lines) with the provided address.
func RemoveByComment(comment string)
RemoveByComment removes all host entries that have the specified comment. This removes entire lines where the comment matches.
func RemoveByComments(comments []string)
RemoveByComments removes all host entries that have any of the specified comments. This removes entire lines where the comment matches. This is part of the public API for bulk comment-based cleanup (e.g., kubefwd teardown).
func RemoveCIDRs(cidrs []string) error
RemoveCIDRs Remove CIDR Range (Classless inter-domain routing) examples:
127.1.0.0/16 = 127.1.0.0 -> 127.1.255.255
127.1.27.0/24 = 127.1.27.0 -> 127.1.27.255func RemoveFirstAddress(address string) bool
RemoveFirstAddress removes the first entry (line) found with the provided address.
func RemoveFirstHost(host string) bool
RemoveFirstHost removes the first hostname entry found and returns true if successful.
func RemoveHost(host string)
RemoveHost removes all hostname entries of provided host.
func RemoveHosts(hosts []string)
RemoveHosts removes all hostname entries of the provided host slice.
func RenderHostsFile() string
RenderHostsFile returns the hosts file content as a formatted string.
func Save() error
Save renders and writes the hosts file to the configured write path.
func SaveAs(fileName string) error
SaveAs saves rendered hosts file to the filename specified.
type HostsConfig
HostsConfig contains configuration for reading and writing hosts files.
type HostsConfig struct {
ReadFilePath string
WriteFilePath string
// RawText for input. If RawText is set ReadFilePath, WriteFilePath are ignored. Use RenderHostsFile rather
// than save to get the results.
RawText *string
// MaxHostsPerLine limits the number of hostnames per line when adding hosts.
// This is useful for Windows which has a limitation of ~9 hostnames per line.
// Values:
// 0 = auto-detect (Windows: 9, others: unlimited)
// -1 = force unlimited (no limit)
// >0 = explicit limit
MaxHostsPerLine int
// AutoFlush triggers a DNS cache flush after every successful Save/SaveAs.
// Flush failures are returned as *FlushError, distinguishable via errors.As.
AutoFlush bool
}Fields
ReadFilePath stringWriteFilePath stringRawText *stringRawText for input. If RawText is set ReadFilePath, WriteFilePath are ignored. Use RenderHostsFile rather than save to get the results.
MaxHostsPerLine intMaxHostsPerLine limits the number of hostnames per line when adding hosts. This is useful for Windows which has a limitation of ~9 hostnames per line. Values: 0 = auto-detect (Windows: 9, others: unlimited) -1 = force unlimited (no limit)
0 = explicit limit
AutoFlush boolAutoFlush triggers a DNS cache flush after every successful Save/SaveAs. Flush failures are returned as *FlushError, distinguishable via errors.As.
type IPFamily
IPFamily represents the IP address family (IPv4 or IPv6).
type IPFamily int64