fix: 修复 TLS ConnectionState、SPA 回退、健康检查与监听小问题
This commit is contained in:
@@ -7,7 +7,8 @@ import (
|
||||
)
|
||||
|
||||
// ClientIP 按 DEVELOPMENT 4.5:仅当对端在 trusted 网段内时采信
|
||||
// X-Forwarded-For(从右往左第一个不在 trusted 内的地址)。
|
||||
// X-Forwarded-For(合并多行,从右往左第一个不在 trusted 内的地址)。
|
||||
// 遇到无法解析的项立即停下,回退到对端地址。
|
||||
func ClientIP(r *http.Request, trusted []*net.IPNet) string {
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
@@ -20,17 +21,20 @@ func ClientIP(r *http.Request, trusted []*net.IPNet) string {
|
||||
if !ipInNets(ip, trusted) {
|
||||
return ip.String()
|
||||
}
|
||||
xff := r.Header.Get("X-Forwarded-For")
|
||||
xff := strings.Join(r.Header.Values("X-Forwarded-For"), ",")
|
||||
if xff == "" {
|
||||
return ip.String()
|
||||
}
|
||||
parts := strings.Split(xff, ",")
|
||||
for i := len(parts) - 1; i >= 0; i-- {
|
||||
cand := strings.TrimSpace(parts[i])
|
||||
parsed := net.ParseIP(cand)
|
||||
if parsed == nil {
|
||||
if cand == "" {
|
||||
continue
|
||||
}
|
||||
parsed := parseForwardedIP(cand)
|
||||
if parsed == nil {
|
||||
return ip.String()
|
||||
}
|
||||
if !ipInNets(parsed, trusted) {
|
||||
return parsed.String()
|
||||
}
|
||||
@@ -38,6 +42,20 @@ func ClientIP(r *http.Request, trusted []*net.IPNet) string {
|
||||
return ip.String()
|
||||
}
|
||||
|
||||
func parseForwardedIP(s string) net.IP {
|
||||
if ip := net.ParseIP(s); ip != nil {
|
||||
return ip
|
||||
}
|
||||
host, _, err := net.SplitHostPort(s)
|
||||
if err == nil {
|
||||
return net.ParseIP(host)
|
||||
}
|
||||
if strings.HasPrefix(s, "[") && strings.HasSuffix(s, "]") {
|
||||
return net.ParseIP(s[1 : len(s)-1])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// IsHTTPS 判定请求是否视为 HTTPS(直连 TLS 或受信任代理的 X-Forwarded-Proto)。
|
||||
func IsHTTPS(r *http.Request, trusted []*net.IPNet) bool {
|
||||
if r.TLS != nil {
|
||||
|
||||
Reference in New Issue
Block a user