diff --git a/context/context.go b/context/context.go new file mode 100644 index 0000000..32bf969 --- /dev/null +++ b/context/context.go @@ -0,0 +1,28 @@ +package context + +import ( + "context" + "google.golang.org/grpc/peer" + "net" + "strings" +) + +// GetClientIP extracts the client IP address from the context +func GetClientIP(ctx context.Context) (string, error) { + p, ok := peer.FromContext(ctx) + if !ok { + return "", FailedToGetPeerFromContextError + } + + // Get the IP address from the peer address + addr := p.Addr.String() + ip, _, err := net.SplitHostPort(addr) + if err != nil { + return "", err + } + + // Remove any surrounding brackets from IPv6 addresses + ip = strings.Trim(ip, "[]") + + return ip, nil +} diff --git a/context/errors.go b/context/errors.go new file mode 100644 index 0000000..3593487 --- /dev/null +++ b/context/errors.go @@ -0,0 +1,9 @@ +package context + +import ( + "errors" +) + +var ( + FailedToGetPeerFromContextError = errors.New("failed to get peer from context") +)