fix(httpx): Resolve HTML escaping issue during JSON serialization (#5032)

This commit is contained in:
Joe Bird
2025-07-31 19:53:40 +08:00
committed by GitHub
parent 63ec989376
commit 93c11a7eb7
2 changed files with 124 additions and 2 deletions

View File

@@ -1,6 +1,7 @@
package httpx
import (
"bytes"
"context"
"encoding/json"
"errors"
@@ -172,8 +173,28 @@ func doHandleError(w http.ResponseWriter, err error, handler func(error) (int, a
}
}
func doMarshalJson(v any) ([]byte, error) {
// why not use json.Marshal? https://github.com/golang/go/issues/28453
// it change the behavior of json.Marshal, like & -> \u0026, < -> \u003c, > -> \u003e
// which is not what we want in logic response
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(false)
if err := enc.Encode(v); err != nil {
return nil, err
}
bs := buf.Bytes()
// Remove trailing newline added by json.Encoder.Encode
if len(bs) > 0 && bs[len(bs)-1] == '\n' {
bs = bs[:len(bs)-1]
}
return bs, nil
}
func doWriteJson(w http.ResponseWriter, code int, v any) error {
bs, err := json.Marshal(v)
bs, err := doMarshalJson(v)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return fmt.Errorf("marshal json failed, error: %w", err)