package rest import ( "net/http" "github.com/go-chi/render" "github.com/pkg/errors" "git.ifooth.com/common/pkg/components" ) var ( // UnauthorizedError 未登入 UnauthorizedError = errors.New("用户未登入") ) // HandlerFunc type RestHandlerFunc func(r *http.Request) (interface{}, error) func (h RestHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) { data, err := h(r) if err != nil { // handle returned error here. render.Render(w, r, AbortWithBadRequestError(err)) return } switch v := data.(type) { case render.Renderer: if err := v.Render(w, r); err != nil { render.Render(w, r, AbortWithBadRequestError(err)) return } default: render.JSON(w, r, data) } } // Result 返回的标准结构 type Response 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 *Response) Render(w http.ResponseWriter, r *http.Request) error { statusCode := res.HTTPStatusCode if statusCode == 0 { statusCode = http.StatusOK } res.RequestId = components.RequestIDValue(r.Context()) render.Status(r, statusCode) return nil } // UnauthorizedErrRender 未登入返回 func AbortWithUnauthorizedError(err error) render.Renderer { return &Response{ Code: 1401, Message: err.Error(), HTTPStatusCode: http.StatusUnauthorized, } } // AbortWithBadRequestError 错误 func AbortWithBadRequestError(err error) render.Renderer { return &Response{ Code: 1400, Message: err.Error(), HTTPStatusCode: http.StatusBadRequest, } } // AbortWithWithForbiddenError 没有权限 func AbortWithWithForbiddenError(err error) render.Renderer { return &Response{ Code: 1403, Message: err.Error(), HTTPStatusCode: http.StatusForbidden, } } // OKRender 正常返回 func OKRender(data interface{}) render.Renderer { return &Response{Data: data} }