Files
cms-server/utils/response.go
2026-01-20 17:48:52 +08:00

55 lines
1.0 KiB
Go

package utils
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/goccy/go-json"
)
type RespStatus struct {
Code int `json:"code"`
ErrorId string `json:"error_id"`
Status string `json:"status"`
Data any `json:"data"`
}
func render(c *gin.Context, code int, id string, status string, data []any, abort bool) {
resp := RespStatus{
Code: code,
ErrorId: id,
Status: status,
}
switch len(data) {
case 0:
resp.Data = nil
case 1:
resp.Data = data[0]
default:
resp.Data = data
}
jsonBytes, err := json.Marshal(resp)
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
c.Header("Content-Type", "application/json; charset=utf-8")
if abort {
c.AbortWithStatus(code)
} else {
c.Status(code)
}
_, _ = c.Writer.Write(jsonBytes)
}
func HttpResponse(c *gin.Context, code int, id string, status string, data ...any) {
render(c, code, id, status, data, false)
}
func HttpAbort(c *gin.Context, code int, id string, status string, data ...any) {
render(c, code, id, status, data, true)
}