Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
6 changes: 3 additions & 3 deletions utils/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
2 changes: 1 addition & 1 deletion utils/json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}