metadata: allow to remove key from metadata (#1453)

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2020-03-31 22:55:33 +03:00 committed by GitHub
parent 18061723bb
commit 5e65a46be3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 41 additions and 2 deletions

View File

@ -25,6 +25,13 @@ func (md Metadata) Get(key string) (string, bool) {
return val, ok
}
func (md Metadata) Del(key string) {
// delete key as-is
delete(md, key)
// delete also Title key
delete(md, strings.Title(key))
}
// Copy makes a copy of the metadata
func Copy(md Metadata) Metadata {
cmd := make(Metadata)
@ -34,13 +41,22 @@ func Copy(md Metadata) Metadata {
return cmd
}
// Del key from metadata
func Del(ctx context.Context, k string) context.Context {
return Set(ctx, k, "")
}
// Set add key with val to metadata
func Set(ctx context.Context, k, v string) context.Context {
md, ok := FromContext(ctx)
if !ok {
md = make(Metadata)
}
if v == "" {
delete(md, k)
} else {
md[k] = v
}
return context.WithValue(ctx, MetadataKey{}, md)
}
@ -96,8 +112,10 @@ func MergeContext(ctx context.Context, patchMd Metadata, overwrite bool) context
for k, v := range patchMd {
if _, ok := cmd[k]; ok && !overwrite {
// skip
} else {
} else if v != "" {
cmd[k] = v
} else {
delete(cmd, k)
}
}
return context.WithValue(ctx, MetadataKey{}, cmd)

View File

@ -18,6 +18,27 @@ func TestMetadataSet(t *testing.T) {
}
}
func TestMetadataDel(t *testing.T) {
md := Metadata{
"Foo": "bar",
"Baz": "empty",
}
ctx := NewContext(context.TODO(), md)
ctx = Set(ctx, "Baz", "")
emd, ok := FromContext(ctx)
if !ok {
t.Fatal("key Key not found")
}
_, ok = emd["Baz"]
if ok {
t.Fatal("key Baz not deleted")
}
}
func TestMetadataCopy(t *testing.T) {
md := Metadata{
"Foo": "bar",