common.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package api
  2. import (
  3. "cockData/server/log"
  4. "github.com/gin-gonic/gin"
  5. "github.com/gin-gonic/gin/binding"
  6. )
  7. const (
  8. ResponseCodeSuccess = 200
  9. ResponseCodeErrorInternal = 30000 // 内部错误
  10. ResponseCodeErrorParams = 30001 // 参数错误
  11. ResponseCodeErrorSession = 30002 // 会话失效
  12. )
  13. // Response 通用返回结构
  14. type Response struct {
  15. Code int `json:"code"`
  16. Msg string `json:"message"`
  17. Data interface{} `json:"data"`
  18. }
  19. func CreateSuccessResponse(data interface{}) *Response {
  20. return &Response{
  21. Code: ResponseCodeSuccess,
  22. Msg: "Success",
  23. Data: data,
  24. }
  25. }
  26. func CreateErrorResponse(code int, msg string) *Response {
  27. log.Infof("返回错误%d,%s", code, msg)
  28. return &Response{
  29. Code: code,
  30. Msg: msg,
  31. Data: "",
  32. }
  33. }
  34. func CreateParamsErrorResponse() *Response {
  35. return CreateErrorResponse(ResponseCodeErrorParams, "参数错误")
  36. }
  37. func CreateInternalErrorResponse() *Response {
  38. return CreateErrorResponse(ResponseCodeErrorInternal, "内部错误")
  39. }
  40. func CreateSessionErrorResponse() *Response {
  41. return CreateErrorResponse(ResponseCodeErrorSession, "会话失效")
  42. }
  43. func CheckParams(context *gin.Context, obj interface{}) error {
  44. err := context.ShouldBindBodyWith(&obj, binding.JSON)
  45. log.Infof("请求参数 %s", obj)
  46. if err != nil {
  47. ResponseApi(context, *CreateParamsErrorResponse())
  48. }
  49. return err
  50. }
  51. func ResponseApiWithError(context *gin.Context, rep *Response, err error) {
  52. if err != nil {
  53. ResponseApi(context, *CreateInternalErrorResponse())
  54. } else {
  55. ResponseApi(context, *rep)
  56. }
  57. }
  58. // ResponseApi 创建一个200返回并中断context
  59. func ResponseApi(context *gin.Context, response Response) {
  60. log.Warnf("应答:%+v", response)
  61. context.AbortWithStatusJSON(200, response)
  62. }