validation.go 826 B

1234567891011121314151617181920212223242526272829303132
  1. package middleware
  2. import (
  3. "net/http"
  4. "git.linuxforward.com/byom/byom-core/validation"
  5. "github.com/gin-gonic/gin"
  6. )
  7. // ValidateRequest validates the request body against the given struct and returns validation errors
  8. func ValidateRequest[T any](c *gin.Context) (*T, bool) {
  9. var req T
  10. if err := c.ShouldBindJSON(&req); err != nil {
  11. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
  12. "code": "INVALID_REQUEST",
  13. "error": "Invalid request format",
  14. "errors": []validation.ValidationError{{Field: "body", Message: err.Error()}},
  15. })
  16. return nil, false
  17. }
  18. if errors := validation.Validate(req); len(errors) > 0 {
  19. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
  20. "code": "VALIDATION_ERROR",
  21. "error": "Validation failed",
  22. "errors": errors,
  23. })
  24. return nil, false
  25. }
  26. return &req, true
  27. }