-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create extract IP address from context util function
- Loading branch information
1 parent
b58c1ef
commit a317252
Showing
2 changed files
with
55 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,19 @@ | ||
package util | ||
|
||
import ( | ||
"context" | ||
"google.golang.org/grpc/metadata" | ||
"google.golang.org/grpc/status" | ||
"google.golang.org/grpc/codes" | ||
) | ||
|
||
func extractAddressFromCtx(ctx context.Context) (string, error) { | ||
if md, ok := metadata.FromIncomingContext(ctx); ok { | ||
addresses := md.Get("client-address") | ||
if len(addresses) > 0 { | ||
return addresses[0], nil | ||
} | ||
return "", status.Error(codes.InvalidArgument, "client address not provided in metadata") | ||
} | ||
return "", status.Error(codes.Internal, "failed to extract metadata") | ||
} |
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,36 @@ | ||
package util | ||
|
||
import ( | ||
"context" | ||
"testing" | ||
|
||
"google.golang.org/grpc/metadata" | ||
"google.golang.org/grpc/codes" | ||
"google.golang.org/grpc/status" | ||
) | ||
|
||
func TestExtractAddressFromCtx(t *testing.T) { | ||
// Create a context with metadata | ||
md := metadata.New(map[string]string{"client-address": "192.168.1.1"}) | ||
ctx := metadata.NewIncomingContext(context.Background(), md) | ||
|
||
// Test extraction | ||
addr, err := extractAddressFromCtx(ctx) | ||
if err != nil { | ||
t.Fatalf("Failed to extract address: %v", err) | ||
} | ||
if addr != "192.168.1.1" { | ||
t.Errorf("Extracted address is incorrect, got: %s, want: %s", addr, "192.168.1.1") | ||
} | ||
|
||
// Test with no metadata | ||
ctxNoMeta := context.Background() | ||
_, err = extractAddressFromCtx(ctxNoMeta) | ||
if err == nil { | ||
t.Errorf("Expected an error for missing metadata, but got none") | ||
} | ||
st, _ := status.FromError(err) | ||
if st.Code() != codes.InvalidArgument { | ||
t.Errorf("Expected InvalidArgument, got: %v", st.Code()) | ||
} | ||
} |