mirror of
https://github.com/go-micro/go-micro.git
synced 2024-11-24 08:02:32 +02:00
adding PatchContext - this will create new context with original + patch metadata
This commit is contained in:
parent
f5b8a12106
commit
1f658cfbff
@ -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)
|
||||
|
||||
}
|
||||
|
@ -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"])
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user