github.com/profzone/eden-framework@v1.0.10/pkg/courier/transport_grpc/client_ip.go (about) 1 package transport_grpc 2 3 import ( 4 "context" 5 "net" 6 "strings" 7 8 "google.golang.org/grpc/metadata" 9 "google.golang.org/grpc/peer" 10 11 "github.com/profzone/eden-framework/pkg/courier/httpx" 12 ) 13 14 func ClientIP(ctx context.Context) string { 15 md, ok := metadata.FromIncomingContext(ctx) 16 if ok { 17 if values, ok := md[httpx.HeaderForwardedFor]; ok { 18 clientIP := httpx.GetClientIPByHeaderForwardedFor(strings.Join(values, "")) 19 if clientIP != "" { 20 return clientIP 21 } 22 } 23 24 if values, ok := md[httpx.HeaderRealIP]; ok { 25 clientIP := httpx.GetClientIPByHeaderRealIP(strings.Join(values, "")) 26 if clientIP != "" { 27 return clientIP 28 } 29 } 30 } 31 32 if p, ok := peer.FromContext(ctx); ok { 33 if clientIP, _, err := net.SplitHostPort(strings.TrimSpace(p.Addr.String())); err == nil { 34 return clientIP 35 } 36 } 37 38 return "" 39 }