功能代码
This commit is contained in:
67
response.go
Normal file
67
response.go
Normal file
@@ -0,0 +1,67 @@
|
||||
package response
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"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 CodeInternalServerError, "未知错误类型或内部服务错误"
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
if code == CodeInternalServerError || !errors.Is(err, ErrSuccess) && code == 0 {
|
||||
httpStatus = http.StatusInternalServerError
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
if code == CodeInternalServerError || !errors.Is(err, ErrSuccess) && code == 0 {
|
||||
httpStatus = http.StatusInternalServerError
|
||||
}
|
||||
|
||||
c.JSON(httpStatus, Response{
|
||||
Code: code,
|
||||
Message: message,
|
||||
Total: total,
|
||||
Data: data,
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user