xfy 616762e840 refactor(netutil): 提取通用主机名处理函数
- 新增 StripPort() 函数用于移除主机名中的端口
- 新增 HasPort() 函数用于检测主机名是否包含端口
- 替代 vhost 和 ssl 模块中的内联端口处理逻辑

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-10 11:20:10 +08:00

70 lines
1.3 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Package netutil 提供网络相关的工具函数。
//
// 该文件包含主机名处理相关的工具函数。
//
// 作者xfy
package netutil
import (
"strings"
)
// StripPort 从 Host 头中移除端口号。
//
// 支持 IPv4 和 IPv6 格式:
// - example.com:8080 -> example.com
// - [::1]:8080 -> [::1]
// - [2001:db8::1]:443 -> [2001:db8::1]
// - example.com -> example.com
//
// 参数:
// - host: 主机名(可能包含端口)
//
// 返回值:
// - string: 移除端口后的主机名
func StripPort(host string) string {
if len(host) == 0 {
return host
}
// IPv6 格式:以 '[' 开头,找 ']:' 作为分隔点
if host[0] == '[' {
for i := 0; i < len(host)-1; i++ {
if host[i] == ']' && host[i+1] == ':' {
return host[:i+1]
}
}
return host
}
// IPv4 或域名格式:找第一个 ':' 作为分隔点
for i := 0; i < len(host); i++ {
if host[i] == ':' {
return host[:i]
}
}
return host
}
// HasPort 检查主机名是否包含端口号。
//
// 参数:
// - host: 主机名
//
// 返回值:
// - bool: true 表示包含端口
func HasPort(host string) bool {
if len(host) == 0 {
return false
}
// IPv6 格式
if host[0] == '[' {
return strings.Contains(host, "]:")
}
// IPv4 或域名格式
return strings.Contains(host, ":")
}