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

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