mirror of
https://github.com/infinite-iroha/touka.git
synced 2026-06-13 15:47:38 +08:00
Update context.go
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
This commit is contained in:
parent
45c6d36748
commit
d0fa14c3c5
1 changed files with 4 additions and 3 deletions
|
|
@ -420,16 +420,17 @@ func (c *Context) JSON(code int, obj any) {
|
||||||
// JSONBuf 先将 JSON 编码到 buffer, 成功后再写入状态码和响应体.
|
// JSONBuf 先将 JSON 编码到 buffer, 成功后再写入状态码和响应体.
|
||||||
// 与 JSON 相比,编码失败时可以正确返回 500 状态码,代价是多一次内存分配.
|
// 与 JSON 相比,编码失败时可以正确返回 500 状态码,代价是多一次内存分配.
|
||||||
func (c *Context) JSONBuf(code int, obj any) {
|
func (c *Context) JSONBuf(code int, obj any) {
|
||||||
data, err := json.Marshal(obj)
|
var buf bytes.Buffer
|
||||||
if err != nil {
|
if err := json.MarshalWrite(&buf, obj); err != nil {
|
||||||
errMsg := fmt.Errorf("failed to marshal JSON: %w", err)
|
errMsg := fmt.Errorf("failed to marshal JSON: %w", err)
|
||||||
c.AddError(errMsg)
|
c.AddError(errMsg)
|
||||||
c.ErrorUseHandle(http.StatusInternalServerError, errMsg)
|
c.ErrorUseHandle(http.StatusInternalServerError, errMsg)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c.Writer.Header().Set("Content-Type", "application/json; charset=utf-8")
|
c.Writer.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
c.Writer.WriteHeader(code)
|
c.Writer.WriteHeader(code)
|
||||||
c.Writer.Write(data)
|
c.Writer.Write(buf.Bytes())
|
||||||
}
|
}
|
||||||
|
|
||||||
// GOB 向响应写入GOB数据
|
// GOB 向响应写入GOB数据
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue