1
0
mirror of https://github.com/go-micro/go-micro.git synced 2024-12-24 10:07:04 +02:00

adding PatchContext - this will create new context with original + patch metadata

This commit is contained in:
Sumanth Chinthagunta 2019-10-24 17:51:54 -07:00
parent f5b8a12106
commit 1f658cfbff
2 changed files with 39 additions and 0 deletions

View File

@ -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)
}

View File

@ -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"])
}
}