diff --git a/context.go b/context.go index 60bc8c6..d678e91 100644 --- a/context.go +++ b/context.go @@ -208,8 +208,14 @@ func (c *Context) Status(code int) { } // JSON sets the response body to the given JSON representation. -func (c *Context) JSON(code int, obj interface{}) { +func (c *Context) JSON(code int, obj interface{}) ([]byte, error) { c.RequestCtx.Response.Header.SetContentType("application/json") c.RequestCtx.Response.SetStatusCode(code) - c.RequestCtx.Response.SetBodyString(utils.ToJSON(obj)) + jsonBody, err := utils.ToJSON(obj) + if err != nil { + return nil, err + } + c.RequestCtx.Response.SetBodyString(jsonBody) + + return []byte(jsonBody), nil } diff --git a/utils/json.go b/utils/json.go index 5716c3b..6dd1d9b 100644 --- a/utils/json.go +++ b/utils/json.go @@ -2,10 +2,10 @@ package utils import "encoding/json" -func ToJSON(v interface{}) string { +func ToJSON(v interface{}) (string, error) { b, err := json.Marshal(v) if err != nil { - return "" + return "", err } - return string(b) + return string(b), nil } diff --git a/utils/json_test.go b/utils/json_test.go index 6f1252b..3f8e54d 100644 --- a/utils/json_test.go +++ b/utils/json_test.go @@ -7,7 +7,7 @@ import ( func TestToJSON(t *testing.T) { t.Parallel() - res := ToJSON("MY/NAME/IS/:PARAM/*") + res, _ := ToJSON("MY/NAME/IS/:PARAM/*") fmt.Println(res) }