golang 获取客户端IP
import (
"github.com/thinkeridea/go-extend/exnet"
"net"
"net/http"
)
// RemoteIp 返回远程客户端的 IP,如 192.168.1.1
func RemoteIp(req *http.Request) string {
remoteAddr := req.RemoteAddr
if ip := exnet.ClientPublicIP(req); ip != "" {
remoteAddr = ip
} else if ip := exnet.ClientIP(req); ip != "" {
remoteAddr = ip
} else if ip := req.Header.Get("X-Real-IP"); ip != "" {
remoteAddr = ip
} else if ip = req.Header.Get("X-Forwarded-For"); ip != "" {
remoteAddr = ip
} else {
remoteAddr, _, _ = net.SplitHostPort(remoteAddr)
}
if remoteAddr == "::1" {
remoteAddr = "127.0.0.1"
}
return remoteAddr
}