1234567891011121314151617181920212223242526272829303132 |
- package middleware
- import (
- "net/http"
- "git.linuxforward.com/byom/byom-core/validation"
- "github.com/gin-gonic/gin"
- )
- // ValidateRequest validates the request body against the given struct and returns validation errors
- func ValidateRequest[T any](c *gin.Context) (*T, bool) {
- var req T
- if err := c.ShouldBindJSON(&req); err != nil {
- c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
- "code": "INVALID_REQUEST",
- "error": "Invalid request format",
- "errors": []validation.ValidationError{{Field: "body", Message: err.Error()}},
- })
- return nil, false
- }
- if errors := validation.Validate(req); len(errors) > 0 {
- c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
- "code": "VALIDATION_ERROR",
- "error": "Validation failed",
- "errors": errors,
- })
- return nil, false
- }
- return &req, true
- }
|