There is one gRPC middleware realip
Package realip is a middleware that extracts the real IP of requests based on
header values
import "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/realip"
// Simple example of a unary server initialization code.
func ExampleUnaryServerInterceptor() {
// Define list of trusted peers from which we accept forwarded-for and
// real-ip headers.
trustedPeers := []netip.Prefix{
netip.MustParsePrefix("127.0.0.1/32"),
}
// Define headers to look for in the incoming request.
headers := []string{realip.XForwardedFor, realip.XRealIp}
_ = grpc.NewServer(
grpc.ChainUnaryInterceptor(
realip.UnaryServerInterceptor(trustedPeers, headers),
),
)
}
For grpc-gateway is used, the client IP address may be retrieved through x-forwarded-for
like this:
// Get IP from GRPC context
func GetIP(ctx context.Context) string {
if headers, ok := metadata.FromIncomingContext(ctx); ok {
xForwardFor := headers.Get("x-forwarded-for")
if len(xForwardFor) > 0 && xForwardFor[0] != "" {
ips := strings.Split(xForwardFor[0], ",")
if len(ips) > 0 {
clientIp := ips[0]
return clientIp
}
}
}
return ""
}