response.go 930 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package response
  2. import (
  3. "errors"
  4. "github.com/gin-gonic/gin"
  5. "net/http"
  6. )
  7. type Response struct {
  8. Code int `json:"code"`
  9. Message string `json:"message"`
  10. Data interface{} `json:"data"`
  11. }
  12. func HandleSuccess(ctx *gin.Context, data interface{}) {
  13. if data == nil {
  14. data = map[string]string{}
  15. }
  16. resp := Response{Code: errorCodeMap[ErrSuccess], Message: ErrSuccess.Error(), Data: data}
  17. ctx.JSON(http.StatusOK, resp)
  18. }
  19. func HandleError(ctx *gin.Context, httpCode int, err error, data interface{}) {
  20. if data == nil {
  21. data = map[string]string{}
  22. }
  23. resp := Response{Code: errorCodeMap[err], Message: err.Error(), Data: data}
  24. ctx.JSON(httpCode, resp)
  25. }
  26. type Error struct {
  27. Code int
  28. Message string
  29. }
  30. var errorCodeMap = map[error]int{}
  31. func newError(code int, msg string) error {
  32. err := errors.New(msg)
  33. errorCodeMap[err] = code
  34. return err
  35. }
  36. func (e Error) Error() string {
  37. return e.Message
  38. }