validate.go 763 B

12345678910111213141516171819202122232425262728293031323334
  1. package server
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "github.com/langgenius/dify-plugin-daemon/internal/types/entities"
  5. "github.com/langgenius/dify-plugin-daemon/internal/types/validators"
  6. )
  7. func BindRequest[T any](r *gin.Context, success func(T)) {
  8. var request T
  9. var err error
  10. context_type := r.GetHeader("Content-Type")
  11. if context_type == "application/json" {
  12. err = r.ShouldBindJSON(&request)
  13. } else {
  14. err = r.ShouldBind(&request)
  15. }
  16. // validate
  17. if err := validators.GlobalEntitiesValidator.Struct(request); err != nil {
  18. resp := entities.NewErrorResponse(-400, "Invalid request")
  19. r.JSON(400, resp)
  20. return
  21. }
  22. if err != nil {
  23. resp := entities.NewErrorResponse(-400, "Invalid request")
  24. r.JSON(400, resp)
  25. return
  26. }
  27. success(request)
  28. }