package rest import ( "net/http" "github.com/go-chi/render" "github.com/pkg/errors" ) var ( // UnauthorizedError 未登入 UnauthorizedError = errors.New("用户未登入") ) // APIResponse 返回的标准结构 type APIResponse struct { Err error `json:"-"` // low-level runtime error HTTPStatusCode int `json:"-"` // http response status code Code int `json:"code"` Message string `json:"message"` RequestId string `json:"request_id"` Data interface{} `json:"data"` } // Render chi Render 实现 func (res *APIResponse) Render(w http.ResponseWriter, r *http.Request) error { statusCode := res.HTTPStatusCode if statusCode == 0 { statusCode = http.StatusOK } res.RequestId = RequestIDValue(r.Context()) render.Status(r, statusCode) return nil } // UnauthorizedErrRender 未登入返回 func AbortWithUnauthorizedError(err error) render.Renderer { return &APIResponse{ Code: 1401, Message: err.Error(), HTTPStatusCode: http.StatusUnauthorized, } } // AbortWithBadRequestError 错误 func AbortWithBadRequestError(err error) render.Renderer { return &APIResponse{ Code: 1400, Message: err.Error(), HTTPStatusCode: http.StatusBadRequest, } } // AbortWithBadRequestError 错误 func APIError(err error) render.Renderer { return &APIResponse{ Code: 1400, Message: err.Error(), HTTPStatusCode: http.StatusBadRequest, } } // AbortWithWithForbiddenError 没有权限 func AbortWithWithForbiddenError(err error) render.Renderer { return &APIResponse{ Code: 1403, Message: err.Error(), HTTPStatusCode: http.StatusForbidden, } } // OKRender 正常返回 func APIOK(data interface{}) render.Renderer { return &APIResponse{Data: data} }