chore: refine rest validator (#2928)

* chore: refine rest validator

* chore: add more tests

* chore: reformat code

* chore: add comments
This commit is contained in:
Kevin Wan
2023-02-26 21:58:58 +08:00
committed by kevin
parent 366131640e
commit 805cb87d98
2 changed files with 77 additions and 11 deletions

View File

@@ -4,6 +4,7 @@ import (
"io"
"net/http"
"strings"
"sync/atomic"
"github.com/zeromicro/go-zero/core/mapping"
"github.com/zeromicro/go-zero/rest/internal/encoding"
@@ -23,15 +24,13 @@ const (
var (
formUnmarshaler = mapping.NewUnmarshaler(formKey, mapping.WithStringValues())
pathUnmarshaler = mapping.NewUnmarshaler(pathKey, mapping.WithStringValues())
xValidator Validator
validator atomic.Value
)
// Validator defines the interface for validating the request.
type Validator interface {
Validate(data interface{}, lang string) error
}
func SetValidator(validator Validator) {
xValidator = validator
// Validate validates the request and parsed data.
Validate(r *http.Request, data any) error
}
// Parse parses the request.
@@ -52,9 +51,10 @@ func Parse(r *http.Request, v interface{}) error {
return err
}
if xValidator != nil {
return xValidator.Validate(v, r.Header.Get("Accept-Language"))
if val := validator.Load(); val != nil {
return val.(Validator).Validate(r, v)
}
return nil
}
@@ -117,6 +117,13 @@ func ParsePath(r *http.Request, v interface{}) error {
return pathUnmarshaler.Unmarshal(m, v)
}
// SetValidator sets the validator.
// The validator is used to validate the request, only called in Parse,
// not in ParseHeaders, ParseForm, ParseHeader, ParseJsonBody, ParsePath.
func SetValidator(val Validator) {
validator.Store(val)
}
func withJsonBody(r *http.Request) bool {
return r.ContentLength > 0 && strings.Contains(r.Header.Get(header.ContentType), header.ApplicationJson)
}