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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. ctx.JSON(status, gin.H{"msg": err.Error()})
  47. return true
  48. }
  49. func Success(ctx *gin.Context, data interface{}) {
  50. if data == nil {
  51. ctx.Status(http.StatusNoContent)
  52. return
  53. }
  54. switch ctx.Request.Method {
  55. case http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodDelete:
  56. ctx.JSON(http.StatusOK, data)
  57. case http.MethodPost, http.MethodPut, http.MethodPatch:
  58. ctx.JSON(http.StatusCreated, data)
  59. default:
  60. if requestID, found := ctx.Get("request_id"); found {
  61. ctx.JSON(http.StatusBadRequest, HTTPError{
  62. Msg: fmt.Sprintf("request_id: %s | unsupported request method %s",
  63. requestID.(string),
  64. ctx.Request.Method)})
  65. return
  66. }
  67. ctx.JSON(http.StatusBadRequest, HTTPError{Msg: fmt.Sprintf("unsupported request method %s", ctx.Request.Method)})
  68. }
  69. }