70 lines
2.0 KiB
Go
70 lines
2.0 KiB
Go
package ginext
|
|
|
|
import (
|
|
"bringman.de/common/shared/bmerror"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/go-playground/validator/v10"
|
|
"net/http"
|
|
)
|
|
|
|
func ShouldBind(g *gin.Context, uri interface{}, query interface{}, body interface{}) error {
|
|
if uri != nil {
|
|
if err := g.ShouldBindUri(uri); err != nil {
|
|
if vErrs, ok := err.(validator.ValidationErrors); ok {
|
|
return bmerror.Wrap(vErrs, "Could not validate request parameter (uri)").
|
|
Errs("inner", convertValidationErrors(vErrs)).
|
|
WithType(bmerror.ErrQueryValidation).
|
|
WithStatuscode(http.StatusBadRequest).
|
|
Build()
|
|
} else {
|
|
return bmerror.Wrap(err, "Could not parse request parameter (uri)").
|
|
WithType(bmerror.ErrQueryParse).
|
|
WithStatuscode(http.StatusBadRequest).
|
|
Build()
|
|
}
|
|
}
|
|
}
|
|
if query != nil {
|
|
if err := g.ShouldBindQuery(query); err != nil {
|
|
if vErrs, ok := err.(validator.ValidationErrors); ok {
|
|
return bmerror.Wrap(vErrs, "Could not validate request parameter (query)").
|
|
Errs("inner", convertValidationErrors(vErrs)).
|
|
WithType(bmerror.ErrQueryValidation).
|
|
WithStatuscode(http.StatusBadRequest).
|
|
Build()
|
|
} else {
|
|
return bmerror.Wrap(err, "Could not parse request parameter (query)").
|
|
WithType(bmerror.ErrQueryParse).
|
|
WithStatuscode(http.StatusBadRequest).
|
|
Build()
|
|
}
|
|
}
|
|
}
|
|
if body != nil {
|
|
if err := g.ShouldBindJSON(body); err != nil {
|
|
if vErrs, ok := err.(validator.ValidationErrors); ok {
|
|
return bmerror.Wrap(vErrs, "Could not validate request parameter (body:json)").
|
|
Errs("inner", convertValidationErrors(vErrs)).
|
|
WithType(bmerror.ErrQueryValidation).
|
|
WithStatuscode(http.StatusBadRequest).
|
|
Build()
|
|
} else {
|
|
return bmerror.Wrap(err, "Could not parse request parameter (body:json)").
|
|
WithType(bmerror.ErrQueryParse).
|
|
WithStatuscode(http.StatusBadRequest).
|
|
Build()
|
|
}
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func convertValidationErrors(e validator.ValidationErrors) []error {
|
|
r := make([]error, 0, len(e))
|
|
for _, v := range e {
|
|
r = append(r, v)
|
|
}
|
|
return r
|
|
}
|