-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
validation.go
74 lines (64 loc) · 1.78 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package fuego
import (
"fmt"
"net/http"
"strings"
"github.com/go-playground/validator/v10"
)
// explainError translates a validator error into a human readable string.
func explainError(err validator.FieldError) string {
switch err.Tag() {
case "required":
return fmt.Sprintf("%s is required", err.Field())
case "email":
return fmt.Sprintf("%s should be a valid email", err.Field())
case "uuid":
return fmt.Sprintf("%s should be a valid UUID", err.Field())
case "e164":
return fmt.Sprintf("%s should be a valid international phone number (e.g. +33 6 06 06 06 06)", err.Field())
default:
resp := fmt.Sprintf("%s should be %s", err.Field(), err.Tag())
if err.Param() != "" {
resp += "=" + err.Param()
}
return resp
}
}
var v = validator.New()
func validate(a any) error {
_, ok := a.(map[string]any)
if ok {
return nil
}
err := v.Struct(a)
if err == nil {
return nil
}
// this check is only needed when your code could produce an
// invalid value for validation such as interface with nil value
if _, exists := err.(*validator.InvalidValidationError); exists {
return fmt.Errorf("validation error: %w", err)
}
validationError := HTTPError{
Err: err,
Status: http.StatusBadRequest,
Title: "Validation Error",
}
var errorsSummary []string
for _, err := range err.(validator.ValidationErrors) {
errorsSummary = append(errorsSummary, explainError(err))
validationError.Errors = append(validationError.Errors, ErrorItem{
Name: err.StructNamespace(),
Reason: err.Error(),
More: map[string]any{
"nsField": err.StructNamespace(),
"field": err.StructField(),
"tag": err.Tag(),
"param": err.Param(),
"value": err.Value(),
},
})
}
validationError.Detail = strings.Join(errorsSummary, ", ")
return validationError
}