Skip to content

Commit

Permalink
feat: strings add json string func
Browse files Browse the repository at this point in the history
  • Loading branch information
yinheli committed Sep 8, 2021
1 parent e75a0d5 commit 1306951
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
14 changes: 14 additions & 0 deletions pkg/stringx/strings.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package stringx

import (
"encoding/json"
"errors"
"strings"
)
Expand Down Expand Up @@ -119,3 +120,16 @@ func TakeOne(valid, or string) string {

return or
}

// MustJsonString returns string from json.Marshal.
func MustJsonString(obj interface{}) string {
if obj == nil {
return ""
}

b, err := json.Marshal(obj)
if err != nil {
return ""
}
return string(b)
}
19 changes: 19 additions & 0 deletions pkg/stringx/strings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -297,3 +297,22 @@ func TestTakeOne(t *testing.T) {
})
}
}

func TestMustJsonString(t *testing.T) {
tests := []struct {
name string
obj interface{}
want string
}{
{"empty", "", `""`},
{"nil", nil, ``},
{"map", map[string]int{"a": 1}, `{"a":1}`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := MustJsonString(tt.obj); got != tt.want {
t.Errorf("MustJsonString() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit 1306951

Please sign in to comment.