pkg/http/rest/response.go

80 lines
1.8 KiB
Go
Raw Normal View History

2024-12-28 12:26:36 +00:00
package rest
2023-04-09 15:04:57 +00:00
import (
"net/http"
"github.com/go-chi/render"
"github.com/pkg/errors"
)
var (
// UnauthorizedError 未登入
UnauthorizedError = errors.New("用户未登入")
)
2024-12-28 12:01:56 +00:00
// APIResponse 返回的标准结构
type APIResponse struct {
2023-04-09 15:04:57 +00:00
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 实现
2024-12-28 12:01:56 +00:00
func (res *APIResponse) Render(w http.ResponseWriter, r *http.Request) error {
2023-04-09 15:04:57 +00:00
statusCode := res.HTTPStatusCode
if statusCode == 0 {
statusCode = http.StatusOK
}
2024-12-28 12:26:36 +00:00
res.RequestId = RequestIDValue(r.Context())
2023-04-09 15:04:57 +00:00
render.Status(r, statusCode)
return nil
}
// UnauthorizedErrRender 未登入返回
func AbortWithUnauthorizedError(err error) render.Renderer {
2024-12-28 12:01:56 +00:00
return &APIResponse{
2023-04-09 15:04:57 +00:00
Code: 1401,
Message: err.Error(),
HTTPStatusCode: http.StatusUnauthorized,
}
}
// AbortWithBadRequestError 错误
func AbortWithBadRequestError(err error) render.Renderer {
2024-12-28 12:01:56 +00:00
return &APIResponse{
Code: 1400,
Message: err.Error(),
HTTPStatusCode: http.StatusBadRequest,
}
}
// AbortWithBadRequestError 错误
func APIError(err error) render.Renderer {
return &APIResponse{
2023-04-09 15:04:57 +00:00
Code: 1400,
Message: err.Error(),
HTTPStatusCode: http.StatusBadRequest,
}
}
// AbortWithWithForbiddenError 没有权限
func AbortWithWithForbiddenError(err error) render.Renderer {
2024-12-28 12:01:56 +00:00
return &APIResponse{
2023-04-09 15:04:57 +00:00
Code: 1403,
Message: err.Error(),
HTTPStatusCode: http.StatusForbidden,
}
}
// OKRender 正常返回
2024-12-28 12:01:56 +00:00
func APIOK(data interface{}) render.Renderer {
return &APIResponse{Data: data}
2023-04-09 15:04:57 +00:00
}