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

request.go 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. }
  16. if Fail(ctx, err) {
  17. return true
  18. }
  19. if checker, ok := r.(Checker); ok {
  20. err := checker.Check()
  21. if err != nil {
  22. err = HTTPError{Status: http.StatusBadRequest, Msg: err.Error()}
  23. }
  24. if Fail(ctx, err) {
  25. return true
  26. }
  27. }
  28. }
  29. for _, f := range fs {
  30. err := f()
  31. if err != nil {
  32. err = HTTPError{Status: http.StatusBadRequest, Msg: err.Error()}
  33. }
  34. if Fail(ctx, err) {
  35. return true
  36. }
  37. }
  38. return false
  39. }
  40. func Fail(ctx *gin.Context, err error) bool {
  41. if err == nil {
  42. return false
  43. }
  44. status := http.StatusInternalServerError
  45. if v, ok := err.(HTTPError); ok {
  46. status = v.Status
  47. }
  48. ctx.JSON(status, gin.H{"msg": err.Error()})
  49. return true
  50. }
  51. func Success(ctx *gin.Context, data interface{}) {
  52. if data == nil {
  53. ctx.Status(http.StatusNoContent)
  54. return
  55. }
  56. switch ctx.Request.Method {
  57. case http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodDelete:
  58. ctx.JSON(http.StatusOK, data)
  59. case http.MethodPost, http.MethodPut, http.MethodPatch:
  60. ctx.JSON(http.StatusCreated, data)
  61. default:
  62. ctx.JSON(http.StatusBadRequest, HTTPError{Msg: fmt.Sprintf("unsupported request method %s", ctx.Request.Method)})
  63. }
  64. }