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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 ParseSuccess(ctx *gin.Context, r interface{}, fs ...func() error) bool {
  12. if r != nil {
  13. if Error(ctx, http.StatusBadRequest, ctx.ShouldBind(r)) {
  14. return false
  15. }
  16. if checker, ok := r.(Checker); ok {
  17. return !Error(ctx, http.StatusBadRequest, checker.Check())
  18. }
  19. }
  20. for _, f := range fs {
  21. if Error(ctx, http.StatusBadRequest, f()) {
  22. return false
  23. }
  24. }
  25. return true
  26. }
  27. func Error(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. }