golang json.Marshal 避免转义html

在对接微信客服消息的时候,发现换行符、a标签等都被转义了。
调查发现是在对结构体调用json.Marshal发生的。

https://godoc.org/encoding/json#Marshal

String values encode as JSON strings coerced to valid UTF-8, replacing invalid bytes with the Unicode replacement rune. The angle brackets “<” and “>” are escaped to “\u003c” and “\u003e” to keep some browsers from misinterpreting JSON output as HTML. Ampersand “&” is also escaped to “\u0026” for the same reason. This escaping can be disabled using an Encoder that had SetEscapeHTML(false) called on it.

json.Marshal 默认 escapeHtml 为 true, 会转义 <、>、&

func Marshal(v interface{}) ([]byte, error) {
    e := newEncodeState()

    err := e.marshal(v, encOpts{escapeHTML: true})
    if err != nil {
        return nil, err
    }
    buf := append([]byte(nil), e.Bytes()...)

    e.Reset()
    encodeStatePool.Put(e)

    return buf, nil
}

解决办法就是自定义一个encoder

    bf := bytes.NewBuffer([]byte{})
    jsonEncoder := json.NewEncoder(bf)
    jsonEncoder.SetEscapeHTML(false)

    err = jsonEncoder.Encode(msg)
    if err != nil {
        ...
    }

    log.Println(bf.String())

留下评论

电子邮件地址不会被公开。 必填项已用*标注