diff --git a/metadata/metadata.go b/metadata/metadata.go index 3ae6ba85..606c1f05 100644 --- a/metadata/metadata.go +++ b/metadata/metadata.go @@ -28,3 +28,17 @@ func FromContext(ctx context.Context) (Metadata, bool) { func NewContext(ctx context.Context, md Metadata) context.Context { return context.WithValue(ctx, metaKey{}, md) } + +// PatchContext : will add/replace source metadata fields with given patch metadata fields +func PatchContext(ctx context.Context, patchMd Metadata) context.Context { + md, _ := ctx.Value(metaKey{}).(Metadata) + cmd := make(Metadata) + for k, v := range md { + cmd[k] = v + } + for k, v := range patchMd { + cmd[k] = v + } + return context.WithValue(ctx, metaKey{}, cmd) + +} diff --git a/metadata/metadata_test.go b/metadata/metadata_test.go index 9b5545eb..cfd1c1f8 100644 --- a/metadata/metadata_test.go +++ b/metadata/metadata_test.go @@ -40,3 +40,28 @@ func TestMetadataContext(t *testing.T) { t.Errorf("Expected metadata length 1 got %d", i) } } +func TestPatchContext(t *testing.T) { + + original := Metadata{ + "foo": "bar", + } + + patch := Metadata{ + "sumo": "demo", + } + ctx := NewContext(context.TODO(), original) + + patchedCtx := PatchContext(ctx, patch) + + patchedMd, ok := FromContext(patchedCtx) + if !ok { + t.Errorf("Unexpected error retrieving metadata, got %t", ok) + } + + if patchedMd["sumo"] != patch["sumo"] { + t.Errorf("Expected key: %s val: %s, got key: %s val: %s", "sumo", patch["sumo"], "sumo", patchedMd["sumo"]) + } + if patchedMd["foo"] != original["foo"] { + t.Errorf("Expected key: %s val: %s, got key: %s val: %s", "foo", original["foo"], "foo", patchedMd["foo"]) + } +}