From f06e0b21e8b055287b4d912aa0616dc040a129f9 Mon Sep 17 00:00:00 2001 From: Evstigneev Denis Date: Thu, 29 Feb 2024 01:27:33 +0300 Subject: [PATCH] add variadic (#302) Co-authored-by: Vasiliy Tolstov Reviewed-on: https://git.unistack.org/unistack-org/micro/pulls/302 Co-authored-by: Evstigneev Denis Co-committed-by: Evstigneev Denis --- options/options.go | 29 ++++++++++++++++++++--------- options/options_test.go | 18 ++++++++++++------ 2 files changed, 32 insertions(+), 15 deletions(-) diff --git a/options/options.go b/options/options.go index 226fd5e4..cbcf15fd 100644 --- a/options/options.go +++ b/options/options.go @@ -151,15 +151,26 @@ func ContentType(ct string) Option { } // Metadata pass additional metadata -func Metadata(md any) Option { - result := metadata.Metadata{} - switch vt := md.(type) { - case metadata.Metadata: - result = metadata.Copy(vt) - case map[string]string: - result = metadata.Copy(vt) - case []string: - result.Set(vt...) +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 { diff --git a/options/options_test.go b/options/options_test.go index 1bb0ce23..a2f26e8a 100644 --- a/options/options_test.go +++ b/options/options_test.go @@ -100,7 +100,7 @@ func TestMetadataAny(t *testing.T) { }{ { "strings_even", - []string{"key1", "val1", "key2", "val2"}, + []any{"key1", "val1", "key2", "val2"}, metadata.Metadata{ "Key1": "val1", "Key2": "val2", @@ -108,18 +108,18 @@ func TestMetadataAny(t *testing.T) { }, { "strings_odd", - []string{"key1", "val1", "key2"}, + []any{"key1", "val1", "key2"}, metadata.Metadata{ "Key1": "val1", }, }, { - "map", - map[string]string{ + Name: "map", + Data: map[string]string{ "key1": "val1", "key2": "val2", }, - metadata.Metadata{ + Expected: metadata.Metadata{ "Key1": "val1", "Key2": "val2", }, @@ -141,7 +141,13 @@ func TestMetadataAny(t *testing.T) { t.Run(tt.Name, func(t *testing.T) { src := &s{} var opts []options.Option - opts = append(opts, options.Metadata(tt.Data)) + 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)