150 lines
2.5 KiB
Go
150 lines
2.5 KiB
Go
package res
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"servicebase/pkg/cerrors"
|
|
"servicebase/pkg/log"
|
|
"servicebase/pkg/req"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
const (
|
|
CodeSuccess = 200
|
|
CodeFailed = 500
|
|
AuthERR = 400
|
|
)
|
|
|
|
type Fn func(c *gin.Context) Response
|
|
|
|
func WrapApi(f Fn) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
if f == nil {
|
|
c.JSON(http.StatusInternalServerError, Failed("biz fn is nil"))
|
|
c.Abort()
|
|
return
|
|
}
|
|
rsp := f(c)
|
|
if rsp.Cause != nil {
|
|
log.ErrorFWithCtx(c.Request.Context(), "api err :[%+v]", rsp.Cause)
|
|
}
|
|
c.JSON(http.StatusOK, rsp)
|
|
}
|
|
}
|
|
|
|
type Response struct {
|
|
Code int `json:"code"`
|
|
Msg string `json:"msg,omitempty"`
|
|
Data interface{} `json:"data,omitempty"`
|
|
Cause error `json:"-"`
|
|
}
|
|
|
|
type PageData struct {
|
|
Total int64 `json:"total"`
|
|
CountPage int64 `json:"count_page"`
|
|
HasNext bool `json:"has_next"`
|
|
List interface{} `json:"list"`
|
|
}
|
|
|
|
func (t Response) Success() bool {
|
|
return t.Code == CodeSuccess
|
|
}
|
|
|
|
func Success(data interface{}) Response {
|
|
return Response{
|
|
Code: CodeSuccess,
|
|
Msg: "",
|
|
Data: data,
|
|
}
|
|
}
|
|
|
|
func Empty() Response {
|
|
return Response{
|
|
Code: CodeSuccess,
|
|
Msg: "",
|
|
}
|
|
}
|
|
|
|
func Page(pageable req.Page, count int64, data interface{}) Response {
|
|
cnt := (count + pageable.Size - 1) / pageable.Size
|
|
return Success(PageData{
|
|
Total: count,
|
|
CountPage: cnt,
|
|
HasNext: pageable.Size < cnt,
|
|
List: data,
|
|
})
|
|
}
|
|
|
|
func Failed(msg string) Response {
|
|
return Response{
|
|
Code: CodeFailed,
|
|
Msg: msg,
|
|
}
|
|
}
|
|
|
|
func Error(e error) Response {
|
|
return Response{
|
|
Code: CodeFailed,
|
|
Msg: e.Error(),
|
|
}
|
|
}
|
|
|
|
func ErrorMsg(msg string, e error) Response {
|
|
return Response{
|
|
Code: CodeFailed,
|
|
Msg: fmt.Sprintf("%s,%v", msg, e),
|
|
}
|
|
}
|
|
|
|
func ErrorCode(code int) Response {
|
|
return Response{
|
|
Code: code,
|
|
Msg: cerrors.Msg(code),
|
|
}
|
|
}
|
|
|
|
func FailedWithCause(msg string, err error) Response {
|
|
return Response{
|
|
Code: CodeFailed,
|
|
Msg: msg,
|
|
Cause: err,
|
|
}
|
|
}
|
|
|
|
func Cause(err error) Response {
|
|
return Response{
|
|
Code: CodeFailed,
|
|
Msg: err.Error(),
|
|
Cause: err,
|
|
}
|
|
}
|
|
|
|
func AuthFailed(msg string) Response {
|
|
return Response{
|
|
Code: AuthERR,
|
|
Msg: msg,
|
|
}
|
|
}
|
|
|
|
func FailedF(msg string, args ...interface{}) Response {
|
|
return Response{
|
|
Code: CodeFailed,
|
|
Msg: fmt.Sprintf(msg, args...),
|
|
}
|
|
}
|
|
|
|
type IDBody struct {
|
|
ID string `json:"id" form:"id" uri:"id"`
|
|
}
|
|
|
|
type ImageDTO struct {
|
|
ImageID string `json:"image_id"`
|
|
ImageUrl string `json:"image_url"`
|
|
}
|
|
|
|
type AccessTokenDTO struct {
|
|
AccessToken string
|
|
ExpireTime string
|
|
}
|