From ab1c95bdd4c00a690cfe615ebe727f66d7014cf4 Mon Sep 17 00:00:00 2001 From: liushaobo Date: Fri, 12 Mar 2021 22:58:54 +0800 Subject: [PATCH] func support json serialize --- cast_test.go | 22 ++++++++++++++++++++-- caste.go | 7 +++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/cast_test.go b/cast_test.go index cc4ebce..270a5ed 100644 --- a/cast_test.go +++ b/cast_test.go @@ -7,6 +7,7 @@ package cast import ( "errors" + "encoding/json" "fmt" "html/template" "testing" @@ -599,6 +600,19 @@ func TestToStringE(t *testing.T) { } key := &Key{"foo"} + type Stru struct { + K string + } + stru := &Stru{K:"foo"} + + struStr, _ := json.Marshal(stru) + + dic := map[string]interface{}{ + "obj": map[string]int{"key": 123}, + } + + dicStr, _ := json.Marshal(dic) + tests := []struct { input interface{} expect string @@ -620,15 +634,19 @@ func TestToStringE(t *testing.T) { {false, "false", false}, {nil, "", false}, {[]byte("one time"), "one time", false}, + {[]byte("你好!"), "你好!", false}, + {[]rune("你好!"), "你好!", false}, {"one more time", "one more time", false}, {template.HTML("one time"), "one time", false}, {template.URL("http://somehost.foo"), "http://somehost.foo", false}, {template.JS("(1+2)"), "(1+2)", false}, {template.CSS("a"), "a", false}, {template.HTMLAttr("a"), "a", false}, + {dic, string(dicStr), false}, + {stru, string(struStr), false}, // errors - {testing.T{}, "", true}, - {key, "", true}, + {testing.T{}, "{}", false}, + {key, "{}", false}, } for i, test := range tests { diff --git a/caste.go b/caste.go index 9ac1015..35da14e 100644 --- a/caste.go +++ b/caste.go @@ -830,6 +830,8 @@ func ToStringE(i interface{}) (string, error) { return strconv.FormatUint(uint64(s), 10), nil case []byte: return string(s), nil + case []rune: + return string(s), nil case template.HTML: return string(s), nil case template.URL: @@ -847,6 +849,11 @@ func ToStringE(i interface{}) (string, error) { case error: return s.Error(), nil default: + jsonContent, err := json.Marshal(s) + if err == nil { + return string(jsonContent), nil + } + return "", fmt.Errorf("unable to cast %#v of type %T to string", i, i) } }