File tree Expand file tree Collapse file tree 1 file changed +19
-4
lines changed
Expand file tree Collapse file tree 1 file changed +19
-4
lines changed Original file line number Diff line number Diff line change 55package http
66
77import (
8+ "net"
89 "net/http"
910 "strings"
1011
11- net_ "github.com/searKing/golang/go/net"
1212 strings_ "github.com/searKing/golang/go/strings"
1313)
1414
@@ -25,10 +25,25 @@ func ClientIP(req *http.Request) string {
2525 if clientIP != "" {
2626 return clientIP
2727 }
28+ return ipFromHostPort (req .RemoteAddr )
29+ }
2830
29- if ip , _ , err := net_ .SplitHostPort (strings .TrimSpace (req .RemoteAddr )); err == nil {
30- return ip
31+ // ServerIP implements a best effort algorithm to return the real server IP, it parses
32+ // LocalAddrContextKey from request context to get server IP.
33+ func ServerIP (req * http.Request ) string {
34+ if addr , ok := req .Context ().Value (http .LocalAddrContextKey ).(net.Addr ); ok {
35+ return ipFromHostPort (addr .String ())
3136 }
32-
3337 return ""
3438}
39+
40+ func ipFromHostPort (hp string ) string {
41+ h , _ , err := net .SplitHostPort (hp )
42+ if err != nil {
43+ return ""
44+ }
45+ if len (h ) > 0 && h [0 ] == '[' {
46+ return h [1 : len (h )- 1 ]
47+ }
48+ return h
49+ }
You can’t perform that action at this time.
0 commit comments