另客网go项目公用的代码库

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package request
  2. import (
  3. "fmt"
  4. "net/http"
  5. "runtime"
  6. "github.com/gin-gonic/gin"
  7. "github.com/sirupsen/logrus"
  8. )
  9. type Checker interface {
  10. Check() error
  11. }
  12. func ParseParamFail(ctx *gin.Context, r interface{}, fs ...func() error) bool {
  13. if r != nil {
  14. if Fail(ctx, http.StatusBadRequest, ctx.ShouldBind(r)) {
  15. return true
  16. }
  17. if checker, ok := r.(Checker); ok {
  18. return Fail(ctx, http.StatusBadRequest, checker.Check())
  19. }
  20. }
  21. for _, f := range fs {
  22. if Fail(ctx, http.StatusBadRequest, f()) {
  23. return true
  24. }
  25. }
  26. return false
  27. }
  28. func Fail(ctx *gin.Context, status int, err error) bool {
  29. if err == nil {
  30. return false
  31. }
  32. ctx.JSON(status, HTTPError{Msg: err.Error()})
  33. if status == http.StatusInternalServerError {
  34. _, file, line, _ := runtime.Caller(1)
  35. logrus.WithField("err", err).Errorf("file:%s line:%d", file, line)
  36. }
  37. return true
  38. }
  39. func Success(ctx *gin.Context, data interface{}) {
  40. if data == nil {
  41. ctx.Status(http.StatusNoContent)
  42. return
  43. }
  44. switch ctx.Request.Method {
  45. case http.MethodGet, http.MethodHead, http.MethodOptions:
  46. ctx.JSON(http.StatusOK, data)
  47. case http.MethodPost, http.MethodPut, http.MethodPatch:
  48. ctx.JSON(http.StatusCreated, data)
  49. default:
  50. ctx.JSON(http.StatusBadRequest, HTTPError{Msg: fmt.Sprintf("unsupported request method %s", ctx.Request.Method)})
  51. }
  52. }