Fix response structure error and router error

Signed-off-by: Asai Neko <sugar@sne.moe>
This commit is contained in:
2026-01-20 17:48:52 +08:00
parent 5e17bbd965
commit 9b83ab565a
7 changed files with 55 additions and 28 deletions

View File

@@ -1,6 +1,11 @@
package utils
import "github.com/gin-gonic/gin"
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/goccy/go-json"
)
type RespStatus struct {
Code int `json:"code"`
@@ -9,22 +14,41 @@ type RespStatus struct {
Data any `json:"data"`
}
func HttpResponse(c *gin.Context, code int, errorId string, status string, data ...any) {
var resp = RespStatus{
func render(c *gin.Context, code int, id string, status string, data []any, abort bool) {
resp := RespStatus{
Code: code,
ErrorId: errorId,
ErrorId: id,
Status: status,
Data: data,
}
c.JSON(code, resp)
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 HttpAbort(c *gin.Context, code int, errorId string, status string, data ...any) {
var resp = RespStatus{
Code: code,
ErrorId: errorId,
Status: status,
Data: data,
}
c.AbortWithStatusJSON(code, resp)
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)
}