| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- package response
- import (
- "context"
- "errors"
- "net/http"
- "github.com/zeromicro/go-zero/core/logx"
- "github.com/zeromicro/go-zero/rest/httpx"
- )
- type Body struct {
- Code int `json:"code"`
- Msg string `json:"msg"`
- Data interface{} `json:"data,omitempty"`
- }
- type CodeError struct {
- code int
- msg string
- }
- func NewCodeError(code int, msg string) *CodeError {
- return &CodeError{code: code, msg: msg}
- }
- func (e *CodeError) Error() string { return e.msg }
- func (e *CodeError) Code() int { return e.code }
- func ErrBadRequest(msg string) *CodeError { return NewCodeError(400, msg) }
- func ErrUnauthorized(msg string) *CodeError { return NewCodeError(401, msg) }
- func ErrForbidden(msg string) *CodeError { return NewCodeError(403, msg) }
- func ErrNotFound(msg string) *CodeError { return NewCodeError(404, msg) }
- func ErrConflict(msg string) *CodeError { return NewCodeError(409, msg) }
- func Setup() {
- httpx.SetOkHandler(func(_ context.Context, v any) any {
- if v == nil {
- return Body{Code: 0, Msg: "ok"}
- }
- return Body{Code: 0, Msg: "ok", Data: v}
- })
- httpx.SetErrorHandlerCtx(func(ctx context.Context, err error) (int, any) {
- var ce *CodeError
- if errors.As(err, &ce) {
- return http.StatusOK, Body{Code: ce.Code(), Msg: ce.Error()}
- }
- logx.WithContext(ctx).Errorf("internal error: %+v", err)
- return http.StatusOK, Body{Code: 500, Msg: "服务器内部错误"}
- })
- }
|