51 lines
1.5 KiB
Go
51 lines
1.5 KiB
Go
package backoffice
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"base/internal/dto"
|
|
"base/pkg/helper"
|
|
"base/pkg/validation"
|
|
)
|
|
|
|
func shouldBindJSON(c *gin.Context) bool {
|
|
switch c.Request.Method {
|
|
case http.MethodPost, http.MethodPut, http.MethodPatch:
|
|
default:
|
|
return false
|
|
}
|
|
contentType := c.ContentType()
|
|
return contentType == "application/json" || strings.HasSuffix(contentType, "+json")
|
|
}
|
|
|
|
func (ctl *Controller) validateRequest(c *gin.Context, request dto.DTO) bool {
|
|
if err := c.ShouldBindUri(request); err != nil {
|
|
ctl.logger.Error().Err(err).Msg("RequestBindErr")
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request path parameters"})
|
|
return false
|
|
}
|
|
if err := c.ShouldBindQuery(request); err != nil {
|
|
ctl.logger.Error().Err(err).Msg("RequestBindErr")
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request query parameters"})
|
|
return false
|
|
}
|
|
if shouldBindJSON(c) {
|
|
if err := c.ShouldBindJSON(request); err != nil {
|
|
ctl.logger.Error().Err(err).Msg("RequestBindErr")
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
|
return false
|
|
}
|
|
}
|
|
validator := validation.NewGenericValidator()
|
|
validator.Validate(helper.StructToMap(request), request.Schema())
|
|
if validator.HasErrors() {
|
|
ctl.logger.Error().Any("request", request).Any("error", validator.GetErrors()).Msg("validatorHasErrors")
|
|
c.JSON(http.StatusBadRequest, gin.H{"errors": validator.GetErrors()})
|
|
return false
|
|
}
|
|
return true
|
|
}
|