response.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 Setup() {
  29. httpx.SetOkHandler(func(_ context.Context, v any) any {
  30. if v == nil {
  31. return Body{Code: 0, Msg: "ok"}
  32. }
  33. return Body{Code: 0, Msg: "ok", Data: v}
  34. })
  35. httpx.SetErrorHandlerCtx(func(ctx context.Context, err error) (int, any) {
  36. var ce *CodeError
  37. if errors.As(err, &ce) {
  38. return http.StatusOK, Body{Code: ce.Code(), Msg: ce.Error()}
  39. }
  40. logx.WithContext(ctx).Errorf("internal error: %+v", err)
  41. return http.StatusOK, Body{Code: 500, Msg: "服务器内部错误"}
  42. })
  43. }