112 lines
2.2 KiB
Go
112 lines
2.2 KiB
Go
package api
|
||
|
||
import (
|
||
"SciencesServer/config"
|
||
"SciencesServer/serve/logger"
|
||
"SciencesServer/utils"
|
||
"errors"
|
||
"net/http"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
"github.com/gin-gonic/gin/binding"
|
||
)
|
||
|
||
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 GetTenantID() ApiHandle {
|
||
return func(c *gin.Context) interface{} {
|
||
value := c.GetHeader(config.ContentForTenantID)
|
||
|
||
if value == "" {
|
||
return uint64(1)
|
||
}
|
||
return utils.StringToUnit64(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("参数异常/缺失【" + err.Error() + "】")
|
||
}
|
||
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
|
||
}
|
||
}
|