Browse Source

fix: get client ip on keep-alive

master 1.8.3
OhYee 2 weeks ago
parent
commit
d0dc96d4ac
Signed by: OhYee
GPG Key ID: 5A9E1F63ED274FBB
  1. 10
      register/context_http.go
  2. 10
      register/context_websocket.go
  3. 11
      register/utils.go

10
register/context_http.go

@ -208,9 +208,11 @@ func (context *HTTPContext) GetContext(key string) (value interface{}, ok bool) @@ -208,9 +208,11 @@ func (context *HTTPContext) GetContext(key string) (value interface{}, ok bool)
// GetClientIP returns client ip
func (context *HTTPContext) GetClientIP() string {
clientIP := getIPFromHeader(&context.Request.Header, X_Real_IP)
if clientIP == "" {
clientIP = getIPFromHeader(&context.Request.Header, X_FORWARDED_FOR)
for _, headerName := range ipHeaders {
if clientIP := getIPFromHeader(&context.Request.Header, headerName); clientIP != "" {
return clientIP
}
}
return clientIP
return ""
}

10
register/context_websocket.go

@ -127,9 +127,11 @@ func (context *WebSocketContext) GetContext(key string) (value interface{}, ok b @@ -127,9 +127,11 @@ func (context *WebSocketContext) GetContext(key string) (value interface{}, ok b
// GetClientIP returns client ip
func (context *WebSocketContext) GetClientIP() string {
clientIP := getIPFromHeader(&context.Request.Header, X_Real_IP)
if clientIP == "" {
clientIP = getIPFromHeader(&context.Request.Header, X_FORWARDED_FOR)
for _, headerName := range ipHeaders {
if clientIP := getIPFromHeader(&context.Request.Header, headerName); clientIP != "" {
return clientIP
}
}
return clientIP
return ""
}

11
register/utils.go

@ -6,14 +6,19 @@ import ( @@ -6,14 +6,19 @@ import (
)
const (
X_Real_IP = "X-Real-Ip"
X_FORWARDED_FOR = "X-Forwarded-For"
_X_Real_IP = "X-Real-Ip"
_X_FORWARDED_FOR = "X-Forwarded-For"
)
var (
ipHeaders = []string{_X_FORWARDED_FOR, _X_Real_IP}
)
func getIPFromHeader(header *http.Header, headerName string) string {
IPs := header.Values(headerName)
if len(IPs) > 0 {
remoteIP := IPs[0]
remoteIP := IPs[len(IPs)-1]
arr := strings.Split(remoteIP, ",")
if len(arr) > 0 {
return strings.TrimSpace(arr[0])

Loading…
Cancel
Save