feat:完善信息
This commit is contained in:
@ -1,99 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"SciencesServer/config"
|
||||
"SciencesServer/serve/logger"
|
||||
"SciencesServer/utils"
|
||||
"errors"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
const (
|
||||
SuccessCode = 200 //成功的状态码
|
||||
FailureCode = 999 //失败的状态码
|
||||
)
|
||||
|
||||
type response struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Data interface{} `json:"data"`
|
||||
}
|
||||
|
||||
type ApiHandle func(c *gin.Context) interface{}
|
||||
|
||||
func GetSession() ApiHandle {
|
||||
return func(c *gin.Context) interface{} {
|
||||
value, _ := c.Get(config.TokenForSession)
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
func Bind(req interface{}) ApiHandle {
|
||||
return func(c *gin.Context) interface{} {
|
||||
var err error
|
||||
|
||||
if c.Request.Method == "GET" {
|
||||
err = c.ShouldBindQuery(req)
|
||||
} else {
|
||||
err = c.ShouldBindBodyWith(req, binding.JSON)
|
||||
}
|
||||
if err != nil {
|
||||
logger.ErrorF("Request URL【%s】Params Bind Error:%v", c.Request.URL, err)
|
||||
return errors.New("参数异常/缺失")
|
||||
}
|
||||
c.Set("params", utils.AnyToJSON(req))
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func APISuccess(data ...interface{}) ApiHandle {
|
||||
return func(c *gin.Context) interface{} {
|
||||
resp := &response{
|
||||
Code: SuccessCode,
|
||||
Message: "ok",
|
||||
}
|
||||
if len(data) > 0 {
|
||||
resp.Data = data[0]
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func APIFailure(err error) ApiHandle {
|
||||
return func(c *gin.Context) interface{} {
|
||||
resp := &response{
|
||||
Code: FailureCode,
|
||||
Message: "failure",
|
||||
}
|
||||
if err != nil {
|
||||
resp.Message = err.Error()
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
c.Abort()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func APIResponse(err error, data ...interface{}) ApiHandle {
|
||||
return func(c *gin.Context) interface{} {
|
||||
resp := &response{
|
||||
Code: SuccessCode,
|
||||
Message: "ok",
|
||||
}
|
||||
if err != nil {
|
||||
resp.Code = FailureCode
|
||||
resp.Message = err.Error()
|
||||
c.JSON(http.StatusOK, resp)
|
||||
c.Abort()
|
||||
return nil
|
||||
}
|
||||
if len(data) > 0 {
|
||||
resp.Data = data[0]
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
return nil
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user