Skip to content
Myr

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

3 files+508 added−26 removed

modified:binding/form_mapping_test.go+390 added
3 unmodified lines
45package binding67import (8 "encoding"9 "encoding/hex"10 "errors"11 "mime/multipart"12 "reflect"
511 unmodified lines
524525 assert.EqualValues(t, 245, s.Foo)526}527528func 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)534535 assert.EqualValues(t, 0xf5, s.Foo)536}537538type customUnmarshalParamType struct {539 Protocol string540 Path string541 Name string
92 unmodified lines
634 assert.Equal(t, "bar", s.FileData[0])635 assert.Equal(t, "foo", s.FileData[1])636}637638func 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}646647func 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}655656func 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}664665type objectID [12]byte666667func (o *objectID) UnmarshalParam(param string) error {668 oid, err := convertTo(param)
43 unmodified lines
712 expected, _ := convertTo(val)713 assert.Equal(t, expected, s.FileData)714}715716func TestMappingCustomArrayOfArrayUri(t *testing.T) {717 id1, _ := convertTo(`664a062ac74a8ad104e0e80e`)718 id2, _ := convertTo(`664a062ac74a8ad104e0e80f`)719720 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}727728func TestMappingCustomArrayOfArrayForm(t *testing.T) {729 id1, _ := convertTo(`664a062ac74a8ad104e0e80e`)730 id2, _ := convertTo(`664a062ac74a8ad104e0e80f`)731732 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}739740// ==== TextUnmarshaler tests START ====741742type customUnmarshalTextHex int743744func (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}752753// verify type implements TextUnmarshaler754var _ encoding.TextUnmarshaler = (*customUnmarshalTextHex)(nil)755756func 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}764765func 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}773774func 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}782783type customUnmarshalTextType struct {784 Protocol string785 Path string786 Name string787}788789func (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}799800var _ encoding.TextUnmarshaler = (*customUnmarshalTextType)(nil)801802func 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)808809 assert.Equal(t, "file", s.FileData.Protocol)810 assert.Equal(t, "/foo", s.FileData.Path)811 assert.Equal(t, "happiness", s.FileData.Name)812}813814func 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)820821 assert.Equal(t, "file", s.FileData.Protocol)822 assert.Equal(t, "/foo", s.FileData.Path)823 assert.Equal(t, "happiness", s.FileData.Name)824}825826func 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)832833 assert.Equal(t, "file", s.FileData.Protocol)834 assert.Equal(t, "/foo", s.FileData.Path)835 assert.Equal(t, "happiness", s.FileData.Name)836}837838func 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)844845 assert.Equal(t, "file", s.FileData.Protocol)846 assert.Equal(t, "/foo", s.FileData.Path)847 assert.Equal(t, "happiness", s.FileData.Name)848}849850type customPathUnmarshalText []string851852func (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 }858859 *p = elems860 return nil861}862863var _ encoding.TextUnmarshaler = (*customPathUnmarshalText)(nil)864865func 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)871872 assert.Equal(t, "bar", s.FileData[0])873 assert.Equal(t, "foo", s.FileData[1])874}875876func 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)882883 assert.Equal(t, "bar", s.FileData[0])884 assert.Equal(t, "foo", s.FileData[1])885}886887func 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}895896func 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}904905func 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}913914func 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}922923type objectIDUnmarshalText [12]byte924925func (o *objectIDUnmarshalText) UnmarshalText(text []byte) error {926 oid, err := convertToOidUnmarshalText(string(text))927 if err != nil {928 return err929 }930931 *o = oid932 return nil933}934935func convertToOidUnmarshalText(s string) (objectIDUnmarshalText, error) {936 oid, err := convertTo(s)937 return objectIDUnmarshalText(oid), err938}939940var _ encoding.TextUnmarshaler = (*objectIDUnmarshalText)(nil)941942func 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)949950 expected, _ := convertToOidUnmarshalText(val)951 assert.Equal(t, expected, s.FileData)952}953954func 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)961962 expected, _ := convertToOidUnmarshalText(val)963 assert.Equal(t, expected, s.FileData)964}965966func TestMappingCustomArrayOfArrayUnmarshalTextUri(t *testing.T) {967 id1, _ := convertToOidUnmarshalText(`664a062ac74a8ad104e0e80e`)968 id2, _ := convertToOidUnmarshalText(`664a062ac74a8ad104e0e80f`)969970 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}977978func TestMappingCustomArrayOfArrayUnmarshalTextForm(t *testing.T) {979 id1, _ := convertToOidUnmarshalText(`664a062ac74a8ad104e0e80e`)980 id2, _ := convertToOidUnmarshalText(`664a062ac74a8ad104e0e80f`)981982 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}989990func TestMappingCustomArrayOfArrayUnmarshalTextDefault(t *testing.T) {991 id1, _ := convertToOidUnmarshalText(`664a062ac74a8ad104e0e80e`)992 id2, _ := convertToOidUnmarshalText(`664a062ac74a8ad104e0e80f`)993994 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}10011002// If someone specifies parser=TextUnmarshaler and it's not defined for the type, gin should revert to using its default1003// binding logic.1004func 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)10141015 assert.EqualValues(t, 0xf5, s.Hex)1016 assert.EqualValues(t, 0xf5, s.HexByUnmarshalText) // reverts to BindUnmarshaler binding1017}10181019// 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)1022func 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)10321033 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}10361037type customHexUnmarshalParamAndUnmarshalText int10381039func (f *customHexUnmarshalParamAndUnmarshalText) UnmarshalParam(param string) error {1040 return errors.New("should not be called in unit test if parser tag present")1041}10421043func (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}10511052// 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.1054func 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)10621063 assert.EqualValues(t, 0xf5, s.Hex)1064}10651066// ==== TextUnmarshaler tests END ====10671068func 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 lines
modified:binding/form_mapping.go+48 added-20 removed
3 unmodified lines
45package binding67import (8 "encoding"9 "errors"10 "fmt"11 "maps"12 "mime/multipart"
124 unmodified lines
137138type 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}144145func tryToSetValue(value reflect.Value, field reflect.StructField, setter setter, tag string) (bool, error) {146 var tagValue string
23 unmodified lines
170 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 }178179 return setter.TrySet(value, field, tagValue, setOpt)
15 unmodified lines
195 }196 return false, nil197}198199// 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.201func 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}212213func 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, nil
9 unmodified lines
226 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 }232233 totalLength := 0234 for _, v := range vs {
27 unmodified lines
262 vs = strings.Split(opt.defaultValue, ",")263 }264 }265247 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 }271272 if vs, err = trySplit(vs, field); err != nil {273 return false, err274 }275255 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, nil
6 unmodified lines
287 vs = strings.Split(opt.defaultValue, ",")288 }289 }290270 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 }296297 if vs, err = trySplit(vs, field); err != nil {298 return false, err
2 unmodified lines
301 if len(vs) != value.Len() {302 return false, fmt.Errorf("%q is not valid value for %s", vs, value.Type().String())303 }304282 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 }288289 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 {313314 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}322302func setWithProperType(val string, value reflect.Value, field reflect.StructField) error {323func 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 }330331 // 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 lines
379 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 nil
98 unmodified lines
486 value.Set(reflect.ValueOf(t))487 return nil488}489462func setArray(vals []string, value reflect.Value, field reflect.StructField) error {490func 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}499472func setSlice(vals []string, value reflect.Value, field reflect.StructField) error {500func 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 lines
modified:docs/doc.md+70 added-6 removed
909 unmodified lines
910```911912NOTE: 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"916917918#### Collection format for arrays
89 unmodified lines
1008```10091010### Bind custom unmarshaler10111012To 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.10131014```go1015package main10161017import (1018 "encoding"1019 "strings"10201021 "github.com/gin-gonic/gin"1022)10231024type Birthday string10251026func (b *Birthday) UnmarshalText(text []byte) error {1027 *b = Birthday(strings.Replace(string(text), "-", "/", -1))1028 return nil1029}10301031var _ encoding.TextUnmarshaler = (*Birthday)(nil) //assert Birthday implements encoding.TextUnmarshaler10321033func 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```10471048Test it with:10491050```sh1051curl 'localhost:8088/test?birthday=2000-01-01&birthdays=2000-01-01,2000-01-02'1052```1053Result1054```sh1055{"Birthday":"2000/01/01","Birthdays":["2000/01/01","2000/01/02"],"BirthdaysDefault":["2020/09/01","2020/09/02"]}1056```10571058Note: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.10611062---10631064If 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.10651066```go1067package main10681069import (1070 "strings"10711072 "github.com/gin-gonic/gin"1073 "github.com/gin-gonic/gin/binding"1074)10751076type Birthday string1077
1 unmodified line
1079 *b = Birthday(strings.Replace(param, "-", "/", -1))1080 return nil1081}10821083var _ binding.BindUnmarshaler = (*Birthday)(nil) //assert Birthday implements binding.BindUnmarshaler10841085func 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```10991100Test it with:11011102```sh1043curl 'localhost:8088/test?birthday=2000-01-01'1103curl 'localhost:8088/test?birthday=2000-01-01&birthdays=2000-01-01,2000-01-02'1104```1105Result1106```sh1047"2000/01/01"1107{"Birthday":"2000/01/01","Birthdays":["2000/01/01","2000/01/02"],"BirthdaysDefault":["2020/09/01","2020/09/02"]}1108```11091110Note: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.11131114### Bind Header11151116```go1117package main
1504 unmodified lines