Newer
Older
package validationmdl
import (
"net/http"
"net/url"
"github.com/thedevsaddam/govalidator"
)
//ValidateRequest func validates the given model
func ValidateRequest(httpRequest *http.Request, validationRules, validationMessages govalidator.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
opts := govalidator.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)
opts.Data = &data
validator := govalidator.New(opts)
validationErrors = validator.ValidateJSON()
} else {
//Validate request type form-data, form-urlencoded
validator := govalidator.New(opts)
validationErrors = validator.Validate()
}
if len(validationErrors) > 0 {
errs := map[string]interface{}{"validationErrors": validationErrors}
return errs
}
return nil
}