fix: 修复域名转化 ipv6 失效

This commit is contained in:
Akizon77
2025-11-05 17:33:01 +08:00
parent dbd8479981
commit e8835d135a

View File

@@ -1,6 +1,7 @@
package utils
import (
"net"
"net/url"
"strings"
@@ -16,8 +17,15 @@ func ConvertIDNToASCII(urlStr string) (string, error) {
return urlStr, err
}
hostname := parsedURL.Hostname()
// 检查是否为 IP 地址(IPv4 或 IPv6),如果是则不需要转换
if net.ParseIP(hostname) != nil {
return parsedURL.String(), nil
}
// 转换主机名为 Punycode
asciiHost, err := idna.ToASCII(parsedURL.Hostname())
asciiHost, err := idna.ToASCII(hostname)
if err != nil {
return urlStr, err
}
@@ -37,18 +45,45 @@ func ConvertIDNToASCII(urlStr string) (string, error) {
func ConvertHostToASCII(host string) (string, error) {
// 分离主机名和端口
var hostname, port string
if idx := strings.LastIndex(host, ":"); idx != -1 {
hostname = host[:idx]
port = host[idx:]
// 处理 IPv6 地址格式 [::1]:port
if strings.HasPrefix(host, "[") {
if idx := strings.LastIndex(host, "]"); idx != -1 {
hostname = host[1:idx] // 去掉方括号
if len(host) > idx+1 {
port = host[idx+1:] // 包含冒号
}
} else {
hostname = host
}
} else if idx := strings.LastIndex(host, ":"); idx != -1 {
// 检查是否为 IPv6 地址(包含多个冒号)
if strings.Count(host, ":") > 1 {
// 可能是不带方括号的 IPv6 地址
hostname = host
} else {
// IPv4:port 格式
hostname = host[:idx]
port = host[idx:]
}
} else {
hostname = host
}
// 检查是否为 IP 地址,如果是则不需要转换
if net.ParseIP(hostname) != nil {
return host, nil
}
// 转换为 ASCII
asciiHost, err := idna.ToASCII(hostname)
if err != nil {
return host, err
}
// 重新组装,如果原始输入有方括号则保留
if strings.HasPrefix(host, "[") && port != "" {
return "[" + asciiHost + "]" + port, nil
}
return asciiHost + port, nil
}