package httpresult import ( // "go-scaffold/common/logwriter" "net/http" "github.com/zeromicro/go-zero/rest/httpx" ) const defaultErrCode = 1001 const defaultSuccessCode = 200 type CodeError struct { Code int `json:"code"` Message string `json:"msg"` Success bool `json:"success"` ErrMsg interface{} `json:"err_msg"` } type CodeErrorResponse struct { Code int `json:"code"` Message string `json:"msg"` Success bool `json:"success"` ErrMsg interface{} `json:"err_msg"` } type CodeSuccessResponse struct { Code int `json:"code"` Message string `json:"msg"` Success bool `json:"success"` Data interface{} `json:"data"` } // http 错误返回 func ErrorResult(msg string, err_msg interface{}) error { return &CodeError{Code: defaultErrCode, Message: msg, Success: false, ErrMsg: err_msg} } // http 默认错误返回 func ErrorResultDefault(msg string) error { return ErrorResult(msg, "") } // 错误方法返回 func (e *CodeError) Error() string { return e.Message } // 错误数据赋值 func (e *CodeError) ErrorData() *CodeErrorResponse { return &CodeErrorResponse{ Code: e.Code, Message: e.Message, Success: e.Success, ErrMsg: e.ErrMsg, } } // http 成功返回 func SuccessResult(msg string, data interface{}) (res *CodeSuccessResponse) { return &CodeSuccessResponse{Code: defaultSuccessCode, Message: msg, Success: true, Data: data} } // http 参数错误返回 func ParamErrorResult(r *http.Request, w http.ResponseWriter, err error) { msg := &CodeErrorResponse{ Code: 403, Message: "请求参数错误", Success: false, ErrMsg: err.Error(), } httpx.WriteJson(w, http.StatusOK, msg) } // http 通用错误返回 func CommonErrorResult(r *http.Request, w http.ResponseWriter, err error) { if r.PostForm != nil { // logwriter.ErrorLogWriter(r.Context(), r.URL.Path, err.Error(), r.PostForm) } else { // logwriter.ErrorLogWriter(r.Context(), r.URL.Path, err.Error(), nil) } msg := &CodeErrorResponse{ Code: defaultErrCode, Message: "请求失败", Success: false, ErrMsg: err.Error(), } httpx.WriteJson(w, http.StatusOK, msg) } // http auth错误返回 func AuthErrorResult(r *http.Request, w http.ResponseWriter, err error) { msg := &CodeErrorResponse{ Code: 401, Message: "鉴权失败", Success: false, ErrMsg: err.Error(), } httpx.WriteJson(w, http.StatusUnauthorized, msg) } // http 权限错误返回 func PermissionErrorResult(r *http.Request, w http.ResponseWriter, err error) { msg := &CodeErrorResponse{ Code: 403, Message: "权限校验失败", Success: false, ErrMsg: err.Error(), } httpx.WriteJson(w, 403, msg) } // http 503错误返回 func ServiceUnavailableErrorResult(w http.ResponseWriter, massage string) { msg := &CodeErrorResponse{ Code: 503, Message: "服务不可用", Success: false, ErrMsg: nil, } httpx.WriteJson(w, 503, msg) }