-
Notifications
You must be signed in to change notification settings - Fork 0
/
validation.go
56 lines (45 loc) · 1.32 KB
/
validation.go
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
package common_utils
import (
"fmt"
"io"
"strings"
"github.com/go-playground/validator/v10"
)
type ValidationError struct {
Message string
}
func (ve *ValidationError) Error() string {
return fmt.Sprintf("validation error: message %s", ve.Message)
}
type ValidationErrors struct {
Errors []ValidationError
StatusCode int
}
func (ve *ValidationErrors) Error() string {
return fmt.Sprintf("validation errors: status code %d, message %s", ve.StatusCode, ve.Errors[0].Message)
}
func PanicValidationError(errors []ValidationError, statusCode int) {
validationErrors := ValidationErrors{
Errors: errors,
StatusCode: statusCode,
}
panic(validationErrors)
}
func ValidateStruct(data interface{}) {
var validationErrors []ValidationError
validate := validator.New()
errorValidate := validate.Struct(data)
if errorValidate != nil {
for _, err := range errorValidate.(validator.ValidationErrors) {
var validationError ValidationError
validationError.Message = strings.Split(err.Error(), "Error:")[1]
validationErrors = append(validationErrors, validationError)
}
PanicValidationError(validationErrors, 400)
}
}
func ValidateBodyPayload(body io.ReadCloser, output interface{}) {
err := NewDecoder(body).Decode(output)
PanicIfAppError(err, "failed when decode body payload", 400)
ValidateStruct(output)
}