Skip to content

Commit

Permalink
✨ feat: maputil - add new util function StringsMapToAnyMap()
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Jun 19, 2023
1 parent 47bdeb4 commit c41dbba
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
24 changes: 24 additions & 0 deletions maputil/convert.go
Expand Up @@ -74,6 +74,30 @@ func HTTPQueryString(data map[string]any) string {
return strings.Join(ss, "&")
}

// StringsMapToAnyMap convert map[string][]string to map[string]any
//
// Example:
// {"k1": []string{"v1", "v2"}, "k2": []string{"v3"}}
// =>
// {"k": []string{"v1", "v2"}, "k2": "v3"}
//
// mp := StringsMapToAnyMap(httpReq.Header)
func StringsMapToAnyMap(ssMp map[string][]string) map[string]any {
if len(ssMp) == 0 {
return nil
}

anyMp := make(map[string]any, len(ssMp))
for k, v := range ssMp {
if len(v) == 1 {
anyMp[k] = v[0]
continue
}
anyMp[k] = v
}
return anyMp
}

// ToString simple and quickly convert map[string]any to string.
func ToString(mp map[string]any) string {
if mp == nil {
Expand Down
19 changes: 19 additions & 0 deletions maputil/convert_test.go
Expand Up @@ -2,6 +2,7 @@ package maputil_test

import (
"fmt"
"net/http"
"testing"

"github.com/gookit/goutil/dump"
Expand Down Expand Up @@ -100,3 +101,21 @@ func TestFlatten(t *testing.T) {
maputil.FlatWithFunc(nil, nil)
})
}

func TestStringsMapToAnyMap(t *testing.T) {
assert.Nil(t, maputil.StringsMapToAnyMap(nil))

hh := http.Header{
"key0": []string{"val0", "val1"},
"key1": []string{"val2"},
}

mp := maputil.StringsMapToAnyMap(hh)
assert.Contains(t, mp, "key0")
assert.Contains(t, mp, "key1")
assert.Len(t, mp["key0"], 2)

dm := maputil.Data(mp)
assert.Eq(t, "val0", dm.Str("key0.0"))
assert.Eq(t, "val2", dm.Str("key1"))
}

0 comments on commit c41dbba

Please sign in to comment.