chore: refine rest validator (#2928)
* chore: refine rest validator * chore: add more tests * chore: reformat code * chore: add comments
This commit is contained in:
@@ -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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user