-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvalidation.go
66 lines (57 loc) · 2.08 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
package httpsuite
import (
"errors"
"net/http"
"github.com/go-playground/validator/v10"
)
// Validator instance
var validate = validator.New()
// ValidationErrorDetail provides structured details about a single validation error.
type ValidationErrorDetail struct {
Field string `json:"field"` // The name of the field that failed validation.
Message string `json:"message"` // A human-readable message describing the error.
}
// NewValidationProblemDetails creates a ProblemDetails instance based on validation errors.
// It maps field-specific validation errors into structured details.
func NewValidationProblemDetails(err error) *ProblemDetails {
var validationErrors validator.ValidationErrors
if !errors.As(err, &validationErrors) {
// If the error is not of type ValidationErrors, return a generic problem response.
return NewProblemDetails(
http.StatusBadRequest,
GetProblemTypeURL("bad_request_error"),
"Invalid Request",
"Invalid data format or structure",
)
}
// Collect structured details about each validation error.
errorDetails := make([]ValidationErrorDetail, len(validationErrors))
for i, vErr := range validationErrors {
errorDetails[i] = ValidationErrorDetail{
Field: vErr.Field(),
Message: formatValidationMessage(vErr),
}
}
return &ProblemDetails{
Type: GetProblemTypeURL("validation_error"),
Title: "Validation Error",
Status: http.StatusBadRequest,
Detail: "One or more fields failed validation.",
Extensions: map[string]interface{}{
"errors": errorDetails,
},
}
}
// formatValidationMessage generates a descriptive message for a validation error.
func formatValidationMessage(vErr validator.FieldError) string {
return vErr.Field() + " failed " + vErr.Tag() + " validation"
}
// IsRequestValid validates the provided request struct using the go-playground/validator package.
// It returns a ProblemDetails instance if validation fails, or nil if the request is valid.
func IsRequestValid(request any) *ProblemDetails {
err := validate.Struct(request)
if err != nil {
return NewValidationProblemDetails(err)
}
return nil
}