test support go1.18 (#2990)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by thinkerou · committed by GitHub · parent 9701b65 · Browse files · 47 files·+214 added−174 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
47 files+214 added−174 removed
- other:+214 added−174 removed
Provenance
- Commit
2bde107- Tree
9ed53ab- Author
thinkerou <thinkerou@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
9701b65
47 files changed+214 added−174 removed
added:binding/any.go+10 added
1+// Copyright 2022 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+//go:build !go1.186+// +build !go1.187+8+package binding9+10+type any = interface{}modified:binding/binding_nomsgpack.go+6 added-6 removed
25 unmodified lines26 // data present in the request such as JSON request body, query parameters or27 // the form POST.28 type Binding interface {29 Name() string30- Bind(*http.Request, interface{}) error30+ Bind(*http.Request, any) error31 }32 33 // BindingBody adds BindBody method to Binding. BindBody is similar with Bind,34 // but it reads the body from supplied bytes instead of req.Body.35 type BindingBody interface {36 Binding37- BindBody([]byte, interface{}) error37+ BindBody([]byte, any) error38 }39 40 // BindingUri adds BindUri method to Binding. BindUri is similar with Bind,41 // but it reads the Params.42 type BindingUri interface {43 Name() string44- BindUri(map[string][]string, interface{}) error44+ BindUri(map[string][]string, any) error45 }46 47 // StructValidator is the minimal interface which needs to be implemented in48 // order for it to be used as the validator engine for ensuring the correctness4 unmodified lines53 // If the received type is not a struct, any validation should be skipped and nil must be returned.54 // If the received type is a struct or pointer to a struct, the validation should be performed.55 // If the struct is not valid or the validation itself fails, a descriptive error should be returned.56 // Otherwise nil must be returned.57- ValidateStruct(interface{}) error57+ ValidateStruct(any) error58 59 // Engine returns the underlying validator engine which powers the60 // StructValidator implementation.61- Engine() interface{}61+ Engine() any62 }63 64 // Validator is the default validator which implements the StructValidator65 // interface. It uses https://github.com/go-playground/validator/tree/v10.6.137 unmodified lines103 return Form104 }105 }106 107-func validate(obj interface{}) error {107+func validate(obj any) error {108 if Validator == nil {109 return nil110 }111 return Validator.ValidateStruct(obj)1 unmodified linemodified:binding/binding_test.go+9 added-9 removed
59 unmodified lines60 Bar string `msgpack:"bar" json:"bar" form:"bar,default=hello" xml:"bar" binding:"required"`61 }62 63 type FooStructUseNumber struct {64- Foo interface{} `json:"foo" binding:"required"`64+ Foo any `json:"foo" binding:"required"`65 }66 67 type FooStructDisallowUnknownFields struct {68- Foo interface{} `json:"foo" binding:"required"`68+ Foo any `json:"foo" binding:"required"`69 }70 71 type FooBarStructForTimeType struct {72 TimeFoo time.Time `form:"time_foo" time_format:"2006-01-02" time_utc:"1" time_location:"Asia/Chongqing"`19 unmodified lines92 TimeFoo time.Time `form:"time_foo" time_format:"2006-01-02" time_location:"/asia/chongqing"`93 }94 95 type FooStructForMapType struct {96- MapFoo map[string]interface{} `form:"map_foo"`96+ MapFoo map[string]any `form:"map_foo"`97 }98 99 type FooStructForIgnoreFormTag struct {100 Foo *string `form:"-"`4 unmodified lines105 }106 107 type InvalidNameMapType struct {108 TestName struct {109- MapFoo map[string]interface{} `form:"map_foo"`109+ MapFoo map[string]any `form:"map_foo"`110 }111 }112 113 type FooStructForSliceType struct {13 unmodified lines127 }128 129 type FooStructForSliceMapType struct {130 // Unknown type: not support map131- SliceMapFoo []map[string]interface{} `form:"slice_map_foo"`131+ SliceMapFoo []map[string]any `form:"slice_map_foo"`132 }133 134 type FooStructForBoolType struct {135 BoolFoo bool `form:"bool_foo"`4 unmodified lines140 PtrBar *string `form:"ptr_bar" binding:"required"`141 }142 143 type FooStructForMapPtrType struct {144- PtrBar *map[string]interface{} `form:"ptr_bar"`144+ PtrBar *map[string]any `form:"ptr_bar"`145 }146 147 func TestBindingDefault(t *testing.T) {148 assert.Equal(t, Form, Default("GET", ""))618 unmodified lines767 req = requestWithBody("GET", "/", "")768 req.Header.Add("fail", `{fail:fail}`)769 770 type failStruct struct {771- Fail map[string]interface{} `header:"fail"`771+ Fail map[string]any `header:"fail"`772 }773 774 err := h.Bind(req, &failStruct{})775 assert.Error(t, err)12 unmodified lines788 assert.NoError(t, b.BindUri(m, &tag))789 assert.Equal(t, "thinkerou", tag.Name)790 791 type NotSupportStruct struct {792- Name map[string]interface{} `uri:"name"`792+ Name map[string]any `uri:"name"`793 }794 var not NotSupportStruct795 assert.Error(t, b.BindUri(m, ¬))796- assert.Equal(t, map[string]interface{}(nil), not.Name)796+ assert.Equal(t, map[string]any(nil), not.Name)797 }798 799 func TestUriInnerBinding(t *testing.T) {800 type Tag struct {559 unmodified linesmodified:binding/binding.go+6 added-6 removed
27 unmodified lines28 // data present in the request such as JSON request body, query parameters or29 // the form POST.30 type Binding interface {31 Name() string32- Bind(*http.Request, interface{}) error32+ Bind(*http.Request, any) error33 }34 35 // BindingBody adds BindBody method to Binding. BindBody is similar with Bind,36 // but it reads the body from supplied bytes instead of req.Body.37 type BindingBody interface {38 Binding39- BindBody([]byte, interface{}) error39+ BindBody([]byte, any) error40 }41 42 // BindingUri adds BindUri method to Binding. BindUri is similar with Bind,43 // but it reads the Params.44 type BindingUri interface {45 Name() string46- BindUri(map[string][]string, interface{}) error46+ BindUri(map[string][]string, any) error47 }48 49 // StructValidator is the minimal interface which needs to be implemented in50 // order for it to be used as the validator engine for ensuring the correctness5 unmodified lines56 // If the received type is not a struct or slice|array, any validation should be skipped and nil must be returned.57 // If the received type is a struct or pointer to a struct, the validation should be performed.58 // If the struct is not valid or the validation itself fails, a descriptive error should be returned.59 // Otherwise nil must be returned.60- ValidateStruct(interface{}) error60+ ValidateStruct(any) error61 62 // Engine returns the underlying validator engine which powers the63 // StructValidator implementation.64- Engine() interface{}64+ Engine() any65 }66 67 // Validator is the default validator which implements the StructValidator68 // interface. It uses https://github.com/go-playground/validator/tree/v10.6.140 unmodified lines109 return Form110 }111 }112 113-func validate(obj interface{}) error {113+func validate(obj any) error {114 if Validator == nil {115 return nil116 }117 return Validator.ValidateStruct(obj)1 unmodified linemodified:binding/default_validator_test.go+1 added-1 removed
52 unmodified lines53 }54 tests := []struct {55 name string56 v *defaultValidator57- obj interface{}57+ obj any58 wantErr bool59 }{60 {"validate nil obj", &defaultValidator{}, nil, false},61 {"validate int obj", &defaultValidator{}, 3, false},27 unmodified linesmodified:binding/default_validator.go+3 added-3 removed
44 unmodified lines45 46 var _ StructValidator = &defaultValidator{}47 48 // ValidateStruct receives any kind of type, but only performed struct or pointer to struct type.49-func (v *defaultValidator) ValidateStruct(obj interface{}) error {49+func (v *defaultValidator) ValidateStruct(obj any) error {50 if obj == nil {51 return nil52 }53 20 unmodified lines74 }75 }76 77 // validateStruct receives struct type78-func (v *defaultValidator) validateStruct(obj interface{}) error {78+func (v *defaultValidator) validateStruct(obj any) error {79 v.lazyinit()80 return v.validate.Struct(obj)81 }82 83 // Engine returns the underlying validator engine which powers the default84 // Validator instance. This is useful if you want to register custom validations85 // or struct level validations. See validator GoDoc for more info -86 // https://pkg.go.dev/github.com/go-playground/validator/v1087-func (v *defaultValidator) Engine() interface{} {87+func (v *defaultValidator) Engine() any {88 v.lazyinit()89 return v.validate90 }91 6 unmodified linesmodified:binding/form_mapping_test.go+2 added-2 removed
16 unmodified lines17 return &i18 }19 for _, tt := range []struct {20 name string21- value interface{}21+ value any22 form string23- expect interface{}23+ expect any24 }{25 {"base type", struct{ F int }{}, "9", int(9)},26 {"base type", struct{ F int8 }{}, "9", int8(9)},27 {"base type", struct{ F int16 }{}, "9", int16(9)},263 unmodified linesmodified:binding/form_mapping.go+7 added-7 removed
24 unmodified lines25 // ErrConvertToMapString can not convert to map[string]string26 ErrConvertToMapString = errors.New("can not convert to map of strings")27 )28 29-func mapURI(ptr interface{}, m map[string][]string) error {29+func mapURI(ptr any, m map[string][]string) error {30 return mapFormByTag(ptr, m, "uri")31 }32 33-func mapForm(ptr interface{}, form map[string][]string) error {33+func mapForm(ptr any, form map[string][]string) error {34 return mapFormByTag(ptr, form, "form")35 }36 37-func MapFormWithTag(ptr interface{}, form map[string][]string, tag string) error {37+func MapFormWithTag(ptr any, form map[string][]string, tag string) error {38 return mapFormByTag(ptr, form, tag)39 }40 41 var emptyField = reflect.StructField{}42 43-func mapFormByTag(ptr interface{}, form map[string][]string, tag string) error {43+func mapFormByTag(ptr any, form map[string][]string, tag string) error {44 // Check if ptr is a map45 ptrVal := reflect.ValueOf(ptr)46- var pointed interface{}46+ var pointed any47 if ptrVal.Kind() == reflect.Ptr {48 ptrVal = ptrVal.Elem()49 pointed = ptrVal.Interface()50 }21 unmodified lines72 func (form formSource) TrySet(value reflect.Value, field reflect.StructField, tagValue string, opt setOptions) (isSet bool, err error) {73 return setByForm(value, field, form, tagValue, opt)74 }75 76-func mappingByPtr(ptr interface{}, setter setter, tag string) error {76+func mappingByPtr(ptr any, setter setter, tag string) error {77 _, err := mapping(reflect.ValueOf(ptr), emptyField, setter, tag)78 return err79 }80 294 unmodified lines375 }376 return str[:idx], str[idx+len(sep):]377 }378 379-func setFormMap(ptr interface{}, form map[string][]string) error {379+func setFormMap(ptr any, form map[string][]string) error {380 el := reflect.TypeOf(ptr).Elem()381 382 if el.Kind() == reflect.Slice {383 ptrMap, ok := ptr.(map[string][]string)20 unmodified linesmodified:binding/form.go+3 added-3 removed
17 unmodified lines18 func (formBinding) Name() string {19 return "form"20 }21 22-func (formBinding) Bind(req *http.Request, obj interface{}) error {22+func (formBinding) Bind(req *http.Request, obj any) error {23 if err := req.ParseForm(); err != nil {24 return err25 }26 if err := req.ParseMultipartForm(defaultMemory); err != nil && !errors.Is(err, http.ErrNotMultipart) {8 unmodified lines35 func (formPostBinding) Name() string {36 return "form-urlencoded"37 }38 39-func (formPostBinding) Bind(req *http.Request, obj interface{}) error {39+func (formPostBinding) Bind(req *http.Request, obj any) error {40 if err := req.ParseForm(); err != nil {41 return err42 }43 if err := mapForm(obj, req.PostForm); err != nil {5 unmodified lines49 func (formMultipartBinding) Name() string {50 return "multipart/form-data"51 }52 53-func (formMultipartBinding) Bind(req *http.Request, obj interface{}) error {53+func (formMultipartBinding) Bind(req *http.Request, obj any) error {54 if err := req.ParseMultipartForm(defaultMemory); err != nil {55 return err56 }57 if err := mappingByPtr(obj, (*multipartRequest)(req), "form"); err != nil {5 unmodified linesmodified:binding/header.go+2 added-2 removed
10 unmodified lines11 func (headerBinding) Name() string {12 return "header"13 }14 15-func (headerBinding) Bind(req *http.Request, obj interface{}) error {15+func (headerBinding) Bind(req *http.Request, obj any) error {16 17 if err := mapHeader(obj, req.Header); err != nil {18 return err19 }20 21 return validate(obj)22 }23 24-func mapHeader(ptr interface{}, h map[string][]string) error {24+func mapHeader(ptr any, h map[string][]string) error {25 return mappingByPtr(ptr, headerSource(h), "header")26 }27 28 type headerSource map[string][]string6 unmodified linesmodified:binding/json.go+3 added-3 removed
28 unmodified lines29 func (jsonBinding) Name() string {30 return "json"31 }32 33-func (jsonBinding) Bind(req *http.Request, obj interface{}) error {33+func (jsonBinding) Bind(req *http.Request, obj any) error {34 if req == nil || req.Body == nil {35 return errors.New("invalid request")36 }37 return decodeJSON(req.Body, obj)38 }39 40-func (jsonBinding) BindBody(body []byte, obj interface{}) error {40+func (jsonBinding) BindBody(body []byte, obj any) error {41 return decodeJSON(bytes.NewReader(body), obj)42 }43 44-func decodeJSON(r io.Reader, obj interface{}) error {44+func decodeJSON(r io.Reader, obj any) error {45 decoder := json.NewDecoder(r)46 if EnableDecoderUseNumber {47 decoder.UseNumber()48 }8 unmodified linesmodified:binding/msgpack_test.go+1 added-1 removed
24 unmodified lines25 require.NoError(t, err)26 assert.Equal(t, "FOO", s.Foo)27 }28 29-func msgpackBody(t *testing.T, obj interface{}) []byte {29+func msgpackBody(t *testing.T, obj any) []byte {30 var bs bytes.Buffer31 h := &codec.MsgpackHandle{}32 err := codec.NewEncoder(&bs, h).Encode(obj)33 require.NoError(t, err)2 unmodified linesmodified:binding/msgpack.go+3 added-3 removed
19 unmodified lines20 func (msgpackBinding) Name() string {21 return "msgpack"22 }23 24-func (msgpackBinding) Bind(req *http.Request, obj interface{}) error {24+func (msgpackBinding) Bind(req *http.Request, obj any) error {25 return decodeMsgPack(req.Body, obj)26 }27 28-func (msgpackBinding) BindBody(body []byte, obj interface{}) error {28+func (msgpackBinding) BindBody(body []byte, obj any) error {29 return decodeMsgPack(bytes.NewReader(body), obj)30 }31 32-func decodeMsgPack(r io.Reader, obj interface{}) error {32+func decodeMsgPack(r io.Reader, obj any) error {33 cdc := new(codec.MsgpackHandle)34 if err := codec.NewDecoder(r, cdc).Decode(&obj); err != nil {35 return err36 }2 unmodified linesmodified:binding/multipart_form_mapping_test.go+1 added-1 removed
74 unmodified lines75 }76 77 for _, tt := range []struct {78 name string79- s interface{}79+ s any80 }{81 {"wrong type", &struct {82 Files int `form:"file"`83 }{}},55 unmodified linesmodified:binding/protobuf.go+2 added-2 removed
16 unmodified lines17 func (protobufBinding) Name() string {18 return "protobuf"19 }20 21-func (b protobufBinding) Bind(req *http.Request, obj interface{}) error {21+func (b protobufBinding) Bind(req *http.Request, obj any) error {22 buf, err := ioutil.ReadAll(req.Body)23 if err != nil {24 return err25 }26 return b.BindBody(buf, obj)27 }28 29-func (protobufBinding) BindBody(body []byte, obj interface{}) error {29+func (protobufBinding) BindBody(body []byte, obj any) error {30 msg, ok := obj.(proto.Message)31 if !ok {32 return errors.New("obj is not ProtoMessage")33 }8 unmodified linesmodified:binding/query.go+1 added-1 removed
10 unmodified lines11 func (queryBinding) Name() string {12 return "query"13 }14 15-func (queryBinding) Bind(req *http.Request, obj interface{}) error {15+func (queryBinding) Bind(req *http.Request, obj any) error {16 values := req.URL.Query()17 if err := mapForm(obj, values); err != nil {18 return err19 }2 unmodified linesmodified:binding/uri.go+1 added-1 removed
8 unmodified lines9 func (uriBinding) Name() string {10 return "uri"11 }12 13-func (uriBinding) BindUri(m map[string][]string, obj interface{}) error {13+func (uriBinding) BindUri(m map[string][]string, obj any) error {14 if err := mapURI(obj, m); err != nil {15 return err16 }17 return validate(obj)1 unmodified linemodified:binding/validate_test.go+2 added-2 removed
57 unmodified lines58 StructPointerSlice []*substructNoValidation59 StructSlice []substructNoValidation60 InterfaceSlice []testInterface61 62- UniversalInterface interface{}62+ UniversalInterface any63 CustomInterface testInterface64 65 FloatMap map[string]float3266 StructMap mapNoValidationSub101 unmodified lines168 169 //assert.Equal(t, origin, test)170 }171 172-type Object map[string]interface{}172+type Object map[string]any173 174 func TestValidatePrimitives(t *testing.T) {175 obj := Object{"foo": "bar", "bar": 1}176 assert.NoError(t, validate(obj))52 unmodified linesmodified:binding/xml.go+3 added-3 removed
15 unmodified lines16 func (xmlBinding) Name() string {17 return "xml"18 }19 20-func (xmlBinding) Bind(req *http.Request, obj interface{}) error {20+func (xmlBinding) Bind(req *http.Request, obj any) error {21 return decodeXML(req.Body, obj)22 }23 24-func (xmlBinding) BindBody(body []byte, obj interface{}) error {24+func (xmlBinding) BindBody(body []byte, obj any) error {25 return decodeXML(bytes.NewReader(body), obj)26 }27-func decodeXML(r io.Reader, obj interface{}) error {27+func decodeXML(r io.Reader, obj any) error {28 decoder := xml.NewDecoder(r)29 if err := decoder.Decode(obj); err != nil {30 return err31 }2 unmodified linesmodified:binding/yaml.go+3 added-3 removed
16 unmodified lines17 func (yamlBinding) Name() string {18 return "yaml"19 }20 21-func (yamlBinding) Bind(req *http.Request, obj interface{}) error {21+func (yamlBinding) Bind(req *http.Request, obj any) error {22 return decodeYAML(req.Body, obj)23 }24 25-func (yamlBinding) BindBody(body []byte, obj interface{}) error {25+func (yamlBinding) BindBody(body []byte, obj any) error {26 return decodeYAML(bytes.NewReader(body), obj)27 }28 29-func decodeYAML(r io.Reader, obj interface{}) error {29+func decodeYAML(r io.Reader, obj any) error {30 decoder := yaml.NewDecoder(r)31 if err := decoder.Decode(obj); err != nil {32 return err33 }2 unmodified linesadded:render/any.go+10 added
1+// Copyright 2021 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+//go:build !go1.186+// +build !go1.187+8+package render9+10+type any = interface{}modified:render/html.go+4 added-4 removed
18 unmodified lines19 20 // HTMLRender interface is to be implemented by HTMLProduction and HTMLDebug.21 type HTMLRender interface {22 // Instance returns an HTML instance.23- Instance(string, interface{}) Render23+ Instance(string, any) Render24 }25 26 // HTMLProduction contains template reference and its delims.27 type HTMLProduction struct {12 unmodified lines40 // HTML contains template reference and its name with given interface object.41 type HTML struct {42 Template *template.Template43 Name string44- Data interface{}44+ Data any45 }46 47 var htmlContentType = []string{"text/html; charset=utf-8"}48 49 // Instance (HTMLProduction) returns an HTML instance which it realizes Render interface.50-func (r HTMLProduction) Instance(name string, data interface{}) Render {50+func (r HTMLProduction) Instance(name string, data any) Render {51 return HTML{52 Template: r.Template,53 Name: name,54 Data: data,55 }56 }57 58 // Instance (HTMLDebug) returns an HTML instance which it realizes Render interface.59-func (r HTMLDebug) Instance(name string, data interface{}) Render {59+func (r HTMLDebug) Instance(name string, data any) Render {60 return HTML{61 Template: r.loadTemplate(),62 Name: name,63 Data: data,29 unmodified linesmodified:render/json.go+7 added-7 removed
14 unmodified lines15 )16 17 // JSON contains the given interface object.18 type JSON struct {19- Data interface{}19+ Data any20 }21 22 // IndentedJSON contains the given interface object.23 type IndentedJSON struct {24- Data interface{}24+ Data any25 }26 27 // SecureJSON contains the given interface object and its prefix.28 type SecureJSON struct {29 Prefix string30- Data interface{}30+ Data any31 }32 33 // JsonpJSON contains the given interface object its callback.34 type JsonpJSON struct {35 Callback string36- Data interface{}36+ Data any37 }38 39 // AsciiJSON contains the given interface object.40 type AsciiJSON struct {41- Data interface{}41+ Data any42 }43 44 // PureJSON contains the given interface object.45 type PureJSON struct {46- Data interface{}46+ Data any47 }48 49 var (50 jsonContentType = []string{"application/json; charset=utf-8"}14 unmodified lines65 writeContentType(w, jsonContentType)66 }67 68 // WriteJSON marshals the given interface object and writes it with custom ContentType.69-func WriteJSON(w http.ResponseWriter, obj interface{}) error {69+func WriteJSON(w http.ResponseWriter, obj any) error {70 writeContentType(w, jsonContentType)71 jsonBytes, err := json.Marshal(obj)72 if err != nil {73 return err120 unmodified linesmodified:render/msgpack.go+2 added-2 removed
19 unmodified lines20 )21 22 // MsgPack contains the given interface object.23 type MsgPack struct {24- Data interface{}24+ Data any25 }26 27 var msgpackContentType = []string{"application/msgpack; charset=utf-8"}28 7 unmodified lines36 return WriteMsgPack(w, r.Data)37 }38 39 // WriteMsgPack writes MsgPack ContentType and encodes the given interface object.40-func WriteMsgPack(w http.ResponseWriter, obj interface{}) error {40+func WriteMsgPack(w http.ResponseWriter, obj any) error {41 writeContentType(w, msgpackContentType)42 var mh codec.MsgpackHandle43 return codec.NewEncoder(w, &mh).Encode(obj)44 }modified:render/protobuf.go+1 added-1 removed
10 unmodified lines11 )12 13 // ProtoBuf contains the given interface object.14 type ProtoBuf struct {15- Data interface{}15+ Data any16 }17 18 var protobufContentType = []string{"application/x-protobuf"}19 17 unmodified linesmodified:render/render_msgpack_test.go+1 added-1 removed
19 unmodified lines20 // test errors21 22 func TestRenderMsgPack(t *testing.T) {23 w := httptest.NewRecorder()24- data := map[string]interface{}{24+ data := map[string]any{25 "foo": "bar",26 }27 28 (MsgPack{data}).WriteContentType(w)16 unmodified linesmodified:render/render_test.go+18 added-18 removed
22 unmodified lines23 // test errors24 25 func TestRenderJSON(t *testing.T) {26 w := httptest.NewRecorder()27- data := map[string]interface{}{27+ data := map[string]any{28 "foo": "bar",29 "html": "<b>",30 }31 16 unmodified lines48 }49 50 func TestRenderIndentedJSON(t *testing.T) {51 w := httptest.NewRecorder()52- data := map[string]interface{}{52+ data := map[string]any{53 "foo": "bar",54 "bar": "foo",55 }56 14 unmodified lines71 }72 73 func TestRenderSecureJSON(t *testing.T) {74 w1 := httptest.NewRecorder()75- data := map[string]interface{}{75+ data := map[string]any{76 "foo": "bar",77 }78 79 (SecureJSON{"while(1);", data}).WriteContentType(w1)5 unmodified lines85 assert.Equal(t, "{\"foo\":\"bar\"}", w1.Body.String())86 assert.Equal(t, "application/json; charset=utf-8", w1.Header().Get("Content-Type"))87 88 w2 := httptest.NewRecorder()89- datas := []map[string]interface{}{{89+ datas := []map[string]any{{90 "foo": "bar",91 }, {92 "bar": "foo",93 }}14 unmodified lines108 }109 110 func TestRenderJsonpJSON(t *testing.T) {111 w1 := httptest.NewRecorder()112- data := map[string]interface{}{112+ data := map[string]any{113 "foo": "bar",114 }115 116 (JsonpJSON{"x", data}).WriteContentType(w1)5 unmodified lines122 assert.Equal(t, "x({\"foo\":\"bar\"});", w1.Body.String())123 assert.Equal(t, "application/javascript; charset=utf-8", w1.Header().Get("Content-Type"))124 125 w2 := httptest.NewRecorder()126- datas := []map[string]interface{}{{126+ datas := []map[string]any{{127 "foo": "bar",128 }, {129 "bar": "foo",130 }}5 unmodified lines136 }137 138 func TestRenderJsonpJSONError2(t *testing.T) {139 w := httptest.NewRecorder()140- data := map[string]interface{}{140+ data := map[string]any{141 "foo": "bar",142 }143 (JsonpJSON{"", data}).WriteContentType(w)144 assert.Equal(t, "application/javascript; charset=utf-8", w.Header().Get("Content-Type"))15 unmodified lines160 }161 162 func TestRenderAsciiJSON(t *testing.T) {163 w1 := httptest.NewRecorder()164- data1 := map[string]interface{}{164+ data1 := map[string]any{165 "lang": "GO语言",166 "tag": "<br>",167 }168 20 unmodified lines189 }190 191 func TestRenderPureJSON(t *testing.T) {192 w := httptest.NewRecorder()193- data := map[string]interface{}{193+ data := map[string]any{194 "foo": "bar",195 "html": "<b>",196 }197 err := (PureJSON{data}).Render(w)1 unmodified line199 assert.Equal(t, "{\"foo\":\"bar\",\"html\":\"<b>\"}\n", w.Body.String())200 assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))201 }202 203-type xmlmap map[string]interface{}203+type xmlmap map[string]any204 205 // Allows type H to be used with xml.Marshal206 func (h xmlmap) MarshalXML(e *xml.Encoder, start xml.StartElement) error {207 start.Name = xml.Name{35 unmodified lines243 244 type fail struct{}245 246 // Hook MarshalYAML247-func (ft *fail) MarshalYAML() (interface{}, error) {247+func (ft *fail) MarshalYAML() (any, error) {248 return nil, errors.New("fail")249 }250 251 func TestRenderYAMLFail(t *testing.T) {105 unmodified lines357 w := httptest.NewRecorder()358 359 (String{360 Format: "hello %s %d",361- Data: []interface{}{},361+ Data: []any{},362 }).WriteContentType(w)363 assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type"))364 365 err := (String{366 Format: "hola %s %d",367- Data: []interface{}{"manu", 2},367+ Data: []any{"manu", 2},368 }).Render(w)369 370 assert.NoError(t, err)371 assert.Equal(t, "hola manu 2", w.Body.String())4 unmodified lines376 w := httptest.NewRecorder()377 378 err := (String{379 Format: "hola %s %d",380- Data: []interface{}{},380+ Data: []any{},381 }).Render(w)382 383 assert.NoError(t, err)384 assert.Equal(t, "hola %s %d", w.Body.String())4 unmodified lines389 w := httptest.NewRecorder()390 templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))391 392 htmlRender := HTMLProduction{Template: templ}393- instance := htmlRender.Instance("t", map[string]interface{}{393+ instance := htmlRender.Instance("t", map[string]any{394 "name": "alexandernyquist",395 })396 397 err := instance.Render(w)7 unmodified lines405 w := httptest.NewRecorder()406 templ := template.Must(template.New("").Parse(`Hello {{.name}}`))407 408 htmlRender := HTMLProduction{Template: templ}409- instance := htmlRender.Instance("", map[string]interface{}{409+ instance := htmlRender.Instance("", map[string]any{410 "name": "alexandernyquist",411 })412 413 err := instance.Render(w)10 unmodified lines424 Glob: "",425 Delims: Delims{Left: "{[{", Right: "}]}"},426 FuncMap: nil,427 }428- instance := htmlRender.Instance("hello.tmpl", map[string]interface{}{428+ instance := htmlRender.Instance("hello.tmpl", map[string]any{429 "name": "thinkerou",430 })431 432 err := instance.Render(w)10 unmodified lines443 Glob: "../testdata/template/hello*",444 Delims: Delims{Left: "{[{", Right: "}]}"},445 FuncMap: nil,446 }447- instance := htmlRender.Instance("hello.tmpl", map[string]interface{}{447+ instance := htmlRender.Instance("hello.tmpl", map[string]any{448 "name": "thinkerou",449 })450 451 err := instance.Render(w)61 unmodified linesmodified:render/text.go+2 added-2 removed
12 unmodified lines13 14 // String contains the given interface object slice and its format.15 type String struct {16 Format string17- Data []interface{}17+ Data []any18 }19 20 var plainContentType = []string{"text/plain; charset=utf-8"}21 7 unmodified lines29 writeContentType(w, plainContentType)30 }31 32 // WriteString writes data according to its format and write custom ContentType.33-func WriteString(w http.ResponseWriter, format string, data []interface{}) (err error) {33+func WriteString(w http.ResponseWriter, format string, data []any) (err error) {34 writeContentType(w, plainContentType)35 if len(data) > 0 {36 _, err = fmt.Fprintf(w, format, data...)37 return4 unmodified linesmodified:render/xml.go+1 added-1 removed
9 unmodified lines10 )11 12 // XML contains the given interface object.13 type XML struct {14- Data interface{}14+ Data any15 }16 17 var xmlContentType = []string{"application/xml; charset=utf-8"}18 10 unmodified linesmodified:render/yaml.go+1 added-1 removed
10 unmodified lines11 )12 13 // YAML contains the given interface object.14 type YAML struct {15- Data interface{}15+ Data any16 }17 18 var yamlContentType = []string{"application/x-yaml; charset=utf-8"}19 17 unmodified linesadded:testdata/protoexample/any.go+10 added
1+// Copyright 2021 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+//go:build !go1.186+// +build !go1.187+8+package protoexample9+10+type any = interface{}modified:testdata/protoexample/test.pb.go+3 added-3 removed
229 unmodified lines230 }231 232 var file_test_proto_enumTypes = make([]protoimpl.EnumInfo, 1)233 var file_test_proto_msgTypes = make([]protoimpl.MessageInfo, 2)234-var file_test_proto_goTypes = []interface{}{234+var file_test_proto_goTypes = []any{235 (FOO)(0), // 0: protoexample.FOO236 (*Test)(nil), // 1: protoexample.Test237 (*Test_OptionalGroup)(nil), // 2: protoexample.Test.OptionalGroup238 }11 unmodified lines250 if File_test_proto != nil {251 return252 }253 if !protoimpl.UnsafeEnabled {254- file_test_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {254+ file_test_proto_msgTypes[0].Exporter = func(v any, i int) any {255 switch v := v.(*Test); i {256 case 0:257 return &v.state258 case 1:3 unmodified lines262 default:263 return nil264 }265 }266- file_test_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {266+ file_test_proto_msgTypes[1].Exporter = func(v any, i int) any {267 switch v := v.(*Test_OptionalGroup); i {268 case 0:269 return &v.state270 case 1:28 unmodified linesadded:any.go+10 added
1+// Copyright 2022 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+//go:build !go1.186+// +build !go1.187+8+package gin9+10+type any = interface{}modified:context_test.go+8 added-8 removed
210 unmodified lines211 c.Set("int64", int64(42424242424242))212 c.Set("uint64", uint64(42))213 c.Set("float32", float32(4.2))214 c.Set("float64", 4.2)215- var a interface{} = 1215+ var a any = 1216 c.Set("intInterface", a)217 218 assert.Exactly(t, c.MustGet("string").(string), "this is a string")219 assert.Exactly(t, c.MustGet("int32").(int32), int32(-42))66 unmodified lines286 }287 288 func TestContextGetStringMap(t *testing.T) {289 c, _ := CreateTestContext(httptest.NewRecorder())290- m := make(map[string]interface{})290+ m := make(map[string]any)291 m["foo"] = 1292 c.Set("map", m)293 294 assert.Equal(t, m, c.GetStringMap("map"))1829 unmodified lines2124 2125 func TestContextWithFallbackValueFromRequestContext(t *testing.T) {2126 tests := []struct {2127 name string2128- getContextAndKey func() (*Context, interface{})2129- value interface{}2128+ getContextAndKey func() (*Context, any)2129+ value any2130 }{2131 {2132 name: "c with struct context key",2133- getContextAndKey: func() (*Context, interface{}) {2133+ getContextAndKey: func() (*Context, any) {2134 var key struct{}2135 c := &Context{}2136 c.Request, _ = http.NewRequest("POST", "/", nil)2137 c.Request = c.Request.WithContext(context.WithValue(context.TODO(), key, "value"))2 unmodified lines2140 value: "value",2141 },2142 {2143 name: "c with string context key",2144- getContextAndKey: func() (*Context, interface{}) {2144+ getContextAndKey: func() (*Context, any) {2145 c := &Context{}2146 c.Request, _ = http.NewRequest("POST", "/", nil)2147 c.Request = c.Request.WithContext(context.WithValue(context.TODO(), contextKey("key"), "value"))2148 return c, contextKey("key")1 unmodified line2150 value: "value",2151 },2152 {2153 name: "c with nil http.Request",2154- getContextAndKey: func() (*Context, interface{}) {2154+ getContextAndKey: func() (*Context, any) {2155 c := &Context{}2156 return c, "key"2157 },2158 value: nil,2159 },2160 {2161 name: "c with nil http.Request.Context()",2162- getContextAndKey: func() (*Context, interface{}) {2162+ getContextAndKey: func() (*Context, any) {2163 c := &Context{}2164 c.Request, _ = http.NewRequest("POST", "/", nil)2165 return c, "key"2166 },21 unmodified linesmodified:context.go+44 added-44 removed
60 unmodified lines61 // This mutex protects Keys map.62 mu sync.RWMutex63 64 // Keys is a key/value pair exclusively for the context of each request.65- Keys map[string]interface{}65+ Keys map[string]any66 67 // Errors is a list of errors attached to all the handlers/middlewares who used this context.68 Errors errorMsgs69 44 unmodified lines114 cp.writermem.ResponseWriter = nil115 cp.Writer = &cp.writermem116 cp.index = abortIndex117 cp.handlers = nil118- cp.Keys = map[string]interface{}{}118+ cp.Keys = map[string]any{}119 for k, v := range c.Keys {120 cp.Keys[k] = v121 }122 paramCopy := make([]Param, len(cp.Params))70 unmodified lines193 194 // AbortWithStatusJSON calls `Abort()` and then `JSON` internally.195 // This method stops the chain, writes the status code and return a JSON body.196 // It also sets the Content-Type as "application/json".197-func (c *Context) AbortWithStatusJSON(code int, jsonObj interface{}) {197+func (c *Context) AbortWithStatusJSON(code int, jsonObj any) {198 c.Abort()199 c.JSON(code, jsonObj)200 }201 37 unmodified lines239 /************************************/240 241 // Set is used to store a new key/value pair exclusively for this context.242 // It also lazy initializes c.Keys if it was not used previously.243-func (c *Context) Set(key string, value interface{}) {243+func (c *Context) Set(key string, value any) {244 c.mu.Lock()245 if c.Keys == nil {246- c.Keys = make(map[string]interface{})246+ c.Keys = make(map[string]any)247 }248 249 c.Keys[key] = value250 c.mu.Unlock()251 }252 253 // Get returns the value for the given key, ie: (value, true).254 // If the value does not exist it returns (nil, false)255-func (c *Context) Get(key string) (value interface{}, exists bool) {255+func (c *Context) Get(key string) (value any, exists bool) {256 c.mu.RLock()257 value, exists = c.Keys[key]258 c.mu.RUnlock()259 return260 }261 262 // MustGet returns the value for the given key if it exists, otherwise it panics.263-func (c *Context) MustGet(key string) interface{} {263+func (c *Context) MustGet(key string) any {264 if value, exists := c.Get(key); exists {265 return value266 }267 panic("Key \"" + key + "\" does not exist")79 unmodified lines347 return348 }349 350 // GetStringMap returns the value associated with the key as a map of interfaces.351-func (c *Context) GetStringMap(key string) (sm map[string]interface{}) {351+func (c *Context) GetStringMap(key string) (sm map[string]any) {352 if val, ok := c.Get(key); ok && val != nil {353- sm, _ = val.(map[string]interface{})353+ sm, _ = val.(map[string]any)354 }355 return356 }357 248 unmodified lines606 // "application/xml" --> XML binding607 // It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input.608 // It decodes the json payload into the struct specified as a pointer.609 // It writes a 400 error and sets Content-Type header "text/plain" in the response if input is not valid.610-func (c *Context) Bind(obj interface{}) error {610+func (c *Context) Bind(obj any) error {611 b := binding.Default(c.Request.Method, c.ContentType())612 return c.MustBindWith(obj, b)613 }614 615 // BindJSON is a shortcut for c.MustBindWith(obj, binding.JSON).616-func (c *Context) BindJSON(obj interface{}) error {616+func (c *Context) BindJSON(obj any) error {617 return c.MustBindWith(obj, binding.JSON)618 }619 620 // BindXML is a shortcut for c.MustBindWith(obj, binding.BindXML).621-func (c *Context) BindXML(obj interface{}) error {621+func (c *Context) BindXML(obj any) error {622 return c.MustBindWith(obj, binding.XML)623 }624 625 // BindQuery is a shortcut for c.MustBindWith(obj, binding.Query).626-func (c *Context) BindQuery(obj interface{}) error {626+func (c *Context) BindQuery(obj any) error {627 return c.MustBindWith(obj, binding.Query)628 }629 630 // BindYAML is a shortcut for c.MustBindWith(obj, binding.YAML).631-func (c *Context) BindYAML(obj interface{}) error {631+func (c *Context) BindYAML(obj any) error {632 return c.MustBindWith(obj, binding.YAML)633 }634 635 // BindHeader is a shortcut for c.MustBindWith(obj, binding.Header).636-func (c *Context) BindHeader(obj interface{}) error {636+func (c *Context) BindHeader(obj any) error {637 return c.MustBindWith(obj, binding.Header)638 }639 640 // BindUri binds the passed struct pointer using binding.Uri.641 // It will abort the request with HTTP 400 if any error occurs.642-func (c *Context) BindUri(obj interface{}) error {642+func (c *Context) BindUri(obj any) error {643 if err := c.ShouldBindUri(obj); err != nil {644 c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) // nolint: errcheck645 return err646 }2 unmodified lines649 650 // MustBindWith binds the passed struct pointer using the specified binding engine.651 // It will abort the request with HTTP 400 if any error occurs.652 // See the binding package.653-func (c *Context) MustBindWith(obj interface{}, b binding.Binding) error {653+func (c *Context) MustBindWith(obj any, b binding.Binding) error {654 if err := c.ShouldBindWith(obj, b); err != nil {655 c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) // nolint: errcheck656 return err657 }6 unmodified lines664 // "application/xml" --> XML binding665 // It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input.666 // It decodes the json payload into the struct specified as a pointer.667 // Like c.Bind() but this method does not set the response status code to 400 or abort if input is not valid.668-func (c *Context) ShouldBind(obj interface{}) error {668+func (c *Context) ShouldBind(obj any) error {669 b := binding.Default(c.Request.Method, c.ContentType())670 return c.ShouldBindWith(obj, b)671 }672 673 // ShouldBindJSON is a shortcut for c.ShouldBindWith(obj, binding.JSON).674-func (c *Context) ShouldBindJSON(obj interface{}) error {674+func (c *Context) ShouldBindJSON(obj any) error {675 return c.ShouldBindWith(obj, binding.JSON)676 }677 678 // ShouldBindXML is a shortcut for c.ShouldBindWith(obj, binding.XML).679-func (c *Context) ShouldBindXML(obj interface{}) error {679+func (c *Context) ShouldBindXML(obj any) error {680 return c.ShouldBindWith(obj, binding.XML)681 }682 683 // ShouldBindQuery is a shortcut for c.ShouldBindWith(obj, binding.Query).684-func (c *Context) ShouldBindQuery(obj interface{}) error {684+func (c *Context) ShouldBindQuery(obj any) error {685 return c.ShouldBindWith(obj, binding.Query)686 }687 688 // ShouldBindYAML is a shortcut for c.ShouldBindWith(obj, binding.YAML).689-func (c *Context) ShouldBindYAML(obj interface{}) error {689+func (c *Context) ShouldBindYAML(obj any) error {690 return c.ShouldBindWith(obj, binding.YAML)691 }692 693 // ShouldBindHeader is a shortcut for c.ShouldBindWith(obj, binding.Header).694-func (c *Context) ShouldBindHeader(obj interface{}) error {694+func (c *Context) ShouldBindHeader(obj any) error {695 return c.ShouldBindWith(obj, binding.Header)696 }697 698 // ShouldBindUri binds the passed struct pointer using the specified binding engine.699-func (c *Context) ShouldBindUri(obj interface{}) error {699+func (c *Context) ShouldBindUri(obj any) error {700 m := make(map[string][]string)701 for _, v := range c.Params {702 m[v.Key] = []string{v.Value}703 }1 unmodified line705 }706 707 // ShouldBindWith binds the passed struct pointer using the specified binding engine.708 // See the binding package.709-func (c *Context) ShouldBindWith(obj interface{}, b binding.Binding) error {709+func (c *Context) ShouldBindWith(obj any, b binding.Binding) error {710 return b.Bind(c.Request, obj)711 }712 713 // ShouldBindBodyWith is similar with ShouldBindWith, but it stores the request714 // body into the context, and reuse when it is called again.715 //716 // NOTE: This method reads the body before binding. So you should use717 // ShouldBindWith for better performance if you need to call only once.718-func (c *Context) ShouldBindBodyWith(obj interface{}, bb binding.BindingBody) (err error) {718+func (c *Context) ShouldBindBodyWith(obj any, bb binding.BindingBody) (err error) {719 var body []byte720 if cb, ok := c.Get(BodyBytesKey); ok {721 if cbb, ok := cb.([]byte); ok {722 body = cbb176 unmodified lines899 900 // HTML renders the HTTP template specified by its file name.901 // It also updates the HTTP code and sets the Content-Type as "text/html".902 // See http://golang.org/doc/articles/wiki/903-func (c *Context) HTML(code int, name string, obj interface{}) {903+func (c *Context) HTML(code int, name string, obj any) {904 instance := c.engine.HTMLRender.Instance(name, obj)905 c.Render(code, instance)906 }907 908 // IndentedJSON serializes the given struct as pretty JSON (indented + endlines) into the response body.909 // It also sets the Content-Type as "application/json".910 // WARNING: we recommend using this only for development purposes since printing pretty JSON is911 // more CPU and bandwidth consuming. Use Context.JSON() instead.912-func (c *Context) IndentedJSON(code int, obj interface{}) {912+func (c *Context) IndentedJSON(code int, obj any) {913 c.Render(code, render.IndentedJSON{Data: obj})914 }915 916 // SecureJSON serializes the given struct as Secure JSON into the response body.917 // Default prepends "while(1)," to response body if the given struct is array values.918 // It also sets the Content-Type as "application/json".919-func (c *Context) SecureJSON(code int, obj interface{}) {919+func (c *Context) SecureJSON(code int, obj any) {920 c.Render(code, render.SecureJSON{Prefix: c.engine.secureJSONPrefix, Data: obj})921 }922 923 // JSONP serializes the given struct as JSON into the response body.924 // It adds padding to response body to request data from a server residing in a different domain than the client.925 // It also sets the Content-Type as "application/javascript".926-func (c *Context) JSONP(code int, obj interface{}) {926+func (c *Context) JSONP(code int, obj any) {927 callback := c.DefaultQuery("callback", "")928 if callback == "" {929 c.Render(code, render.JSON{Data: obj})930 return2 unmodified lines933 }934 935 // JSON serializes the given struct as JSON into the response body.936 // It also sets the Content-Type as "application/json".937-func (c *Context) JSON(code int, obj interface{}) {937+func (c *Context) JSON(code int, obj any) {938 c.Render(code, render.JSON{Data: obj})939 }940 941 // AsciiJSON serializes the given struct as JSON into the response body with unicode to ASCII string.942 // It also sets the Content-Type as "application/json".943-func (c *Context) AsciiJSON(code int, obj interface{}) {943+func (c *Context) AsciiJSON(code int, obj any) {944 c.Render(code, render.AsciiJSON{Data: obj})945 }946 947 // PureJSON serializes the given struct as JSON into the response body.948 // PureJSON, unlike JSON, does not replace special html characters with their unicode entities.949-func (c *Context) PureJSON(code int, obj interface{}) {949+func (c *Context) PureJSON(code int, obj any) {950 c.Render(code, render.PureJSON{Data: obj})951 }952 953 // XML serializes the given struct as XML into the response body.954 // It also sets the Content-Type as "application/xml".955-func (c *Context) XML(code int, obj interface{}) {955+func (c *Context) XML(code int, obj any) {956 c.Render(code, render.XML{Data: obj})957 }958 959 // YAML serializes the given struct as YAML into the response body.960-func (c *Context) YAML(code int, obj interface{}) {960+func (c *Context) YAML(code int, obj any) {961 c.Render(code, render.YAML{Data: obj})962 }963 964 // ProtoBuf serializes the given struct as ProtoBuf into the response body.965-func (c *Context) ProtoBuf(code int, obj interface{}) {965+func (c *Context) ProtoBuf(code int, obj any) {966 c.Render(code, render.ProtoBuf{Data: obj})967 }968 969 // String writes the given string into the response body.970-func (c *Context) String(code int, format string, values ...interface{}) {970+func (c *Context) String(code int, format string, values ...any) {971 c.Render(code, render.String{Format: format, Data: values})972 }973 974 // Redirect returns an HTTP redirect to the specific location.50 unmodified lines1025 http.ServeFile(c.Writer, c.Request, filepath)1026 }1027 1028 // SSEvent writes a Server-Sent Event into the body stream.1029-func (c *Context) SSEvent(name string, message interface{}) {1029+func (c *Context) SSEvent(name string, message any) {1030 c.Render(-1, sse.Event{1031 Event: name,1032 Data: message,1033 })25 unmodified lines1059 // Negotiate contains all negotiations data.1060 type Negotiate struct {1061 Offered []string1062 HTMLName string1063- HTMLData interface{}1064- JSONData interface{}1065- XMLData interface{}1066- YAMLData interface{}1067- Data interface{}1063+ HTMLData any1064+ JSONData any1065+ XMLData any1066+ YAMLData any1067+ Data any1068 }1069 1070 // Negotiate calls different Render according to acceptable Accept format.1071 func (c *Context) Negotiate(code int, config Negotiate) {85 unmodified lines1157 1158 // Value returns the value associated with this context for key, or nil1159 // if no value is associated with key. Successive calls to Value with1160 // the same key returns the same result.1161-func (c *Context) Value(key interface{}) interface{} {1161+func (c *Context) Value(key any) any {1162 if key == 0 {1163 return c.Request1164 }1165 if keyAsString, ok := key.(string); ok {9 unmodified linesmodified:debug.go+1 added-1 removed
45 unmodified lines46 debugPrint("Loaded HTML Templates (%d): \n%s\n", len(tmpl.Templates()), buf.String())47 }48 }49 50-func debugPrint(format string, values ...interface{}) {50+func debugPrint(format string, values ...any) {51 if IsDebugging() {52 if !strings.HasSuffix(format, "\n") {53 format += "\n"54 }47 unmodified linesmodified:deprecated.go+1 added-1 removed
10 unmodified lines11 )12 13 // BindWith binds the passed struct pointer using the specified binding engine.14 // See the binding package.15-func (c *Context) BindWith(obj interface{}, b binding.Binding) error {15+func (c *Context) BindWith(obj any, b binding.Binding) error {16 log.Println(`BindWith(\"interface{}, binding.Binding\") error is going to17 be deprecated, please check issue #662 and either use MustBindWith() if you18 want HTTP 400 to be automatically returned if any error occur, or use19 ShouldBindWith() if you need to manage the error.`)2 unmodified linesmodified:errors_test.go+1 added-1 removed
84 unmodified lines85 Meta: some data86 Error #03: third87 Meta: map[status:400]88 `, errs.String())89- assert.Equal(t, []interface{}{89+ assert.Equal(t, []any{90 H{"error": "first"},91 H{"error": "second", "meta": "some data"},92 H{"error": "third", "status": "400"},93 }, errs.JSON())35 unmodified linesmodified:errors.go+5 added-5 removed
32 unmodified lines33 // Error represents a error's specification.34 type Error struct {35 Err error36 Type ErrorType37- Meta interface{}37+ Meta any38 }39 40 type errorMsgs []*Error41 5 unmodified lines47 return msg48 }49 50 // SetMeta sets the error's meta data.51-func (msg *Error) SetMeta(data interface{}) *Error {51+func (msg *Error) SetMeta(data any) *Error {52 msg.Meta = data53 return msg54 }55 56 // JSON creates a properly formatted JSON57-func (msg *Error) JSON() interface{} {57+func (msg *Error) JSON() any {58 jsonData := H{}59 if msg.Meta != nil {60 value := reflect.ValueOf(msg.Meta)61 switch value.Kind() {76 unmodified lines138 }139 return errorStrings140 }141 142-func (a errorMsgs) JSON() interface{} {142+func (a errorMsgs) JSON() any {143 switch length := len(a); length {144 case 0:145 return nil146 case 1:147 return a.Last().JSON()148 default:149- jsonData := make([]interface{}, length)149+ jsonData := make([]any, length)150 for i, err := range a {151 jsonData[i] = err.JSON()152 }153 return jsonData21 unmodified linesmodified:gin_test.go+2 added-2 removed
41 unmodified lines42 router.GET("/test", func(c *Context) {43 c.HTML(http.StatusOK, "hello.tmpl", map[string]string{"name": "world"})44 })45 router.GET("/raw", func(c *Context) {46- c.HTML(http.StatusOK, "raw.tmpl", map[string]interface{}{46+ c.HTML(http.StatusOK, "raw.tmpl", map[string]any{47 "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),48 })49 })50 })415 unmodified lines466 compareFunc(t, router.allNoMethod[1], middleware1)467 compareFunc(t, router.allNoMethod[2], middleware0)468 }469 470-func compareFunc(t *testing.T, a, b interface{}) {470+func compareFunc(t *testing.T, a, b any) {471 sf1 := reflect.ValueOf(a)472 sf2 := reflect.ValueOf(b)473 if sf1.Pointer() != sf2.Pointer() {474 t.Error("different functions")224 unmodified linesmodified:gin.go+1 added-1 removed
196 unmodified lines197 trustedProxies: []string{"0.0.0.0/0"},198 trustedCIDRs: defaultTrustedCIDRs,199 }200 engine.RouterGroup.engine = engine201- engine.pool.New = func() interface{} {201+ engine.pool.New = func() any {202 return engine.allocateContext()203 }204 return engine205 }495 unmodified linesmodified:logger_test.go+1 added-1 removed
179 unmodified lines180 }181 182 func TestLoggerWithConfigFormatting(t *testing.T) {183 var gotParam LogFormatterParams184- var gotKeys map[string]interface{}184+ var gotKeys map[string]any185 buffer := new(bytes.Buffer)186 187 router := New()188 router.engine.trustedCIDRs, _ = router.engine.prepareTrustedCIDRs()246 unmodified linesmodified:logger.go+1 added-1 removed
73 unmodified lines74 isTerm bool75 // BodySize is the size of the Response Body76 BodySize int77 // Keys are the keys set on the request's context.78- Keys map[string]interface{}78+ Keys map[string]any79 }80 81 // StatusCodeColor is the ANSI color for appropriately logging http status code to a terminal.82 func (p *LogFormatterParams) StatusCodeColor() string {188 unmodified linesmodified:recovery_test.go+3 added-3 removed
146 unmodified lines147 func TestCustomRecoveryWithWriter(t *testing.T) {148 errBuffer := new(bytes.Buffer)149 buffer := new(bytes.Buffer)150 router := New()151- handleRecovery := func(c *Context, err interface{}) {151+ handleRecovery := func(c *Context, err any) {152 errBuffer.WriteString(err.(string))153 c.AbortWithStatus(http.StatusBadRequest)154 }155 router.Use(CustomRecoveryWithWriter(buffer, handleRecovery))26 unmodified lines182 errBuffer := new(bytes.Buffer)183 buffer := new(bytes.Buffer)184 router := New()185 DefaultErrorWriter = buffer186- handleRecovery := func(c *Context, err interface{}) {186+ handleRecovery := func(c *Context, err any) {187 errBuffer.WriteString(err.(string))188 c.AbortWithStatus(http.StatusBadRequest)189 }190 router.Use(CustomRecovery(handleRecovery))26 unmodified lines217 errBuffer := new(bytes.Buffer)218 buffer := new(bytes.Buffer)219 router := New()220 DefaultErrorWriter = buffer221- handleRecovery := func(c *Context, err interface{}) {221+ handleRecovery := func(c *Context, err any) {222 errBuffer.WriteString(err.(string))223 c.AbortWithStatus(http.StatusBadRequest)224 }225 router.Use(RecoveryWithWriter(DefaultErrorWriter, handleRecovery))24 unmodified linesmodified:recovery.go+2 added-2 removed
26 unmodified lines27 slash = []byte("/")28 )29 30 // RecoveryFunc defines the function passable to CustomRecovery.31-type RecoveryFunc func(c *Context, err interface{})31+type RecoveryFunc func(c *Context, err any)32 33 // Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.34 func Recovery() HandlerFunc {35 return RecoveryWithWriter(DefaultErrorWriter)65 unmodified lines101 c.Next()102 }103 }104 105-func defaultHandleRecovery(c *Context, err interface{}) {105+func defaultHandleRecovery(c *Context, err any) {106 c.AbortWithStatus(http.StatusInternalServerError)107 }108 109 // stack returns a nicely formatted stack frame, skipping skip frames.64 unmodified linesmodified:tree_test.go+1 added-1 removed
355 unmodified lines356 357 checkPriorities(t, tree)358 }359 360-func catchPanic(testFunc func()) (recv interface{}) {360+func catchPanic(testFunc func()) (recv any) {361 defer func() {362 recv = recover()363 }()364 559 unmodified linesmodified:utils.go+4 added-4 removed
17 unmodified lines18 // BindKey indicates a default bind key.19 const BindKey = "_gin-gonic/gin/bindkey"20 21 // Bind is a helper function for given interface object and returns a Gin middleware.22-func Bind(val interface{}) HandlerFunc {22+func Bind(val any) HandlerFunc {23 value := reflect.ValueOf(val)24 if value.Kind() == reflect.Ptr {25 panic(`Bind struct can not be a pointer. Example:26 Use: gin.Bind(Struct{}) instead of gin.Bind(&Struct{})23 unmodified lines50 }51 }52 53 // H is a shortcut for map[string]interface{}54-type H map[string]interface{}54+type H map[string]any55 56 // MarshalXML allows type H to be used with xml.Marshal.57 func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error {58 start.Name = xml.Name{30 unmodified lines89 }90 return content91 }92 93-func chooseData(custom, wildcard interface{}) interface{} {93+func chooseData(custom, wildcard any) any {94 if custom != nil {95 return custom96 }97 if wildcard != nil {22 unmodified lines120 }121 return str[len(str)-1]122 }123 124-func nameOfFunction(f interface{}) string {124+func nameOfFunction(f any) string {125 return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()126 }127 128 func joinPaths(absolutePath, relativePath string) string {36 unmodified lines