validationmdl.go 1.49 KiB
Newer Older
Rahul A. Sutar's avatar
Rahul A. Sutar committed
package validationmdl

import (
	"fmt"
	"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{} {

	// fmt.Println("Data received : ", httpRequest.Body)

	//Get the content type of the request as validations for content types are different
	contentType := httpRequest.Header.Get("Content-Type")
	fmt.Println("Content type : ", contentType)

	//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
	}

	data := make(map[string]interface{}, 0)

	//Validate request type json and text (RAW data from request)
	if contentType == "application/json" || contentType == "text/plain" {
		fmt.Println("Inside if")

		opts.Data = &data

		validator := govalidator.New(opts)
		validationErrors = validator.ValidateJSON()

	} else {
		fmt.Println("Inside else2")
		opts.Data = &data
		//Validate request type form-data, form-urlencoded
		//		loggermdl.LogVars("opts : ", opts)
		validator := govalidator.New(opts)
		validationErrors = validator.Validate()
	}

	if len(validationErrors) > 0 {
		errs := map[string]interface{}{"validationErrors": validationErrors}
		return errs
	}
	return nil
}