chore: cleanup hostValue code

This commit is contained in:
wwqgtxx
2026-02-07 12:02:47 +08:00
parent 32799662ad
commit 022f677385
2 changed files with 26 additions and 28 deletions

View File

@@ -8,7 +8,6 @@ import (
"strings"
_ "unsafe"
"github.com/metacubex/mihomo/common/utils"
"github.com/metacubex/mihomo/component/resolver/hosts"
"github.com/metacubex/mihomo/component/trie"
"github.com/metacubex/randv2"
@@ -66,37 +65,35 @@ type HostValue struct {
Domain string
}
func NewHostValue(value any) (HostValue, error) {
func NewHostValue(value []string) (HostValue, error) {
isDomain := true
ips := make([]netip.Addr, 0)
ips := make([]netip.Addr, 0, len(value))
domain := ""
if valueArr, err := utils.ToStringSlice(value); err != nil {
return HostValue{}, err
} else {
if len(valueArr) > 1 {
switch len(value) {
case 0:
return HostValue{}, errors.New("value is empty")
case 1:
host := value[0]
if ip, err := netip.ParseAddr(host); err == nil {
ips = append(ips, ip.Unmap())
isDomain = false
for _, str := range valueArr {
if ip, err := netip.ParseAddr(str); err == nil {
ips = append(ips, ip.Unmap())
} else {
return HostValue{}, err
}
}
} else if len(valueArr) == 1 {
host := valueArr[0]
if ip, err := netip.ParseAddr(host); err == nil {
} else {
domain = host
}
default: // > 1
isDomain = false
for _, str := range value {
if ip, err := netip.ParseAddr(str); err == nil {
ips = append(ips, ip.Unmap())
isDomain = false
} else {
domain = host
return HostValue{}, err
}
}
}
if isDomain {
return NewHostValueByDomain(domain)
} else {
return NewHostValueByIPs(ips)
}
return NewHostValueByIPs(ips)
}
func NewHostValueByIPs(ips []netip.Addr) (HostValue, error) {

View File

@@ -1115,22 +1115,23 @@ func parseHosts(cfg *RawConfig) (*trie.DomainTrie[resolver.HostValue], error) {
if len(cfg.Hosts) != 0 {
for domain, anyValue := range cfg.Hosts {
if str, ok := anyValue.(string); ok && str == "lan" {
hosts, err := utils.ToStringSlice(anyValue)
if err != nil {
return nil, err
}
if len(hosts) == 1 && hosts[0] == "lan" {
if addrs, err := net.InterfaceAddrs(); err != nil {
log.Errorln("insert lan to host error: %s", err)
} else {
ips := make([]netip.Addr, 0)
hosts = make([]string, 0, len(addrs))
for _, addr := range addrs {
if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() && !ipnet.IP.IsLinkLocalUnicast() {
if ip, err := netip.ParseAddr(ipnet.IP.String()); err == nil {
ips = append(ips, ip)
}
hosts = append(hosts, ipnet.IP.String())
}
}
anyValue = ips
}
}
value, err := resolver.NewHostValue(anyValue)
value, err := resolver.NewHostValue(hosts)
if err != nil {
return nil, fmt.Errorf("%s is not a valid value", anyValue)
}