Newer
Older
govalidator "github.com/asaskevich/govalidator"
requestValidator "github.com/thedevsaddam/govalidator"
)
//ValidateRequest func validates the given model
func ValidateRequest(httpRequest *http.Request, validationRules, validationMessages requestValidator.MapData) map[string]interface{} {
//Get the content type of the request as validations for content types are different
contentType := httpRequest.Header.Get("Content-Type")
//Initialize the validation errors as blank
var validationErrors url.Values
//Set validator options
Request: httpRequest,
Rules: validationRules,
}
//Set custom validation messages if sent from user
if validationMessages != nil {
opts.Messages = validationMessages
}
if contentType == "application/json" || contentType == "text/plain" {
//Validate request type json and text (RAW data from request)
data := make(map[string]interface{}, 0)
validationErrors = validator.ValidateJSON()
} else {
//Validate request type form-data, form-urlencoded
validationErrors = validator.Validate()
}
if len(validationErrors) > 0 {
errs := map[string]interface{}{"validationErrors": validationErrors}
return errs
}
return nil
}
// ValidateStruct validates the structures with govalidator
func ValidateStruct(structToValidate interface{}) error {
validationResult, err := govalidator.ValidateStruct(structToValidate)
return err
}
if !validationResult {
return errors.New("ERROR:ValidateStruct function error")