mh_server/controller/base.go
2022-08-31 15:25:45 +08:00

131 lines
2.5 KiB
Go

package controller
import (
"encoding/json"
"encoding/xml"
"fmt"
"mh-server/lib/status"
"github.com/codinl/go-logger"
"github.com/gin-gonic/gin"
)
type RespRet struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
func RespJson(c *gin.Context, code int, data interface{}) {
result := RespRet{
Code: code,
Msg: status.StatusMsg(code),
Data: data,
}
body, err := json.Marshal(result)
if err != nil {
logger.Error(err)
body = []byte{}
}
c.Data(status.OK, "application/json; charset=utf-8", body)
c.Abort()
}
func RespOK(c *gin.Context, data interface{}) {
result := RespRet{
Code: 200,
Msg: "成功",
Data: data,
}
body, err := json.Marshal(result)
if err != nil {
logger.Error(err)
body = []byte{}
}
c.Data(status.OK, "application/json; charset=utf-8", body)
c.Abort()
}
func RespError(c *gin.Context, data ...string) {
var respMsg string
if len(data) > 0 {
respMsg = data[0]
} else {
respMsg = "服务器开小差了"
}
result := RespRet{
Code: 500,
Msg: respMsg,
Data: "",
}
body, err := json.Marshal(result)
if err != nil {
logger.Error(err)
body = []byte{}
}
c.Data(status.OK, "application/json; charset=utf-8", body)
c.Abort()
}
func Resp(c *gin.Context, code int, msg string, data interface{}) {
result := RespRet{
Code: code,
Msg: msg,
Data: data,
}
body, err := json.Marshal(result)
if err != nil {
logger.Error(err)
body = []byte{}
}
c.Data(status.OK, "application/json; charset=utf-8", body)
c.Abort()
}
func RespNotice(c *gin.Context, code string, msg string) {
result := struct {
Code string `json:"code"`
Message string `json:"message"`
}{
Code: code,
Message: msg,
}
body, err := json.Marshal(result)
if err != nil {
logger.Error(err)
body = []byte{}
}
c.Data(status.OK, "application/json; charset=utf-8", body)
c.Abort()
}
func RespBodyXML(c *gin.Context, data interface{}) {
body, err := xml.Marshal(data)
if err != nil {
logger.Error(err)
body = []byte{}
}
fmt.Println("回复消息:", string(body))
c.Data(status.OK, "application/xml; charset=utf-8", body)
c.Abort()
}
func Toast(c *gin.Context, data interface{}) {
result := struct {
Code int `json:"code"`
Msg interface{} `json:"msg"`
Data interface{} `json:"data"`
}{
Code: status.ToastErr,
Msg: data,
Data: data,
}
body, err := json.Marshal(result)
if err != nil {
logger.Error(err)
body = []byte{}
}
c.Data(status.OK, "application/json; charset=utf-8", body)
c.Abort()
}