feat(binding): add support for encoding.UnmarshalText in uri/query binding (#4203)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by takanuva15 · committed by GitHub · parent b2b489d · Browse files · 3 files·+508 added−26 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+508 added−26 removed
- other:+508 added−26 removed
Provenance
- Commit
192ac89- Tree
63c1e37- Author
takanuva15 <6986426+takanuva15@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
b2b489d
3 files changed+508 added−26 removed
modified:binding/form_mapping_test.go+390 added
3 unmodified lines4 5 package binding6 7 import (8+ "encoding"9 "encoding/hex"10 "errors"11 "mime/multipart"12 "reflect"511 unmodified lines524 525 assert.EqualValues(t, 245, s.Foo)526 }527 528+func TestMappingCustomUnmarshalParamHexDefault(t *testing.T) {529+ var s struct {530+ Foo customUnmarshalParamHex `form:"foo,default=f5"`531+ }532+ err := mappingByPtr(&s, formSource{"foo": {}}, "form")533+ require.NoError(t, err)534+535+ assert.EqualValues(t, 0xf5, s.Foo)536+}537+538 type customUnmarshalParamType struct {539 Protocol string540 Path string541 Name string92 unmodified lines634 assert.Equal(t, "bar", s.FileData[0])635 assert.Equal(t, "foo", s.FileData[1])636 }637 638+func TestMappingCustomSliceStopsWhenError(t *testing.T) {639+ var s struct {640+ FileData customPath `form:"path"`641+ }642+ err := mappingByPtr(&s, formSource{"path": {"invalid"}}, "form")643+ require.ErrorContains(t, err, "invalid format")644+ require.Empty(t, s.FileData)645+}646+647+func TestMappingCustomSliceOfSliceUri(t *testing.T) {648+ var s struct {649+ FileData []customPath `uri:"path" collection_format:"csv"`650+ }651+ err := mappingByPtr(&s, formSource{"path": {"bar/foo,bar/foo/spam"}}, "uri")652+ require.NoError(t, err)653+ assert.Equal(t, []customPath{{"bar", "foo"}, {"bar", "foo", "spam"}}, s.FileData)654+}655+656+func TestMappingCustomSliceOfSliceForm(t *testing.T) {657+ var s struct {658+ FileData []customPath `form:"path" collection_format:"csv"`659+ }660+ err := mappingByPtr(&s, formSource{"path": {"bar/foo,bar/foo/spam"}}, "form")661+ require.NoError(t, err)662+ assert.Equal(t, []customPath{{"bar", "foo"}, {"bar", "foo", "spam"}}, s.FileData)663+}664+665 type objectID [12]byte666 667 func (o *objectID) UnmarshalParam(param string) error {668 oid, err := convertTo(param)43 unmodified lines712 expected, _ := convertTo(val)713 assert.Equal(t, expected, s.FileData)714 }715 716+func TestMappingCustomArrayOfArrayUri(t *testing.T) {717+ id1, _ := convertTo(`664a062ac74a8ad104e0e80e`)718+ id2, _ := convertTo(`664a062ac74a8ad104e0e80f`)719+720+ var s struct {721+ FileData []objectID `uri:"ids" collection_format:"csv"`722+ }723+ err := mappingByPtr(&s, formSource{"ids": {`664a062ac74a8ad104e0e80e,664a062ac74a8ad104e0e80f`}}, "uri")724+ require.NoError(t, err)725+ assert.Equal(t, []objectID{id1, id2}, s.FileData)726+}727+728+func TestMappingCustomArrayOfArrayForm(t *testing.T) {729+ id1, _ := convertTo(`664a062ac74a8ad104e0e80e`)730+ id2, _ := convertTo(`664a062ac74a8ad104e0e80f`)731+732+ var s struct {733+ FileData []objectID `form:"ids" collection_format:"csv"`734+ }735+ err := mappingByPtr(&s, formSource{"ids": {`664a062ac74a8ad104e0e80e,664a062ac74a8ad104e0e80f`}}, "form")736+ require.NoError(t, err)737+ assert.Equal(t, []objectID{id1, id2}, s.FileData)738+}739+740+// ==== TextUnmarshaler tests START ====741+742+type customUnmarshalTextHex int743+744+func (f *customUnmarshalTextHex) UnmarshalText(text []byte) error {745+ v, err := strconv.ParseInt(string(text), 16, 64)746+ if err != nil {747+ return err748+ }749+ *f = customUnmarshalTextHex(v)750+ return nil751+}752+753+// verify type implements TextUnmarshaler754+var _ encoding.TextUnmarshaler = (*customUnmarshalTextHex)(nil)755+756+func TestMappingCustomUnmarshalTextHexUri(t *testing.T) {757+ var s struct {758+ Field customUnmarshalTextHex `uri:"field,parser=encoding.TextUnmarshaler"`759+ }760+ err := mappingByPtr(&s, formSource{"field": {`f5`}}, "uri")761+ require.NoError(t, err)762+ assert.EqualValues(t, 245, s.Field)763+}764+765+func TestMappingCustomUnmarshalTextHexForm(t *testing.T) {766+ var s struct {767+ Field customUnmarshalTextHex `form:"field,parser=encoding.TextUnmarshaler"`768+ }769+ err := mappingByPtr(&s, formSource{"field": {`f5`}}, "form")770+ require.NoError(t, err)771+ assert.EqualValues(t, 245, s.Field)772+}773+774+func TestMappingCustomUnmarshalTextHexDefault(t *testing.T) {775+ var s struct {776+ Field customUnmarshalTextHex `form:"field,default=f5,parser=encoding.TextUnmarshaler"`777+ }778+ err := mappingByPtr(&s, formSource{"field1": {}}, "form")779+ require.NoError(t, err)780+ assert.EqualValues(t, 0xf5, s.Field)781+}782+783+type customUnmarshalTextType struct {784+ Protocol string785+ Path string786+ Name string787+}788+789+func (f *customUnmarshalTextType) UnmarshalText(text []byte) error {790+ parts := strings.Split(string(text), ":")791+ if len(parts) != 3 {792+ return errors.New("invalid format")793+ }794+ f.Protocol = parts[0]795+ f.Path = parts[1]796+ f.Name = parts[2]797+ return nil798+}799+800+var _ encoding.TextUnmarshaler = (*customUnmarshalTextType)(nil)801+802+func TestMappingCustomStructTypeUnmarshalTextForm(t *testing.T) {803+ var s struct {804+ FileData customUnmarshalTextType `form:"data,parser=encoding.TextUnmarshaler"`805+ }806+ err := mappingByPtr(&s, formSource{"data": {`file:/foo:happiness`}}, "form")807+ require.NoError(t, err)808+809+ assert.Equal(t, "file", s.FileData.Protocol)810+ assert.Equal(t, "/foo", s.FileData.Path)811+ assert.Equal(t, "happiness", s.FileData.Name)812+}813+814+func TestMappingCustomStructTypeUnmarshalTextUri(t *testing.T) {815+ var s struct {816+ FileData customUnmarshalTextType `uri:"data,parser=encoding.TextUnmarshaler"`817+ }818+ err := mappingByPtr(&s, formSource{"data": {`file:/foo:happiness`}}, "uri")819+ require.NoError(t, err)820+821+ assert.Equal(t, "file", s.FileData.Protocol)822+ assert.Equal(t, "/foo", s.FileData.Path)823+ assert.Equal(t, "happiness", s.FileData.Name)824+}825+826+func TestMappingCustomPointerStructTypeUnmarshalTextForm(t *testing.T) {827+ var s struct {828+ FileData *customUnmarshalTextType `form:"data,parser=encoding.TextUnmarshaler"`829+ }830+ err := mappingByPtr(&s, formSource{"data": {`file:/foo:happiness`}}, "form")831+ require.NoError(t, err)832+833+ assert.Equal(t, "file", s.FileData.Protocol)834+ assert.Equal(t, "/foo", s.FileData.Path)835+ assert.Equal(t, "happiness", s.FileData.Name)836+}837+838+func TestMappingCustomPointerStructTypeUnmarshalTextUri(t *testing.T) {839+ var s struct {840+ FileData *customUnmarshalTextType `uri:"data,parser=encoding.TextUnmarshaler"`841+ }842+ err := mappingByPtr(&s, formSource{"data": {`file:/foo:happiness`}}, "uri")843+ require.NoError(t, err)844+845+ assert.Equal(t, "file", s.FileData.Protocol)846+ assert.Equal(t, "/foo", s.FileData.Path)847+ assert.Equal(t, "happiness", s.FileData.Name)848+}849+850+type customPathUnmarshalText []string851+852+func (p *customPathUnmarshalText) UnmarshalText(text []byte) error {853+ elems := strings.Split(string(text), "/")854+ n := len(elems)855+ if n < 2 {856+ return errors.New("invalid format")857+ }858+859+ *p = elems860+ return nil861+}862+863+var _ encoding.TextUnmarshaler = (*customPathUnmarshalText)(nil)864+865+func TestMappingCustomSliceUnmarshalTextUri(t *testing.T) {866+ var s struct {867+ FileData customPathUnmarshalText `uri:"path,parser=encoding.TextUnmarshaler"`868+ }869+ err := mappingByPtr(&s, formSource{"path": {`bar/foo`}}, "uri")870+ require.NoError(t, err)871+872+ assert.Equal(t, "bar", s.FileData[0])873+ assert.Equal(t, "foo", s.FileData[1])874+}875+876+func TestMappingCustomSliceUnmarshalTextForm(t *testing.T) {877+ var s struct {878+ FileData customPathUnmarshalText `form:"path,parser=encoding.TextUnmarshaler"`879+ }880+ err := mappingByPtr(&s, formSource{"path": {`bar/foo`}}, "form")881+ require.NoError(t, err)882+883+ assert.Equal(t, "bar", s.FileData[0])884+ assert.Equal(t, "foo", s.FileData[1])885+}886+887+func TestMappingCustomSliceUnmarshalTextStopsWhenError(t *testing.T) {888+ var s struct {889+ FileData customPathUnmarshalText `form:"path,parser=encoding.TextUnmarshaler"`890+ }891+ err := mappingByPtr(&s, formSource{"path": {"invalid"}}, "form")892+ require.ErrorContains(t, err, "invalid format")893+ require.Empty(t, s.FileData)894+}895+896+func TestMappingCustomSliceOfSliceUnmarshalTextUri(t *testing.T) {897+ var s struct {898+ FileData []customPathUnmarshalText `uri:"path,parser=encoding.TextUnmarshaler" collection_format:"csv"`899+ }900+ err := mappingByPtr(&s, formSource{"path": {"bar/foo,bar/foo/spam"}}, "uri")901+ require.NoError(t, err)902+ assert.Equal(t, []customPathUnmarshalText{{"bar", "foo"}, {"bar", "foo", "spam"}}, s.FileData)903+}904+905+func TestMappingCustomSliceOfSliceUnmarshalTextForm(t *testing.T) {906+ var s struct {907+ FileData []customPathUnmarshalText `form:"path,parser=encoding.TextUnmarshaler" collection_format:"csv"`908+ }909+ err := mappingByPtr(&s, formSource{"path": {"bar/foo,bar/foo/spam"}}, "form")910+ require.NoError(t, err)911+ assert.Equal(t, []customPathUnmarshalText{{"bar", "foo"}, {"bar", "foo", "spam"}}, s.FileData)912+}913+914+func TestMappingCustomSliceOfSliceUnmarshalTextDefault(t *testing.T) {915+ var s struct {916+ FileData []customPathUnmarshalText `form:"path,default=bar/foo;bar/foo/spam,parser=encoding.TextUnmarshaler" collection_format:"csv"`917+ }918+ err := mappingByPtr(&s, formSource{"path": {}}, "form")919+ require.NoError(t, err)920+ assert.Equal(t, []customPathUnmarshalText{{"bar", "foo"}, {"bar", "foo", "spam"}}, s.FileData)921+}922+923+type objectIDUnmarshalText [12]byte924+925+func (o *objectIDUnmarshalText) UnmarshalText(text []byte) error {926+ oid, err := convertToOidUnmarshalText(string(text))927+ if err != nil {928+ return err929+ }930+931+ *o = oid932+ return nil933+}934+935+func convertToOidUnmarshalText(s string) (objectIDUnmarshalText, error) {936+ oid, err := convertTo(s)937+ return objectIDUnmarshalText(oid), err938+}939+940+var _ encoding.TextUnmarshaler = (*objectIDUnmarshalText)(nil)941+942+func TestMappingCustomArrayUnmarshalTextUri(t *testing.T) {943+ var s struct {944+ FileData objectIDUnmarshalText `uri:"id,parser=encoding.TextUnmarshaler"`945+ }946+ val := `664a062ac74a8ad104e0e80f`947+ err := mappingByPtr(&s, formSource{"id": {val}}, "uri")948+ require.NoError(t, err)949+950+ expected, _ := convertToOidUnmarshalText(val)951+ assert.Equal(t, expected, s.FileData)952+}953+954+func TestMappingCustomArrayUnmarshalTextForm(t *testing.T) {955+ var s struct {956+ FileData objectIDUnmarshalText `form:"id,parser=encoding.TextUnmarshaler"`957+ }958+ val := `664a062ac74a8ad104e0e80f`959+ err := mappingByPtr(&s, formSource{"id": {val}}, "form")960+ require.NoError(t, err)961+962+ expected, _ := convertToOidUnmarshalText(val)963+ assert.Equal(t, expected, s.FileData)964+}965+966+func TestMappingCustomArrayOfArrayUnmarshalTextUri(t *testing.T) {967+ id1, _ := convertToOidUnmarshalText(`664a062ac74a8ad104e0e80e`)968+ id2, _ := convertToOidUnmarshalText(`664a062ac74a8ad104e0e80f`)969+970+ var s struct {971+ FileData []objectIDUnmarshalText `uri:"ids,parser=encoding.TextUnmarshaler" collection_format:"csv"`972+ }973+ err := mappingByPtr(&s, formSource{"ids": {`664a062ac74a8ad104e0e80e,664a062ac74a8ad104e0e80f`}}, "uri")974+ require.NoError(t, err)975+ assert.Equal(t, []objectIDUnmarshalText{id1, id2}, s.FileData)976+}977+978+func TestMappingCustomArrayOfArrayUnmarshalTextForm(t *testing.T) {979+ id1, _ := convertToOidUnmarshalText(`664a062ac74a8ad104e0e80e`)980+ id2, _ := convertToOidUnmarshalText(`664a062ac74a8ad104e0e80f`)981+982+ var s struct {983+ FileData []objectIDUnmarshalText `form:"ids,parser=encoding.TextUnmarshaler" collection_format:"csv"`984+ }985+ err := mappingByPtr(&s, formSource{"ids": {`664a062ac74a8ad104e0e80e,664a062ac74a8ad104e0e80f`}}, "form")986+ require.NoError(t, err)987+ assert.Equal(t, []objectIDUnmarshalText{id1, id2}, s.FileData)988+}989+990+func TestMappingCustomArrayOfArrayUnmarshalTextDefault(t *testing.T) {991+ id1, _ := convertToOidUnmarshalText(`664a062ac74a8ad104e0e80e`)992+ id2, _ := convertToOidUnmarshalText(`664a062ac74a8ad104e0e80f`)993+994+ var s struct {995+ FileData []objectIDUnmarshalText `form:"ids,default=664a062ac74a8ad104e0e80e;664a062ac74a8ad104e0e80f,parser=encoding.TextUnmarshaler" collection_format:"csv"`996+ }997+ err := mappingByPtr(&s, formSource{"ids": {}}, "form")998+ require.NoError(t, err)999+ assert.Equal(t, []objectIDUnmarshalText{id1, id2}, s.FileData)1000+}1001+1002+// If someone specifies parser=TextUnmarshaler and it's not defined for the type, gin should revert to using its default1003+// binding logic.1004+func TestMappingUsingBindUnmarshalerAndTextUnmarshalerWhenOnlyBindUnmarshalerDefined(t *testing.T) {1005+ var s struct {1006+ Hex customUnmarshalParamHex `form:"hex"`1007+ HexByUnmarshalText customUnmarshalParamHex `form:"hex2,parser=encoding.TextUnmarshaler"`1008+ }1009+ err := mappingByPtr(&s, formSource{1010+ "hex": {`f5`},1011+ "hex2": {`f5`},1012+ }, "form")1013+ require.NoError(t, err)1014+1015+ assert.EqualValues(t, 0xf5, s.Hex)1016+ assert.EqualValues(t, 0xf5, s.HexByUnmarshalText) // reverts to BindUnmarshaler binding1017+}1018+1019+// If someone does not specify parser=TextUnmarshaler even when it's defined for the type, gin should ignore the1020+// UnmarshalText logic and continue using its default binding logic. (This ensures gin does not break backwards1021+// compatibility)1022+func TestMappingUsingBindUnmarshalerAndTextUnmarshalerWhenOnlyTextUnmarshalerDefined(t *testing.T) {1023+ var s struct {1024+ Hex customUnmarshalTextHex `form:"hex"`1025+ HexByUnmarshalText customUnmarshalTextHex `form:"hex2,parser=encoding.TextUnmarshaler"`1026+ }1027+ err := mappingByPtr(&s, formSource{1028+ "hex": {`11`},1029+ "hex2": {`11`},1030+ }, "form")1031+ require.NoError(t, err)1032+1033+ assert.EqualValues(t, 11, s.Hex) // this is using default int binding, not our custom hex binding. 0x11 should be 17 in decimal1034+ assert.EqualValues(t, 0x11, s.HexByUnmarshalText) // correct expected value for normal hex binding1035+}1036+1037+type customHexUnmarshalParamAndUnmarshalText int1038+1039+func (f *customHexUnmarshalParamAndUnmarshalText) UnmarshalParam(param string) error {1040+ return errors.New("should not be called in unit test if parser tag present")1041+}1042+1043+func (f *customHexUnmarshalParamAndUnmarshalText) UnmarshalText(text []byte) error {1044+ v, err := strconv.ParseInt(string(text), 16, 64)1045+ if err != nil {1046+ return err1047+ }1048+ *f = customHexUnmarshalParamAndUnmarshalText(v)1049+ return nil1050+}1051+1052+// If a type has both UnmarshalParam and UnmarshalText methods defined, but the parser tag is set to TextUnmarshaler,1053+// then only the UnmarshalText method should be invoked.1054+func TestMappingUsingTextUnmarshalerWhenBindUnmarshalerAlsoDefined(t *testing.T) {1055+ var s struct {1056+ Hex customHexUnmarshalParamAndUnmarshalText `form:"hex,parser=encoding.TextUnmarshaler"`1057+ }1058+ err := mappingByPtr(&s, formSource{1059+ "hex": {`f5`},1060+ }, "form")1061+ require.NoError(t, err)1062+1063+ assert.EqualValues(t, 0xf5, s.Hex)1064+}1065+1066+// ==== TextUnmarshaler tests END ====1067+1068 func TestMappingEmptyValues(t *testing.T) {1069 t.Run("slice with default", func(t *testing.T) {1070 var s struct {1071 Slice []int `form:"slice,default=5"`75 unmodified linesmodified:binding/form_mapping.go+48 added-20 removed
3 unmodified lines4 5 package binding6 7 import (8+ "encoding"9 "errors"10 "fmt"11 "maps"12 "mime/multipart"124 unmodified lines137 138 type setOptions struct {139 isDefaultExists bool140 defaultValue string141+ // parser specifies what interface to use for reading the request & default values (e.g. `encoding.TextUnmarshaler`)142+ parser string143 }144 145 func tryToSetValue(value reflect.Value, field reflect.StructField, setter setter, tag string) (bool, error) {146 var tagValue string23 unmodified lines170 if cfTag == "" || cfTag == "multi" || cfTag == "csv" {171 setOpt.defaultValue = strings.ReplaceAll(v, ";", ",")172 }173 }174+ } else if k, v = head(opt, "="); k == "parser" {175+ setOpt.parser = v176 }177 }178 179 return setter.TrySet(value, field, tagValue, setOpt)15 unmodified lines195 }196 return false, nil197 }198 199+// trySetUsingParser tries to set a custom type value based on the presence of the "parser" tag on the field.200+// If the parser tag does not exist or does not match any of the supported parsers, gin will skip over this.201+func trySetUsingParser(val string, value reflect.Value, parser string) (isSet bool, err error) {202+ switch parser {203+ case "encoding.TextUnmarshaler":204+ v, ok := value.Addr().Interface().(encoding.TextUnmarshaler)205+ if !ok {206+ return false, nil207+ }208+ return true, v.UnmarshalText([]byte(val))209+ }210+ return false, nil211+}212+213 func trySplit(vs []string, field reflect.StructField) (newVs []string, err error) {214 cfTag := field.Tag.Get("collection_format")215 if cfTag == "" || cfTag == "multi" {216 return vs, nil9 unmodified lines226 sep = "\t"227 case "pipes":228 sep = "|"229 default:211- return vs, fmt.Errorf("%s is not supported in the collection_format. (csv, ssv, pipes)", cfTag)230+ return vs, fmt.Errorf("%s is not supported in the collection_format. (multi, csv, ssv, tsv, pipes)", cfTag)231 }232 233 totalLength := 0234 for _, v := range vs {27 unmodified lines262 vs = strings.Split(opt.defaultValue, ",")263 }264 }265 247- if ok, err = trySetCustom(vs[0], value); ok {266+ if ok, err = trySetUsingParser(vs[0], value, opt.parser); ok {267 return ok, err268+ } else if ok, err = trySetCustom(vs[0], value); ok {269+ return ok, err270 }271 272 if vs, err = trySplit(vs, field); err != nil {273 return false, err274 }275 255- return true, setSlice(vs, value, field)276+ return true, setSlice(vs, value, field, opt)277 case reflect.Array:278 if len(vs) == 0 {279 if !opt.isDefaultExists {280 return false, nil6 unmodified lines287 vs = strings.Split(opt.defaultValue, ",")288 }289 }290 270- if ok, err = trySetCustom(vs[0], value); ok {291+ if ok, err = trySetUsingParser(vs[0], value, opt.parser); ok {292 return ok, err293+ } else if ok, err = trySetCustom(vs[0], value); ok {294+ return ok, err295 }296 297 if vs, err = trySplit(vs, field); err != nil {298 return false, err2 unmodified lines301 if len(vs) != value.Len() {302 return false, fmt.Errorf("%q is not valid value for %s", vs, value.Type().String())303 }304 282- return true, setArray(vs, value, field)305+ return true, setArray(vs, value, field, opt)306 default:307 var val string285- if !ok {308+ if !ok || len(vs) == 0 || (len(vs) > 0 && vs[0] == "") {309 val = opt.defaultValue287- }288-289- if len(vs) > 0 {310+ } else if len(vs) > 0 {311 val = vs[0]291- if val == "" {292- val = opt.defaultValue293- }312 }295- if ok, err := trySetCustom(val, value); ok {313+314+ if ok, err = trySetUsingParser(val, value, opt.parser); ok {315 return ok, err316+ } else if ok, err = trySetCustom(val, value); ok {317+ return ok, err318 }298- return true, setWithProperType(val, value, field)319+ return true, setWithProperType(val, value, field, opt)320 }321 }322 302-func setWithProperType(val string, value reflect.Value, field reflect.StructField) error {323+func setWithProperType(val string, value reflect.Value, field reflect.StructField, opt setOptions) error {324+ // this if-check is required for parsing nested types like []MyId, where MyId is [12]byte325+ if ok, err := trySetUsingParser(val, value, opt.parser); ok {326+ return err327+ } else if ok, err = trySetCustom(val, value); ok {328+ return err329+ }330+331 // If it is a string type, no spaces are removed, and the user data is not modified here332 if value.Kind() != reflect.String {333 val = strings.TrimSpace(val)334 }44 unmodified lines379 case reflect.Ptr:380 if !value.Elem().IsValid() {381 value.Set(reflect.New(value.Type().Elem()))382 }355- return setWithProperType(val, value.Elem(), field)383+ return setWithProperType(val, value.Elem(), field, opt)384 default:385 return errUnknownType386 }387 return nil98 unmodified lines486 value.Set(reflect.ValueOf(t))487 return nil488 }489 462-func setArray(vals []string, value reflect.Value, field reflect.StructField) error {490+func setArray(vals []string, value reflect.Value, field reflect.StructField, opt setOptions) error {491 for i, s := range vals {464- err := setWithProperType(s, value.Index(i), field)492+ err := setWithProperType(s, value.Index(i), field, opt)493 if err != nil {494 return err495 }496 }497 return nil498 }499 472-func setSlice(vals []string, value reflect.Value, field reflect.StructField) error {500+func setSlice(vals []string, value reflect.Value, field reflect.StructField, opt setOptions) error {501 slice := reflect.MakeSlice(value.Type(), len(vals), len(vals))474- err := setArray(vals, slice, field)502+ err := setArray(vals, slice, field, opt)503 if err != nil {504 return err505 }506 value.Set(slice)44 unmodified linesmodified:docs/doc.md+70 added-6 removed
909 unmodified lines910 ```911 912 NOTE: For default [collection values](#collection-format-for-arrays), the following rules apply:913 - Since commas are used to delimit tag options, they are not supported within a default value and will result in undefined behavior914-- For the collection formats "multi" and "csv", a semicolon should be used in place of a comma to delimited default values914+- For the collection formats "multi" and "csv", a semicolon should be used in place of a comma to delimit default values915 - Since semicolons are used to delimit default values for "multi" and "csv", they are not supported within a default value for "multi" and "csv"916 917 918 #### Collection format for arrays89 unmodified lines1008 ```1009 1010 ### Bind custom unmarshaler1011 1012+To override gin's default binding logic, define a function on your type that satisfies the `encoding.TextUnmarshaler` interface from the Golang standard library. Then specify `parser=encoding.TextUnmarshaler` in the `uri`/`form` tag of the field being bound.1013+1014 ```go1015 package main1016 1017 import (1018+ "encoding"1019+ "strings"1020+1021 "github.com/gin-gonic/gin"1022+)1023+1024+type Birthday string1025+1026+func (b *Birthday) UnmarshalText(text []byte) error {1027+ *b = Birthday(strings.Replace(string(text), "-", "/", -1))1028+ return nil1029+}1030+1031+var _ encoding.TextUnmarshaler = (*Birthday)(nil) //assert Birthday implements encoding.TextUnmarshaler1032+1033+func main() {1034+ route := gin.Default()1035+ var request struct {1036+ Birthday Birthday `form:"birthday,parser=encoding.TextUnmarshaler"`1037+ Birthdays []Birthday `form:"birthdays,parser=encoding.TextUnmarshaler" collection_format:"csv"`1038+ BirthdaysDefault []Birthday `form:"birthdaysDef,default=2020-09-01;2020-09-02,parser=encoding.TextUnmarshaler" collection_format:"csv"`1039+ }1040+ route.GET("/test", func(ctx *gin.Context) {1041+ _ = ctx.BindQuery(&request)1042+ ctx.JSON(200, request)1043+ })1044+ _ = route.Run(":8088")1045+}1046+```1047+1048+Test it with:1049+1050+```sh1051+curl 'localhost:8088/test?birthday=2000-01-01&birthdays=2000-01-01,2000-01-02'1052+```1053+Result1054+```sh1055+{"Birthday":"2000/01/01","Birthdays":["2000/01/01","2000/01/02"],"BirthdaysDefault":["2020/09/01","2020/09/02"]}1056+```1057+1058+Note:1059+- If `parser=encoding.TextUnmarshaler` is specified for a type that does **not** implement `encoding.TextUnmarshaler`, gin will ignore it and proceed with its default binding logic.1060+- If `parser=encoding.TextUnmarshaler` is specified for a type and that type's implementation of `encoding.TextUnmarshaler` returns an error, gin will stop binding and return the error to the client.1061+1062+---1063+1064+If a type already implements `encoding.TextUnmarshaler` but you want to customize how gin binds the type differently (eg to change what error message is returned), you can implement the dedicated `BindUnmarshaler` interface provided by gin instead.1065+1066+```go1067+package main1068+1069+import (1070 "strings"1071+1072+ "github.com/gin-gonic/gin"1073+ "github.com/gin-gonic/gin/binding"1074 )1075 1076 type Birthday string1077 1 unmodified line1079 *b = Birthday(strings.Replace(param, "-", "/", -1))1080 return nil1081 }1082 1083+var _ binding.BindUnmarshaler = (*Birthday)(nil) //assert Birthday implements binding.BindUnmarshaler1084+1085 func main() {1086 route := gin.Default()1087 var request struct {1030- Birthday Birthday `form:"birthday"`1088+ Birthday Birthday `form:"birthday"`1089+ Birthdays []Birthday `form:"birthdays" collection_format:"csv"`1090+ BirthdaysDefault []Birthday `form:"birthdaysDef,default=2020-09-01;2020-09-02" collection_format:"csv"`1091 }1092 route.GET("/test", func(ctx *gin.Context) {1093 _ = ctx.BindQuery(&request)1034- ctx.JSON(200, request.Birthday)1094+ ctx.JSON(200, request)1095 })1036- route.Run(":8088")1096+ _ = route.Run(":8088")1097 }1098 ```1099 1100 Test it with:1101 1102 ```sh1043-curl 'localhost:8088/test?birthday=2000-01-01'1103+curl 'localhost:8088/test?birthday=2000-01-01&birthdays=2000-01-01,2000-01-02'1104 ```1105 Result1106 ```sh1047-"2000/01/01"1107+{"Birthday":"2000/01/01","Birthdays":["2000/01/01","2000/01/02"],"BirthdaysDefault":["2020/09/01","2020/09/02"]}1108 ```1109 1110+Note:1111+- If a type implements both `encoding.TextUnmarshaler` and `BindUnmarshaler`, gin will use `BindUnmarshaler` by default unless you specify `parser=encoding.TextUnmarshaler` in the binding tag.1112+- If a type returns an error from its implementation of `BindUnmarshaler`, gin will stop binding and return the error to the client.1113+1114 ### Bind Header1115 1116 ```go1117 package main1504 unmodified lines