You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
51 lines
960 B
Go
51 lines
960 B
Go
package utils
|
|
|
|
import (
|
|
syserrors "errors"
|
|
"github.com/gin-gonic/gin"
|
|
"insure/e"
|
|
)
|
|
|
|
type Result struct {
|
|
Code string `json:"code"`
|
|
Message string `json:"message"`
|
|
Data Data `json:"data"`
|
|
}
|
|
|
|
type Data map[string]interface{}
|
|
|
|
func JsonHandler(api func(c *gin.Context) (Data, error)) func(c *gin.Context) {
|
|
return func(c *gin.Context) {
|
|
data, err := api(c)
|
|
result := Result{}
|
|
if err != nil {
|
|
result = buildErrorResult(err)
|
|
result.Data = data
|
|
} else {
|
|
result.Code = Success
|
|
result.Message = "成功"
|
|
result.Data = data
|
|
}
|
|
c.JSON(200, result)
|
|
}
|
|
}
|
|
|
|
func Handler(api func(c *gin.Context)) func(c *gin.Context) {
|
|
return api
|
|
}
|
|
|
|
func buildErrorResult(err error) Result {
|
|
result := Result{}
|
|
switch err.(type) {
|
|
case *e.Error:
|
|
var bizErr *e.Error
|
|
syserrors.As(err, &bizErr)
|
|
result.Code = bizErr.Code
|
|
result.Message = bizErr.Message
|
|
default:
|
|
result.Code = Error
|
|
result.Message = "系统异常"
|
|
}
|
|
return result
|
|
}
|