response.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package response
  2. import (
  3. "context"
  4. "errors"
  5. "net/http"
  6. "github.com/zeromicro/go-zero/core/logx"
  7. "github.com/zeromicro/go-zero/rest/httpx"
  8. )
  9. type Body struct {
  10. Code int `json:"code"`
  11. Msg string `json:"msg"`
  12. Data interface{} `json:"data,omitempty"`
  13. }
  14. type CodeError struct {
  15. code int
  16. msg string
  17. }
  18. func NewCodeError(code int, msg string) *CodeError {
  19. return &CodeError{code: code, msg: msg}
  20. }
  21. func (e *CodeError) Error() string { return e.msg }
  22. func (e *CodeError) Code() int { return e.code }
  23. func ErrBadRequest(msg string) *CodeError { return NewCodeError(400, msg) }
  24. func ErrUnauthorized(msg string) *CodeError { return NewCodeError(401, msg) }
  25. func ErrForbidden(msg string) *CodeError { return NewCodeError(403, msg) }
  26. func ErrNotFound(msg string) *CodeError { return NewCodeError(404, msg) }
  27. func ErrConflict(msg string) *CodeError { return NewCodeError(409, msg) }
  28. func ErrTooManyRequests(msg string) *CodeError { return NewCodeError(429, msg) }
  29. func Setup() {
  30. httpx.SetOkHandler(func(_ context.Context, v any) any {
  31. if v == nil {
  32. return Body{Code: 0, Msg: "ok"}
  33. }
  34. return Body{Code: 0, Msg: "ok", Data: v}
  35. })
  36. httpx.SetErrorHandlerCtx(func(ctx context.Context, err error) (int, any) {
  37. var ce *CodeError
  38. if errors.As(err, &ce) {
  39. return http.StatusOK, Body{Code: ce.Code(), Msg: ce.Error()}
  40. }
  41. logx.WithContext(ctx).Errorf("internal error: %+v", err)
  42. return http.StatusOK, Body{Code: 500, Msg: "服务器内部错误"}
  43. })
  44. }