Browse Source

feat: add configurable validator for httpx.Parse (#2923)

Co-authored-by: qiying.wang <qiying.wang@highlight.mobi>
Qiying Wang 2 years ago
parent
commit
92c8899f47
1 changed files with 17 additions and 1 deletions
  1. 17 1
      rest/httpx/requests.go

+ 17 - 1
rest/httpx/requests.go

@@ -23,8 +23,17 @@ const (
 var (
 var (
 	formUnmarshaler = mapping.NewUnmarshaler(formKey, mapping.WithStringValues())
 	formUnmarshaler = mapping.NewUnmarshaler(formKey, mapping.WithStringValues())
 	pathUnmarshaler = mapping.NewUnmarshaler(pathKey, mapping.WithStringValues())
 	pathUnmarshaler = mapping.NewUnmarshaler(pathKey, mapping.WithStringValues())
+	xValidator      Validator
 )
 )
 
 
+type Validator interface {
+	Validate(data interface{}, lang string) error
+}
+
+func SetValidator(validator Validator) {
+	xValidator = validator
+}
+
 // Parse parses the request.
 // Parse parses the request.
 func Parse(r *http.Request, v any) error {
 func Parse(r *http.Request, v any) error {
 	if err := ParsePath(r, v); err != nil {
 	if err := ParsePath(r, v); err != nil {
@@ -39,7 +48,14 @@ func Parse(r *http.Request, v any) error {
 		return err
 		return err
 	}
 	}
 
 
-	return ParseJsonBody(r, v)
+	if err := ParseJsonBody(r, v); err != nil {
+		return err
+	}
+
+	if xValidator != nil {
+		return xValidator.Validate(v, r.Header.Get("Accept-Language"))
+	}
+	return nil
 }
 }
 
 
 // ParseHeaders parses the headers request.
 // ParseHeaders parses the headers request.