31 lines
561 B
Go
31 lines
561 B
Go
|
package tools
|
||
|
|
||
|
import (
|
||
|
"net"
|
||
|
"net/http"
|
||
|
"net/textproto"
|
||
|
"strings"
|
||
|
)
|
||
|
|
||
|
// RemoteIP -
|
||
|
func RemoteIP(req *http.Request) string {
|
||
|
ips := make([]string, 0)
|
||
|
if headerAddr := req.Header.Get(textproto.CanonicalMIMEHeaderKey("X-Forwarded-For")); len(headerAddr) > 0 {
|
||
|
ips = strings.Split(headerAddr, ",")
|
||
|
}
|
||
|
if len(ips) > 0 && len(ips[0]) > 0 {
|
||
|
rip, _, err := net.SplitHostPort(ips[0])
|
||
|
if err != nil {
|
||
|
return ips[0]
|
||
|
}
|
||
|
return rip
|
||
|
}
|
||
|
|
||
|
ip := req.RemoteAddr
|
||
|
if rip, _, err := net.SplitHostPort(ip); err == nil {
|
||
|
return rip
|
||
|
} else {
|
||
|
return ip
|
||
|
}
|
||
|
}
|