add variadic #302

Merged
vtolstov merged 2 commits from devstigneev/micro:issue_296 into master 2024-02-29 01:27:34 +03:00
2 changed files with 32 additions and 15 deletions

View File

@ -151,15 +151,26 @@ func ContentType(ct string) Option {
} }
// Metadata pass additional metadata // Metadata pass additional metadata
func Metadata(md any) Option { func Metadata(md ...any) Option {
result := metadata.Metadata{} var result metadata.Metadata
switch vt := md.(type) { if len(md) == 1 {
switch vt := md[0].(type) {
case metadata.Metadata: case metadata.Metadata:
result = metadata.Copy(vt) result = metadata.Copy(vt)
case map[string]string: case map[string]string:
result = metadata.Copy(vt) result = metadata.Copy(vt)
case []string: default:
result.Set(vt...) 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 func(src interface{}) error {

View File

@ -100,7 +100,7 @@ func TestMetadataAny(t *testing.T) {
}{ }{
{ {
"strings_even", "strings_even",
[]string{"key1", "val1", "key2", "val2"}, []any{"key1", "val1", "key2", "val2"},
metadata.Metadata{ metadata.Metadata{
"Key1": "val1", "Key1": "val1",
"Key2": "val2", "Key2": "val2",
@ -108,18 +108,18 @@ func TestMetadataAny(t *testing.T) {
}, },
{ {
"strings_odd", "strings_odd",
[]string{"key1", "val1", "key2"}, []any{"key1", "val1", "key2"},
metadata.Metadata{ metadata.Metadata{
"Key1": "val1", "Key1": "val1",
}, },
}, },
{ {
"map", Name: "map",
map[string]string{ Data: map[string]string{
"key1": "val1", "key1": "val1",
"key2": "val2", "key2": "val2",
}, },
metadata.Metadata{ Expected: metadata.Metadata{
"Key1": "val1", "Key1": "val1",
"Key2": "val2", "Key2": "val2",
}, },
@ -141,7 +141,13 @@ func TestMetadataAny(t *testing.T) {
t.Run(tt.Name, func(t *testing.T) { t.Run(tt.Name, func(t *testing.T) {
src := &s{} src := &s{}
var opts []options.Option 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 { for _, o := range opts {
if err := o(src); err != nil { if err := o(src); err != nil {
t.Fatal(err) t.Fatal(err)