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 34 additions and 14 deletions
Showing only changes of commit 9dd64b1d81 - Show all commits

View File

@ -151,15 +151,29 @@ 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{} result := metadata.Metadata{}
switch vt := md.(type) {
if len(md) > 1 {
var tmp []string
for _, val := range md {
switch vt := val.(type) {
case string:
tmp = append(tmp, vt)
default:
return func(src interface{}) error {
return Set(src, result, ".Metadata")
}
}
}
result.Set(tmp...)
} else 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: }
result.Set(vt...)
} }
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)