Skip to content

Commit

Permalink
feat: print value as json compact string
Browse files Browse the repository at this point in the history
  • Loading branch information
fsamin committed Nov 20, 2020
1 parent 1fde12b commit 896154b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
4 changes: 2 additions & 2 deletions dump_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -609,9 +609,9 @@ func TestEnvVariableWithViper(t *testing.T) {
var myStructFromViper MyStruct
err = viper.Unmarshal(&myStructFromViper)
assert.NoError(t, err)
t.Logf("--> %+v", myStructFromViper)
t.Logf("--> %T %+v", myStructFromViper, myStructFromViper)

assert.Equal(t, fmt.Sprintf("%+v", myStruct), fmt.Sprintf("%+v", myStructFromViper))
assert.Equal(t, myStruct, myStructFromViper)

}

Expand Down
27 changes: 26 additions & 1 deletion encoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ func (e *Encoder) ToStringMap(i interface{}) (res map[string]string, err error)
prefix = e.Prefix + e.Separator
}
for k, v := range ires {
res[prefix+k] = fmt.Sprintf("%v", v)
res[prefix+k] = printValue(v)
}
return
}
Expand Down Expand Up @@ -346,3 +346,28 @@ func (e *Encoder) ViperKey(s string) string {
s = strings.ToLower(s)
return s
}

func printValue(i interface{}) string {
s, is := i.(string)
if is {
return s
}
ps, is := i.(*string)
if is && ps != nil {
return *ps
}
stringer, is := i.(fmt.Stringer)
if is {
return stringer.String()
}
btes, err := json.Marshal(i)
if err == nil {
compactedBuffer := new(bytes.Buffer)
err := json.Compact(compactedBuffer, btes)
if err != nil {
return string(btes)
}
return compactedBuffer.String()
}
return fmt.Sprintf("%v", i)
}

0 comments on commit 896154b

Please sign in to comment.