Skip to content

Commit

Permalink
Create extract IP address from context util function
Browse files Browse the repository at this point in the history
  • Loading branch information
Russell-Tran committed May 9, 2024
1 parent b58c1ef commit a317252
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
19 changes: 19 additions & 0 deletions go/util/util.go
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")
}
36 changes: 36 additions & 0 deletions go/util/util_test.go
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())
}
}

0 comments on commit a317252

Please sign in to comment.