Files
cms-server/utils/response.go
Asai Neko 640ef2fc01
All checks were successful
Server Check Build (NixCN CMS) TeamCity build finished
Strictly define the state of the return data structure
Signed-off-by: Asai Neko <sugar@sne.moe>
2026-03-13 11:26:53 +08:00

55 lines
1.1 KiB
Go

package utils
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/goccy/go-json"
)
type RespStatus struct {
Code int `json:"code" validate:"required"`
Status string `json:"status" validate:"required"`
ErrorId string `json:"error_id" validate:"required"`
Data any `json:"data" validate:"required"`
}
func render(c *gin.Context, code int, errId string, data []any, abort bool) {
resp := RespStatus{
Code: code,
Status: http.StatusText(code),
ErrorId: errId,
}
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, errId string, data ...any) {
render(c, code, errId, data, false)
}
func HttpAbort(c *gin.Context, code int, errId string, data ...any) {
render(c, code, errId, data, true)
}