response.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package utils
  2. import (
  3. "net/http"
  4. "time"
  5. )
  6. // api结构体
  7. type APIException struct {
  8. Code int `json:"code"`
  9. Success bool `json:"success"`
  10. Msg string `json:"msg"`
  11. Timestamp int64 `json:"timestamp"`
  12. Result interface{} `json:"result"`
  13. }
  14. // 实现接口
  15. func (e *APIException) Error() string {
  16. return e.Msg
  17. }
  18. func newAPIException(code int, msg string, data interface{}, success bool) *APIException {
  19. return &APIException{
  20. Code: code,
  21. Success: success,
  22. Msg: msg,
  23. Timestamp: time.Now().Unix(),
  24. Result: data,
  25. }
  26. }
  27. // 500 错误处理
  28. func ServerError() *APIException {
  29. return newAPIException(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError), nil, false)
  30. }
  31. // 404 错误
  32. func NotFound() *APIException {
  33. return newAPIException(http.StatusNotFound, http.StatusText(http.StatusNotFound), nil, false)
  34. }
  35. // 未知错误
  36. func UnknownError(message string) *APIException {
  37. return newAPIException(http.StatusForbidden, message, nil, false)
  38. }
  39. // 参数错误
  40. func ParameterError(message string) *APIException {
  41. return newAPIException(http.StatusBadRequest, message, nil, false)
  42. }
  43. // 授权错误
  44. func AuthError(message string) *APIException {
  45. return newAPIException(http.StatusBadRequest, message, nil, false)
  46. }
  47. // 200
  48. func ResponseJson(message string, data interface{}, success bool) *APIException {
  49. return newAPIException(http.StatusOK, message, data, success)
  50. }