Skip to content

Commit faf5325

Browse files
committed
feat(net/http): Use ipFromHostPort from gocloud.dev
1 parent e413a93 commit faf5325

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

go/net/http/request.go

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,10 @@
55
package http
66

77
import (
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+
}

0 commit comments

Comments
 (0)