Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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
}