| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- package core
- import (
- "github.com/demdxx/gocast"
- "github.com/gin-gonic/gin"
- "net/http"
- "time"
- )
- type Response struct {
- Code int32 `json:"code"` // 响应码
- Msg string `json:"msg"` // 响应消息
- Data any `json:"data"` // 响应信息 ,omitempty
- Time int64 `json:"time"` // 服务器时间
- }
- var (
- ResponseMissAuthToken = &Response{Code: 501, Msg: "Authorization为空"}
- ResponseTokenInvalid = &Response{Code: 501, Msg: "Token过期失效"}
- ResponseSignError = &Response{Code: 503, Msg: "签名错误"}
- )
- func (rc *Response) Error() string {
- return rc.Msg
- }
- func (rc *Response) SetMsg(msg string) *Response {
- return &Response{
- Code: rc.Code,
- Msg: msg,
- }
- }
- func (rc *Response) SetData(data any) *Response {
- return &Response{
- Code: rc.Code,
- Msg: rc.Msg,
- Data: data,
- }
- }
- func (rc *Response) setTime() *Response {
- return &Response{
- Code: rc.Code,
- Msg: rc.Msg,
- Data: rc.Data,
- Time: time.Now().Unix(),
- }
- }
- func newFailErrorMsg(msg string) *Response {
- return &Response{Code: 500, Msg: msg, Time: time.Now().Unix()}
- }
- func newSuccessMsg() *Response {
- return &Response{Code: 200, Msg: "success", Time: time.Now().Unix()}
- }
- func Resp(c *gin.Context, args ...interface{}) {
- var data interface{}
- if len(args) == 0 {
- c.JSON(http.StatusOK, newSuccessMsg())
- return
- }
- data = args[0]
- switch data.(type) {
- case *Response:
- c.JSON(http.StatusOK, data.(*Response).setTime())
- case string:
- c.JSON(http.StatusOK, newFailErrorMsg(gocast.ToString(data)))
- case error:
- c.JSON(http.StatusOK, newFailErrorMsg(data.(error).Error()))
- default:
- c.JSON(http.StatusOK, newSuccessMsg().SetData(data))
- }
- }
|