DriveLinked/pkg/dto/response.go

55 lines
1.2 KiB
Go
Raw Normal View History

2022-04-03 12:30:50 +08:00
package dto
import (
"drive-linked/pkg/serializer"
"github.com/kataras/golog"
2022-04-03 12:30:50 +08:00
"github.com/kataras/iris/v12"
"net/http"
)
type Response struct {
Ctx iris.Context
}
const errJsonUnmarshalMsg = "{\"code\":500,\"msg\":\"Json解析错误请联系管理员\",\"data\":null}"
2022-04-03 12:30:50 +08:00
func NewResponse(ctx iris.Context) *Response {
return &Response{Ctx: ctx}
}
// 成功 统一处理
func (r *Response) Success(data interface{}) {
resp := serializer.ResponseSerial{Code: http.StatusOK, Data: data}
_, err := r.Ctx.JSON(resp)
2022-04-03 12:30:50 +08:00
if err != nil {
golog.Error("Json解析错误: ", resp)
2022-04-03 12:30:50 +08:00
r.Ctx.Write([]byte(errJsonUnmarshalMsg))
return
}
}
// 失败 统一处理
2022-04-05 18:16:20 +08:00
func (r *Response) Error(code int, msg string) {
resp := serializer.ResponseSerial{Code: code, Msg: msg}
_, err := r.Ctx.JSON(resp)
2022-04-03 12:30:50 +08:00
if err != nil {
r.Ctx.Write([]byte(errJsonUnmarshalMsg))
return
}
}
// 参数类型错误
2022-04-05 18:16:20 +08:00
func (r *Response) ErrBadRequest() {
r.Error(http.StatusBadRequest, "请求参数错误")
}
// 未登录/未授权错误
func (r *Response) ErrUnauthorized() {
r.Error(http.StatusUnauthorized, "未登录")
2022-04-03 12:30:50 +08:00
}
2022-04-09 11:48:44 +08:00
// 账号或密码错误
func (r *Response) ErrBadAccPasswd() {
r.Error(serializer.ErrBadLogin, "账号或密码错误")
}