initial commit
This commit is contained in:
58
internal/delivery/http/platform/utils.go
Normal file
58
internal/delivery/http/platform/utils.go
Normal file
@@ -0,0 +1,58 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"base/internal/dto"
|
||||
"base/pkg/helper"
|
||||
"base/pkg/validation"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func shouldBindJSON(c *gin.Context) bool {
|
||||
// Only bind JSON for methods that normally carry bodies
|
||||
switch c.Request.Method {
|
||||
case http.MethodPost,
|
||||
http.MethodPut,
|
||||
http.MethodPatch:
|
||||
default:
|
||||
return false
|
||||
}
|
||||
|
||||
// Must actually be JSON
|
||||
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("RequestBundErr")
|
||||
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("RequestBundErr")
|
||||
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("RequestBundErr")
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user