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
func Metadata(md any) Option {
result := metadata.Metadata{}
switch vt := md.(type) {
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)
case []string:
result.Set(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 {

View File

@ -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)