Gin: Not escaping JSON when rendering responses

Created on 21 Apr 2017  路  8Comments  路  Source: gin-gonic/gin

Hey guys,

I'm currently trying to render out JSON as a response to a request which contains an & in one of the fields which is a pagination URL. Unfortunately when rendering this out to the clients it seems like this character (and others, this is just an example) are getting escaped by the JSON writer used. I tracked it down to this function in json.go:

func WriteJSON(w http.ResponseWriter, obj interface{}) error {
    writeContentType(w, jsonContentType)
    return json.NewEncoder(w).Encode(obj)
}

When I change the function to

func WriteJSON(w http.ResponseWriter, obj interface{}) error {
    writeContentType(w, jsonContentType)
    encoder := json.NewEncoder(w)
    encoder.SetEscapeHTML(false)
    return encoder.Encode(obj)
}

everything seems to work as expected.

Before I submit a pull-request to set a flag somewhere to configure this behaviour, I wanted to quickly check in if this is wanted behaviour?

Most helpful comment

As of now(v1.3.0), This feature is still only existing in master, not in a release. :disappointed:

Related: https://github.com/golang/go/issues/14749

Workaround:

var (
        buf     bytes.Buffer
        encoder = json.NewEncoder(&buf)
    )

        // important
    encoder.SetEscapeHTML(false)

    _ = encoder.Encode(responseData)

    c.DataFromReader(http.StatusOK, int64(buf.Len()), "application/json; charset=utf-8", &buf, map[string]string{})

All 8 comments

Hi @tspecht have you example code?

this will be solved through #694 which is actually on hold, need to stabilize other issues/pr first

Any updates on this?

@tspecht @geoherna #694 have merged to master branch, please retry it, closing. thanks!

I can't find PureJSON function on context...did this get renamed or ever in release?

Is this in master only or a release build....

As of now(v1.3.0), This feature is still only existing in master, not in a release. :disappointed:

Related: https://github.com/golang/go/issues/14749

Workaround:

var (
        buf     bytes.Buffer
        encoder = json.NewEncoder(&buf)
    )

        // important
    encoder.SetEscapeHTML(false)

    _ = encoder.Encode(responseData)

    c.DataFromReader(http.StatusOK, int64(buf.Len()), "application/json; charset=utf-8", &buf, map[string]string{})
Was this page helpful?
0 / 5 - 0 ratings

Related issues

Bloomca picture Bloomca  路  3Comments

ghost picture ghost  路  3Comments

lilee picture lilee  路  3Comments

oryband picture oryband  路  3Comments

mdnight picture mdnight  路  3Comments