Skip to content

Commit

Permalink
feat: Added GetClientIP function
Browse files Browse the repository at this point in the history
* Added GetClientIP function
* Forked from 'github.com/pixel-plaza-dev/uru-databases-2-go-service-common'
  • Loading branch information
ralvarezdev committed Dec 19, 2024
1 parent ad01cdd commit 29da868
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
28 changes: 28 additions & 0 deletions context/context.go
Original file line number Diff line number Diff line change
@@ -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
}
9 changes: 9 additions & 0 deletions context/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package context

import (
"errors"
)

var (
FailedToGetPeerFromContextError = errors.New("failed to get peer from context")
)

0 comments on commit 29da868

Please sign in to comment.