Merge branch 'master' into issue_294
Some checks failed
lint / lint (pull_request) Has been cancelled
pr / test (pull_request) Has been cancelled

This commit is contained in:
Денис Евстигнеев 2024-02-29 13:07:26 +03:00
commit 4124b49481
2 changed files with 98 additions and 2 deletions

View File

@ -151,9 +151,30 @@ func ContentType(ct string) Option {
}
// Metadata pass additional metadata
func Metadata(md metadata.Metadata) Option {
func Metadata(md ...any) Option {
var result metadata.Metadata
if len(md) == 1 {
switch vt := md[0].(type) {
case metadata.Metadata:
result = metadata.Copy(vt)
case map[string]string:
result = metadata.Copy(vt)
default:
result = metadata.New(0)
}
} else {
result = metadata.New(len(md) / 2)
for idx := 0; idx < len(md)/2; idx += 2 {
k, kok := md[idx].(string)
v, vok := md[idx+1].(string)
if kok && vok {
result.Set(k, v)
}
}
}
return func(src interface{}) error {
return Set(src, metadata.Copy(md), ".Metadata")
return Set(src, result, ".Metadata")
}
}

View File

@ -1,10 +1,13 @@
package options_test
import (
"fmt"
"testing"
"go.unistack.org/micro/v4/codec"
"go.unistack.org/micro/v4/metadata"
"go.unistack.org/micro/v4/options"
"go.unistack.org/micro/v4/util/reflect"
)
func TestAddress(t *testing.T) {
@ -84,3 +87,75 @@ func TestLabels(t *testing.T) {
t.Fatal("failed to set labels")
}
}
func TestMetadataAny(t *testing.T) {
type s struct {
Metadata metadata.Metadata
}
testCases := []struct {
Name string
Data any
Expected metadata.Metadata
}{
{
"strings_even",
[]any{"key1", "val1", "key2", "val2"},
metadata.Metadata{
"Key1": "val1",
"Key2": "val2",
},
},
{
"strings_odd",
[]any{"key1", "val1", "key2"},
metadata.Metadata{
"Key1": "val1",
},
},
{
Name: "map",
Data: map[string]string{
"key1": "val1",
"key2": "val2",
},
Expected: metadata.Metadata{
"Key1": "val1",
"Key2": "val2",
},
},
{
"metadata.Metadata",
metadata.Metadata{
"key1": "val1",
"key2": "val2",
},
metadata.Metadata{
"Key1": "val1",
"Key2": "val2",
},
},
}
for _, tt := range testCases {
t.Run(tt.Name, func(t *testing.T) {
src := &s{}
var opts []options.Option
switch valData := tt.Data.(type) {
case []any:
opts = append(opts, options.Metadata(valData...))
case map[string]string, metadata.Metadata:
opts = append(opts, options.Metadata(valData))
}
for _, o := range opts {
if err := o(src); err != nil {
t.Fatal(err)
}
if !reflect.Equal(tt.Expected, src.Metadata) {
t.Fatal(fmt.Sprintf("expected: %v, actual: %v", tt.Expected, src.Metadata))
}
}
})
}
}