Skip to content
This repository has been archived by the owner on Feb 20, 2022. It is now read-only.

Commit

Permalink
Add MapWithPrefix for convenience
Browse files Browse the repository at this point in the history
  • Loading branch information
on99 committed Dec 1, 2020
1 parent f7fea8d commit 48ce79b
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 3 deletions.
20 changes: 17 additions & 3 deletions structs.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,19 @@ func (s *Struct) Map() map[string]interface{} {
return out
}

func (s *Struct) MapWithPrefix(prefix string) map[string]interface{} {
out := make(map[string]interface{})
s.FillMapWithPrefix(out, prefix)
return out
}

// FillMap is the same as Map. Instead of returning the output, it fills the
// given map.
func (s *Struct) FillMap(out map[string]interface{}) {
s.FillMapWithPrefix(out, "")
}

func (s *Struct) FillMapWithPrefix(out map[string]interface{}, prefix string) {
if out == nil {
return
}
Expand Down Expand Up @@ -134,19 +144,19 @@ func (s *Struct) FillMap(out map[string]interface{}) {
if tagOpts.Has("string") {
s, ok := val.Interface().(fmt.Stringer)
if ok {
out[name] = s.String()
out[prefix+name] = s.String()
}
continue
}

if isSubStruct && (tagOpts.Has("flatten")) {
if m, ok := finalVal.(map[string]interface{}); ok {
for k, v := range m {
out[k] = v
out[prefix+k] = v
}
}
} else {
out[name] = finalVal
out[prefix+name] = finalVal
}
}
}
Expand Down Expand Up @@ -448,6 +458,10 @@ func Map(s interface{}) map[string]interface{} {
return New(s).Map()
}

func MapWithPrefix(s interface{}, prefix string) map[string]interface{} {
return New(s).MapWithPrefix(prefix)
}

// FillMap is the same as Map. Instead of returning the output, it fills the
// given map.
func FillMap(s interface{}, out map[string]interface{}) {
Expand Down
30 changes: 30 additions & 0 deletions structs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,36 @@ func TestMap_Tag(t *testing.T) {

}

func TestMapWithPrefix_Tag(t *testing.T) {
var T = struct {
A string `structs:"x"`
B int `structs:"y"`
C bool `structs:"z"`
}{
A: "a-value",
B: 2,
C: true,
}

prefix := "p_"
a := MapWithPrefix(T, prefix)

inMap := func(key interface{}) bool {
for k := range a {
if reflect.DeepEqual(k, key) {
return true
}
}
return false
}

for _, key := range []string{"x", "y", "z"} {
if !inMap(prefix + key) {
t.Errorf("Map should have the key %v", prefix+key)
}
}
}

func TestMap_CustomTag(t *testing.T) {
var T = struct {
A string `json:"x"`
Expand Down

0 comments on commit 48ce79b

Please sign in to comment.