-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* Added GetClientIP function * Forked from 'github.com/pixel-plaza-dev/uru-databases-2-go-service-common'
- Loading branch information
1 parent
ad01cdd
commit 29da868
Showing
2 changed files
with
37 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | ||
) |