Skip to content

Commit

Permalink
metadata: allow to remove key from metadata (micro#1453)
Browse files Browse the repository at this point in the history
Signed-off-by: Vasiliy Tolstov <[email protected]>
  • Loading branch information
vtolstov authored Mar 31, 2020
1 parent 1806172 commit 5e65a46
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
22 changes: 20 additions & 2 deletions metadata/metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
}
md[k] = v
if v == "" {
delete(md, k)
} else {
md[k] = v
}
return context.WithValue(ctx, MetadataKey{}, md)
}

Expand Down Expand Up @@ -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)
Expand Down
21 changes: 21 additions & 0 deletions metadata/metadata_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down

0 comments on commit 5e65a46

Please sign in to comment.