diff --git a/options/options.go b/options/options.go index cda572a6..cbcf15fd 100644 --- a/options/options.go +++ b/options/options.go @@ -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") } } diff --git a/options/options_test.go b/options/options_test.go index 7d3b6a62..a2f26e8a 100644 --- a/options/options_test.go +++ b/options/options_test.go @@ -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)) + } + } + }) + } +}