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

request.go 1.9KB

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