k8s 配置
可以修改kube-system/nginx-configuration configmap的方式,
compute-full-forwarded-for: “true”
forwarded-for-header: “X-Forwarded-For”
use-forwarded-headers: “true”
https://help.aliyun.com/zh/ack/ack-managed-and-ack-dedicated/user-guide/nginx-ingress-faq?spm=a2c4g.11186623.0.i3#section-ril-3ys-j8u
这里加好后,
// 定义可能包含客户端IP地址的HTTP头部
var headers = []string{ "X-Forwarded-For","X-Real-Ip","X-Original-Forwarded-For", "Ali-Cdn-Real-Ip", "Remote_addr"}// GetIPSourse 获取用户来源
func GetIPSourse(c *gin.Context) string {for _, header := range headers {ip := c.Request.Header.Get(header)if ip != "" {// 如果头部值包含多个IP(如X-Forwarded-For),则取第一个ip = strings.Split(ip, ",")[0]ip = strings.TrimSpace(ip) // 清除可能的空格return ip}}// 如果前面的头部都没有找到,使用RemoteAddrip := c.Request.RemoteAddr// 只获取IP部分,忽略端口号if ip != "" {ip = strings.Split(ip, ":")[0]return ip}// 如果所有方法都没有找到IP,则返回空字符串return ""
}
测试一下