Files
response/response.go
2025-12-09 16:17:38 +08:00

58 lines
1.2 KiB
Go

package response
import (
"net/http"
"github.com/gin-gonic/gin"
"google.golang.org/grpc/status"
)
type Response struct {
Code int `json:"code"`
Message string `json:"message"`
Total int64 `json:"total,omitempty"`
Data any `json:"data"`
}
func getErrorCodeAndMessage(err error) (int, string) {
if st, ok := status.FromError(err); ok {
return int(st.Code()), st.Message()
}
return CodeFaild, "未知错误类型或内部服务错误"
}
func Result(c *gin.Context, err error, data any) {
if err == nil {
c.JSON(http.StatusOK, Response{Code: CodeSuccess, Message: MsgSuccess, Data: data})
return
}
code, message := getErrorCodeAndMessage(err)
httpStatus := http.StatusOK
c.JSON(httpStatus, Response{
Code: code,
Message: message,
Data: data,
})
}
func PageResult(c *gin.Context, err error, total int64, data any) {
if err == nil {
c.JSON(http.StatusOK, Response{Code: CodeSuccess, Message: MsgSuccess, Total: total, Data: data})
return
}
code, message := getErrorCodeAndMessage(err)
httpStatus := http.StatusOK
c.JSON(httpStatus, Response{
Code: code,
Message: message,
Total: total,
Data: data,
})
}