base.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package handler
  2. import (
  3. "net/http"
  4. "youngee_b_api/consts"
  5. "youngee_b_api/util"
  6. "github.com/gin-gonic/gin"
  7. "github.com/sirupsen/logrus"
  8. )
  9. type BaseHandler interface {
  10. getContext() *gin.Context
  11. getResponse() interface{}
  12. getRequest() interface{}
  13. run()
  14. checkParam() error
  15. }
  16. func baseRun(baseHandler BaseHandler) {
  17. ctx := baseHandler.getContext()
  18. method := ctx.Request.Method
  19. req := baseHandler.getRequest()
  20. var err error
  21. if method == http.MethodPost || method == http.MethodPut {
  22. err = ctx.ShouldBindJSON(req)
  23. } else if method == http.MethodGet {
  24. err = ctx.BindQuery(req)
  25. }
  26. if err != nil {
  27. util.PackErrorResp(ctx, consts.ErrorParamCheck)
  28. ctx.Abort()
  29. logrus.Infof("[baseHandler] bind json error,err:%+v", err)
  30. return
  31. }
  32. if err = baseHandler.checkParam(); err != nil {
  33. util.PackErrorResp(ctx, consts.ErrorParamCheck)
  34. ctx.Abort()
  35. logrus.Infof("[baseHandler] checkParam error,err:%+v", err)
  36. return
  37. }
  38. baseHandler.run()
  39. if ctx.IsAborted() {
  40. return
  41. }
  42. resp := baseHandler.getResponse()
  43. ctx.JSON(http.StatusOK, resp)
  44. logrus.Infof("[baseHandler] http success")
  45. }