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

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