diff --git a/go/util/util.go b/go/util/util.go new file mode 100644 index 0000000..e6f2d84 --- /dev/null +++ b/go/util/util.go @@ -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") +} diff --git a/go/util/util_test.go b/go/util/util_test.go new file mode 100644 index 0000000..a00f4de --- /dev/null +++ b/go/util/util_test.go @@ -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()) + } +}