Skip to content

Commit

Permalink
feat: add configurable validator for httpx.Parse (zeromicro#2923)
Browse files Browse the repository at this point in the history
Co-authored-by: qiying.wang <qiying.wang@highlight.mobi>
  • Loading branch information
WqyJh and qiying.wang authored Feb 26, 2023
1 parent 238c830 commit 92c8899
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion rest/httpx/requests.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,17 @@ const (
var (
formUnmarshaler = mapping.NewUnmarshaler(formKey, 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.
func Parse(r *http.Request, v any) error {
if err := ParsePath(r, v); err != nil {
Expand All @@ -39,7 +48,14 @@ func Parse(r *http.Request, v any) error {
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.
Expand Down

0 comments on commit 92c8899

Please sign in to comment.