Support binding for slice/array obj [Rewrite] (#2302)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by wuhuizuo · committed by GitHub · parent a573ec6 · Browse files · 4 files·+142 added−11 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: thinkerou <thinkerou@gmail.com>
- Co-authored-by: Bo-Yi Wu <appleboy.tw@gmail.com>
Diff stats
4 files+142 added−11 removed
- other:+142 added−11 removed
Provenance
- Commit
4bfae4c- Tree
11ece6e- Author
wuhuizuo <wuhuizuo@126.com>- Committer
GitHub <noreply@github.com>- Parent
a573ec6
4 files changed+142 added−11 removed
modified:binding/binding_test.go+29 added-1 removed
33 unmodified lines34 appkey35 }36 37 type FooStruct struct {38- Foo string `msgpack:"foo" json:"foo" form:"foo" xml:"foo" binding:"required"`38+ Foo string `msgpack:"foo" json:"foo" form:"foo" xml:"foo" binding:"required,max=32"`39 }40 41 type FooBarStruct struct {42 FooStruct137 unmodified lines180 "/", "/",181 `{"foo": "bar"}`, `{"bar": "foo"}`)182 }183 184+func TestBindingJSONSlice(t *testing.T) {185+ EnableDecoderDisallowUnknownFields = true186+ defer func() {187+ EnableDecoderDisallowUnknownFields = false188+ }()189+190+ testBodyBindingSlice(t, JSON, "json", "/", "/", `[]`, ``)191+ testBodyBindingSlice(t, JSON, "json", "/", "/", `[{"foo": "123"}]`, `[{}]`)192+ testBodyBindingSlice(t, JSON, "json", "/", "/", `[{"foo": "123"}]`, `[{"foo": ""}]`)193+ testBodyBindingSlice(t, JSON, "json", "/", "/", `[{"foo": "123"}]`, `[{"foo": 123}]`)194+ testBodyBindingSlice(t, JSON, "json", "/", "/", `[{"foo": "123"}]`, `[{"bar": 123}]`)195+ testBodyBindingSlice(t, JSON, "json", "/", "/", `[{"foo": "123"}]`, `[{"foo": "123456789012345678901234567890123"}]`)196+}197+198 func TestBindingJSONUseNumber(t *testing.T) {199 testBodyBindingUseNumber(t,200 JSON, "json",201 "/", "/",992 unmodified lines1194 err = JSON.Bind(req, &obj)1195 assert.Error(t, err)1196 }1197 1198+func testBodyBindingSlice(t *testing.T, b Binding, name, path, badPath, body, badBody string) {1199+ assert.Equal(t, name, b.Name())1200+1201+ var obj1 []FooStruct1202+ req := requestWithBody("POST", path, body)1203+ err := b.Bind(req, &obj1)1204+ assert.NoError(t, err)1205+1206+ var obj2 []FooStruct1207+ req = requestWithBody("POST", badPath, badBody)1208+ err = JSON.Bind(req, &obj2)1209+ assert.Error(t, err)1210+}1211+1212 func testBodyBindingStringMap(t *testing.T, b Binding, path, badPath, body, badBody string) {1213 obj := make(map[string]string)1214 req := requestWithBody("POST", path, body)1215 if b.Name() == "form" {138 unmodified linesmodified:binding/binding.go+2 added-1 removed
49 unmodified lines50 // of the request. Gin provides a default implementation for this using51 // https://github.com/go-playground/validator/tree/v8.18.2.52 type StructValidator interface {53 // ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right.54+ // If the received type is a slice|array, the validation should be performed travel on every element.54- // If the received type is not a struct, any validation should be skipped and nil must be returned.55+ // If the received type is not a struct or slice|array, any validation should be skipped and nil must be returned.56 // If the received type is a struct or pointer to a struct, the validation should be performed.57 // If the struct is not valid or the validation itself fails, a descriptive error should be returned.58 // Otherwise nil must be returned.59 ValidateStruct(interface{}) error58 unmodified linesadded:binding/default_validator_test.go+68 added
1+// Copyright 2020 Gin Core Team. All rights reserved.2+// Use of this source code is governed by a MIT style3+// license that can be found in the LICENSE file.4+5+package binding6+7+import (8+ "errors"9+ "testing"10+)11+12+func TestSliceValidateError(t *testing.T) {13+ tests := []struct {14+ name string15+ err sliceValidateError16+ want string17+ }{18+ {"has nil elements", sliceValidateError{errors.New("test error"), nil}, "[0]: test error"},19+ }20+ for _, tt := range tests {21+ t.Run(tt.name, func(t *testing.T) {22+ if got := tt.err.Error(); got != tt.want {23+ t.Errorf("sliceValidateError.Error() = %v, want %v", got, tt.want)24+ }25+ })26+ }27+}28+29+func TestDefaultValidator(t *testing.T) {30+ type exampleStruct struct {31+ A string `binding:"max=8"`32+ B int `binding:"gt=0"`33+ }34+ tests := []struct {35+ name string36+ v *defaultValidator37+ obj interface{}38+ wantErr bool39+ }{40+ {"validate nil obj", &defaultValidator{}, nil, false},41+ {"validate int obj", &defaultValidator{}, 3, false},42+ {"validate struct failed-1", &defaultValidator{}, exampleStruct{A: "123456789", B: 1}, true},43+ {"validate struct failed-2", &defaultValidator{}, exampleStruct{A: "12345678", B: 0}, true},44+ {"validate struct passed", &defaultValidator{}, exampleStruct{A: "12345678", B: 1}, false},45+ {"validate *struct failed-1", &defaultValidator{}, &exampleStruct{A: "123456789", B: 1}, true},46+ {"validate *struct failed-2", &defaultValidator{}, &exampleStruct{A: "12345678", B: 0}, true},47+ {"validate *struct passed", &defaultValidator{}, &exampleStruct{A: "12345678", B: 1}, false},48+ {"validate []struct failed-1", &defaultValidator{}, []exampleStruct{{A: "123456789", B: 1}}, true},49+ {"validate []struct failed-2", &defaultValidator{}, []exampleStruct{{A: "12345678", B: 0}}, true},50+ {"validate []struct passed", &defaultValidator{}, []exampleStruct{{A: "12345678", B: 1}}, false},51+ {"validate []*struct failed-1", &defaultValidator{}, []*exampleStruct{{A: "123456789", B: 1}}, true},52+ {"validate []*struct failed-2", &defaultValidator{}, []*exampleStruct{{A: "12345678", B: 0}}, true},53+ {"validate []*struct passed", &defaultValidator{}, []*exampleStruct{{A: "12345678", B: 1}}, false},54+ {"validate *[]struct failed-1", &defaultValidator{}, &[]exampleStruct{{A: "123456789", B: 1}}, true},55+ {"validate *[]struct failed-2", &defaultValidator{}, &[]exampleStruct{{A: "12345678", B: 0}}, true},56+ {"validate *[]struct passed", &defaultValidator{}, &[]exampleStruct{{A: "12345678", B: 1}}, false},57+ {"validate *[]*struct failed-1", &defaultValidator{}, &[]*exampleStruct{{A: "123456789", B: 1}}, true},58+ {"validate *[]*struct failed-2", &defaultValidator{}, &[]*exampleStruct{{A: "12345678", B: 0}}, true},59+ {"validate *[]*struct passed", &defaultValidator{}, &[]*exampleStruct{{A: "12345678", B: 1}}, false},60+ }61+ for _, tt := range tests {62+ t.Run(tt.name, func(t *testing.T) {63+ if err := tt.v.ValidateStruct(tt.obj); (err != nil) != tt.wantErr {64+ t.Errorf("defaultValidator.Validate() error = %v, wantErr %v", err, tt.wantErr)65+ }66+ })67+ }68+}modified:binding/default_validator.go+43 added-9 removed
3 unmodified lines4 5 package binding6 7 import (8+ "fmt"9 "reflect"10+ "strings"11 "sync"12 13 "github.com/go-playground/validator/v10"14 )2 unmodified lines17 once sync.Once18 validate *validator.Validate19 }20 21+type sliceValidateError []error22+23+func (err sliceValidateError) Error() string {24+ var errMsgs []string25+ for i, e := range err {26+ if e == nil {27+ continue28+ }29+ errMsgs = append(errMsgs, fmt.Sprintf("[%d]: %s", i, e.Error()))30+ }31+ return strings.Join(errMsgs, "\n")32+}33+34 var _ StructValidator = &defaultValidator{}35 36 // ValidateStruct receives any kind of type, but only performed struct or pointer to struct type.37 func (v *defaultValidator) ValidateStruct(obj interface{}) error {23- value := reflect.ValueOf(obj)24- valueType := value.Kind()25- if valueType == reflect.Ptr {26- valueType = value.Elem().Kind()38+ if obj == nil {39+ return nil40 }28- if valueType == reflect.Struct {29- v.lazyinit()30- if err := v.validate.Struct(obj); err != nil {31- return err41+42+ value := reflect.ValueOf(obj)43+ switch value.Kind() {44+ case reflect.Ptr:45+ return v.ValidateStruct(value.Elem().Interface())46+ case reflect.Struct:47+ return v.validateStruct(obj)48+ case reflect.Slice, reflect.Array:49+ count := value.Len()50+ validateRet := make(sliceValidateError, 0)51+ for i := 0; i < count; i++ {52+ if err := v.ValidateStruct(value.Index(i).Interface()); err != nil {53+ validateRet = append(validateRet, err)54+ }55 }56+ if len(validateRet) == 0 {57+ return nil58+ }59+ return validateRet60+ default:61+ return nil62 }34- return nil63 }64 65+// validateStruct receives struct type66+func (v *defaultValidator) validateStruct(obj interface{}) error {67+ v.lazyinit()68+ return v.validate.Struct(obj)69+}70+71 // Engine returns the underlying validator engine which powers the default72 // Validator instance. This is useful if you want to register custom validations73 // or struct level validations. See validator GoDoc for more info -74 // https://godoc.org/gopkg.in/go-playground/validator.v811 unmodified lines