某些场景我们需要获取客户端的ip,比如埋点、反作弊、审计等等
ip := net.ParseIP(ctx.ClientIP())
ip = ip.To4()
ipInt32 := binary.BigEndian.Uint32(ip)
上面这段代码乍看没有问题,但是实际应用中可能panic 我们来看下echo中相关函数的实现
func (c *Context) ClientIP() string {
if c.engine.ForwardedByClientIP {
clientIP := c.requestHeader("X-Forwarded-For")
clientIP = strings.TrimSpace(strings.Split(clientIP, ",")[0])
if clientIP == "" {
clientIP = strings.TrimSpace(c.requestHeader("X-Real-Ip"))
}
if clientIP != "" {
return clientIP
}
}
这里直接通过逗号分隔X-Forwarded-For,取第一个字符串,众所周知X-Forwarded-For是可以篡改的,如果用户不遵守代理协议,把第一个ip地址写成非法的ip地址,比如一个字符串,那么这个函数返回的就是一个字符串
https://www.bfe-networks.net/zh_cn/introduction/route/ https://github.com/gopherchina/conference https://blog.csdn.net/RA681t58CJxsgCkJ31/article/details/116548754 https://github.com/baidu/bfe-book