Skip to content
Myr

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

47 files+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.45//go:build !go1.186// +build !go1.1878package binding910type any = interface{}
modified:binding/binding_nomsgpack.go+6 added-6 removed
25 unmodified lines
26// data present in the request such as JSON request body, query parameters or27// the form POST.28type Binding interface {29 Name() string30 Bind(*http.Request, interface{}) error30 Bind(*http.Request, any) error31}3233// BindingBody adds BindBody method to Binding. BindBody is similar with Bind,34// but it reads the body from supplied bytes instead of req.Body.35type BindingBody interface {36 Binding37 BindBody([]byte, interface{}) error37 BindBody([]byte, any) error38}3940// BindingUri adds BindUri method to Binding. BindUri is similar with Bind,41// but it reads the Params.42type BindingUri interface {43 Name() string44 BindUri(map[string][]string, interface{}) error44 BindUri(map[string][]string, any) error45}4647// StructValidator is the minimal interface which needs to be implemented in48// order for it to be used as the validator engine for ensuring the correctness
4 unmodified lines
53 // 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) error5859 // Engine returns the underlying validator engine which powers the60 // StructValidator implementation.61 Engine() interface{}61 Engine() any62}6364// Validator is the default validator which implements the StructValidator65// interface. It uses https://github.com/go-playground/validator/tree/v10.6.1
37 unmodified lines
103 return Form104 }105}106107func validate(obj interface{}) error {107func validate(obj any) error {108 if Validator == nil {109 return nil110 }111 return Validator.ValidateStruct(obj)
1 unmodified line
modified:binding/binding_test.go+9 added-9 removed
59 unmodified lines
60 Bar string `msgpack:"bar" json:"bar" form:"bar,default=hello" xml:"bar" binding:"required"`61}6263type FooStructUseNumber struct {64 Foo interface{} `json:"foo" binding:"required"`64 Foo any `json:"foo" binding:"required"`65}6667type FooStructDisallowUnknownFields struct {68 Foo interface{} `json:"foo" binding:"required"`68 Foo any `json:"foo" binding:"required"`69}7071type FooBarStructForTimeType struct {72 TimeFoo time.Time `form:"time_foo" time_format:"2006-01-02" time_utc:"1" time_location:"Asia/Chongqing"`
19 unmodified lines
92 TimeFoo time.Time `form:"time_foo" time_format:"2006-01-02" time_location:"/asia/chongqing"`93}9495type FooStructForMapType struct {96 MapFoo map[string]interface{} `form:"map_foo"`96 MapFoo map[string]any `form:"map_foo"`97}9899type FooStructForIgnoreFormTag struct {100 Foo *string `form:"-"`
4 unmodified lines
105}106107type InvalidNameMapType struct {108 TestName struct {109 MapFoo map[string]interface{} `form:"map_foo"`109 MapFoo map[string]any `form:"map_foo"`110 }111}112113type FooStructForSliceType struct {
13 unmodified lines
127}128129type 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}133134type FooStructForBoolType struct {135 BoolFoo bool `form:"bool_foo"`
4 unmodified lines
140 PtrBar *string `form:"ptr_bar" binding:"required"`141}142143type FooStructForMapPtrType struct {144 PtrBar *map[string]interface{} `form:"ptr_bar"`144 PtrBar *map[string]any `form:"ptr_bar"`145}146147func TestBindingDefault(t *testing.T) {148 assert.Equal(t, Form, Default("GET", ""))
618 unmodified lines
767 req = requestWithBody("GET", "/", "")768 req.Header.Add("fail", `{fail:fail}`)769770 type failStruct struct {771 Fail map[string]interface{} `header:"fail"`771 Fail map[string]any `header:"fail"`772 }773774 err := h.Bind(req, &failStruct{})775 assert.Error(t, err)
12 unmodified lines
788 assert.NoError(t, b.BindUri(m, &tag))789 assert.Equal(t, "thinkerou", tag.Name)790791 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, &not))796 assert.Equal(t, map[string]interface{}(nil), not.Name)796 assert.Equal(t, map[string]any(nil), not.Name)797}798799func TestUriInnerBinding(t *testing.T) {800 type Tag struct {
559 unmodified lines
modified:binding/binding.go+6 added-6 removed
27 unmodified lines
28// data present in the request such as JSON request body, query parameters or29// the form POST.30type Binding interface {31 Name() string32 Bind(*http.Request, interface{}) error32 Bind(*http.Request, any) error33}3435// BindingBody adds BindBody method to Binding. BindBody is similar with Bind,36// but it reads the body from supplied bytes instead of req.Body.37type BindingBody interface {38 Binding39 BindBody([]byte, interface{}) error39 BindBody([]byte, any) error40}4142// BindingUri adds BindUri method to Binding. BindUri is similar with Bind,43// but it reads the Params.44type BindingUri interface {45 Name() string46 BindUri(map[string][]string, interface{}) error46 BindUri(map[string][]string, any) error47}4849// StructValidator is the minimal interface which needs to be implemented in50// order for it to be used as the validator engine for ensuring the correctness
5 unmodified lines
56 // 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) error6162 // Engine returns the underlying validator engine which powers the63 // StructValidator implementation.64 Engine() interface{}64 Engine() any65}6667// Validator is the default validator which implements the StructValidator68// interface. It uses https://github.com/go-playground/validator/tree/v10.6.1
40 unmodified lines
109 return Form110 }111}112113func validate(obj interface{}) error {113func validate(obj any) error {114 if Validator == nil {115 return nil116 }117 return Validator.ValidateStruct(obj)
1 unmodified line
modified:binding/default_validator_test.go+1 added-1 removed
52 unmodified lines
53 }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 lines
modified:binding/default_validator.go+3 added-3 removed
44 unmodified lines
4546var _ StructValidator = &defaultValidator{}4748// ValidateStruct receives any kind of type, but only performed struct or pointer to struct type.49func (v *defaultValidator) ValidateStruct(obj interface{}) error {49func (v *defaultValidator) ValidateStruct(obj any) error {50 if obj == nil {51 return nil52 }53
20 unmodified lines
74 }75}7677// validateStruct receives struct type78func (v *defaultValidator) validateStruct(obj interface{}) error {78func (v *defaultValidator) validateStruct(obj any) error {79 v.lazyinit()80 return v.validate.Struct(obj)81}8283// 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/v1087func (v *defaultValidator) Engine() interface{} {87func (v *defaultValidator) Engine() any {88 v.lazyinit()89 return v.validate90}91
6 unmodified lines
modified:binding/form_mapping_test.go+2 added-2 removed
16 unmodified lines
17 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 lines
modified:binding/form_mapping.go+7 added-7 removed
24 unmodified lines
25 // ErrConvertToMapString can not convert to map[string]string26 ErrConvertToMapString = errors.New("can not convert to map of strings")27)2829func mapURI(ptr interface{}, m map[string][]string) error {29func mapURI(ptr any, m map[string][]string) error {30 return mapFormByTag(ptr, m, "uri")31}3233func mapForm(ptr interface{}, form map[string][]string) error {33func mapForm(ptr any, form map[string][]string) error {34 return mapFormByTag(ptr, form, "form")35}3637func MapFormWithTag(ptr interface{}, form map[string][]string, tag string) error {37func MapFormWithTag(ptr any, form map[string][]string, tag string) error {38 return mapFormByTag(ptr, form, tag)39}4041var emptyField = reflect.StructField{}4243func mapFormByTag(ptr interface{}, form map[string][]string, tag string) error {43func 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 lines
72func (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}7576func mappingByPtr(ptr interface{}, setter setter, tag string) error {76func mappingByPtr(ptr any, setter setter, tag string) error {77 _, err := mapping(reflect.ValueOf(ptr), emptyField, setter, tag)78 return err79}80
294 unmodified lines
375 }376 return str[:idx], str[idx+len(sep):]377}378379func setFormMap(ptr interface{}, form map[string][]string) error {379func setFormMap(ptr any, form map[string][]string) error {380 el := reflect.TypeOf(ptr).Elem()381382 if el.Kind() == reflect.Slice {383 ptrMap, ok := ptr.(map[string][]string)
20 unmodified lines
modified:binding/form.go+3 added-3 removed
17 unmodified lines
18func (formBinding) Name() string {19 return "form"20}2122func (formBinding) Bind(req *http.Request, obj interface{}) error {22func (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 lines
35func (formPostBinding) Name() string {36 return "form-urlencoded"37}3839func (formPostBinding) Bind(req *http.Request, obj interface{}) error {39func (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 lines
49func (formMultipartBinding) Name() string {50 return "multipart/form-data"51}5253func (formMultipartBinding) Bind(req *http.Request, obj interface{}) error {53func (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 lines
modified:binding/header.go+2 added-2 removed
10 unmodified lines
11func (headerBinding) Name() string {12 return "header"13}1415func (headerBinding) Bind(req *http.Request, obj interface{}) error {15func (headerBinding) Bind(req *http.Request, obj any) error {1617 if err := mapHeader(obj, req.Header); err != nil {18 return err19 }2021 return validate(obj)22}2324func mapHeader(ptr interface{}, h map[string][]string) error {24func mapHeader(ptr any, h map[string][]string) error {25 return mappingByPtr(ptr, headerSource(h), "header")26}2728type headerSource map[string][]string
6 unmodified lines
modified:binding/json.go+3 added-3 removed
28 unmodified lines
29func (jsonBinding) Name() string {30 return "json"31}3233func (jsonBinding) Bind(req *http.Request, obj interface{}) error {33func (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}3940func (jsonBinding) BindBody(body []byte, obj interface{}) error {40func (jsonBinding) BindBody(body []byte, obj any) error {41 return decodeJSON(bytes.NewReader(body), obj)42}4344func decodeJSON(r io.Reader, obj interface{}) error {44func decodeJSON(r io.Reader, obj any) error {45 decoder := json.NewDecoder(r)46 if EnableDecoderUseNumber {47 decoder.UseNumber()48 }
8 unmodified lines
modified:binding/msgpack_test.go+1 added-1 removed
24 unmodified lines
25 require.NoError(t, err)26 assert.Equal(t, "FOO", s.Foo)27}2829func msgpackBody(t *testing.T, obj interface{}) []byte {29func 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 lines
modified:binding/msgpack.go+3 added-3 removed
19 unmodified lines
20func (msgpackBinding) Name() string {21 return "msgpack"22}2324func (msgpackBinding) Bind(req *http.Request, obj interface{}) error {24func (msgpackBinding) Bind(req *http.Request, obj any) error {25 return decodeMsgPack(req.Body, obj)26}2728func (msgpackBinding) BindBody(body []byte, obj interface{}) error {28func (msgpackBinding) BindBody(body []byte, obj any) error {29 return decodeMsgPack(bytes.NewReader(body), obj)30}3132func decodeMsgPack(r io.Reader, obj interface{}) error {32func 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 lines
modified:binding/multipart_form_mapping_test.go+1 added-1 removed
74 unmodified lines
75 }7677 for _, tt := range []struct {78 name string79 s interface{}79 s any80 }{81 {"wrong type", &struct {82 Files int `form:"file"`83 }{}},
55 unmodified lines
modified:binding/protobuf.go+2 added-2 removed
16 unmodified lines
17func (protobufBinding) Name() string {18 return "protobuf"19}2021func (b protobufBinding) Bind(req *http.Request, obj interface{}) error {21func (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}2829func (protobufBinding) BindBody(body []byte, obj interface{}) error {29func (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 lines
modified:binding/query.go+1 added-1 removed
10 unmodified lines
11func (queryBinding) Name() string {12 return "query"13}1415func (queryBinding) Bind(req *http.Request, obj interface{}) error {15func (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 lines
modified:binding/uri.go+1 added-1 removed
8 unmodified lines
9func (uriBinding) Name() string {10 return "uri"11}1213func (uriBinding) BindUri(m map[string][]string, obj interface{}) error {13func (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 line
modified:binding/validate_test.go+2 added-2 removed
57 unmodified lines
58 StructPointerSlice []*substructNoValidation59 StructSlice []substructNoValidation60 InterfaceSlice []testInterface6162 UniversalInterface interface{}62 UniversalInterface any63 CustomInterface testInterface6465 FloatMap map[string]float3266 StructMap mapNoValidationSub
101 unmodified lines
168169 //assert.Equal(t, origin, test)170}171172type Object map[string]interface{}172type Object map[string]any173174func TestValidatePrimitives(t *testing.T) {175 obj := Object{"foo": "bar", "bar": 1}176 assert.NoError(t, validate(obj))
52 unmodified lines
modified:binding/xml.go+3 added-3 removed
15 unmodified lines
16func (xmlBinding) Name() string {17 return "xml"18}1920func (xmlBinding) Bind(req *http.Request, obj interface{}) error {20func (xmlBinding) Bind(req *http.Request, obj any) error {21 return decodeXML(req.Body, obj)22}2324func (xmlBinding) BindBody(body []byte, obj interface{}) error {24func (xmlBinding) BindBody(body []byte, obj any) error {25 return decodeXML(bytes.NewReader(body), obj)26}27func decodeXML(r io.Reader, obj interface{}) error {27func 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 lines
modified:binding/yaml.go+3 added-3 removed
16 unmodified lines
17func (yamlBinding) Name() string {18 return "yaml"19}2021func (yamlBinding) Bind(req *http.Request, obj interface{}) error {21func (yamlBinding) Bind(req *http.Request, obj any) error {22 return decodeYAML(req.Body, obj)23}2425func (yamlBinding) BindBody(body []byte, obj interface{}) error {25func (yamlBinding) BindBody(body []byte, obj any) error {26 return decodeYAML(bytes.NewReader(body), obj)27}2829func decodeYAML(r io.Reader, obj interface{}) error {29func 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 lines
added: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.45//go:build !go1.186// +build !go1.1878package render910type any = interface{}
modified:render/html.go+4 added-4 removed
18 unmodified lines
1920// HTMLRender interface is to be implemented by HTMLProduction and HTMLDebug.21type HTMLRender interface {22 // Instance returns an HTML instance.23 Instance(string, interface{}) Render23 Instance(string, any) Render24}2526// HTMLProduction contains template reference and its delims.27type HTMLProduction struct {
12 unmodified lines
40// HTML contains template reference and its name with given interface object.41type HTML struct {42 Template *template.Template43 Name string44 Data interface{}44 Data any45}4647var htmlContentType = []string{"text/html; charset=utf-8"}4849// Instance (HTMLProduction) returns an HTML instance which it realizes Render interface.50func (r HTMLProduction) Instance(name string, data interface{}) Render {50func (r HTMLProduction) Instance(name string, data any) Render {51 return HTML{52 Template: r.Template,53 Name: name,54 Data: data,55 }56}5758// Instance (HTMLDebug) returns an HTML instance which it realizes Render interface.59func (r HTMLDebug) Instance(name string, data interface{}) Render {59func (r HTMLDebug) Instance(name string, data any) Render {60 return HTML{61 Template: r.loadTemplate(),62 Name: name,63 Data: data,
29 unmodified lines
modified:render/json.go+7 added-7 removed
14 unmodified lines
15)1617// JSON contains the given interface object.18type JSON struct {19 Data interface{}19 Data any20}2122// IndentedJSON contains the given interface object.23type IndentedJSON struct {24 Data interface{}24 Data any25}2627// SecureJSON contains the given interface object and its prefix.28type SecureJSON struct {29 Prefix string30 Data interface{}30 Data any31}3233// JsonpJSON contains the given interface object its callback.34type JsonpJSON struct {35 Callback string36 Data interface{}36 Data any37}3839// AsciiJSON contains the given interface object.40type AsciiJSON struct {41 Data interface{}41 Data any42}4344// PureJSON contains the given interface object.45type PureJSON struct {46 Data interface{}46 Data any47}4849var (50 jsonContentType = []string{"application/json; charset=utf-8"}
14 unmodified lines
65 writeContentType(w, jsonContentType)66}6768// WriteJSON marshals the given interface object and writes it with custom ContentType.69func WriteJSON(w http.ResponseWriter, obj interface{}) error {69func WriteJSON(w http.ResponseWriter, obj any) error {70 writeContentType(w, jsonContentType)71 jsonBytes, err := json.Marshal(obj)72 if err != nil {73 return err
120 unmodified lines
modified:render/msgpack.go+2 added-2 removed
19 unmodified lines
20)2122// MsgPack contains the given interface object.23type MsgPack struct {24 Data interface{}24 Data any25}2627var msgpackContentType = []string{"application/msgpack; charset=utf-8"}28
7 unmodified lines
36 return WriteMsgPack(w, r.Data)37}3839// WriteMsgPack writes MsgPack ContentType and encodes the given interface object.40func WriteMsgPack(w http.ResponseWriter, obj interface{}) error {40func 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 lines
11)1213// ProtoBuf contains the given interface object.14type ProtoBuf struct {15 Data interface{}15 Data any16}1718var protobufContentType = []string{"application/x-protobuf"}19
17 unmodified lines
modified:render/render_msgpack_test.go+1 added-1 removed
19 unmodified lines
20// test errors2122func TestRenderMsgPack(t *testing.T) {23 w := httptest.NewRecorder()24 data := map[string]interface{}{24 data := map[string]any{25 "foo": "bar",26 }2728 (MsgPack{data}).WriteContentType(w)
16 unmodified lines
modified:render/render_test.go+18 added-18 removed
22 unmodified lines
23// test errors2425func 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 lines
48}4950func 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 lines
71}7273func TestRenderSecureJSON(t *testing.T) {74 w1 := httptest.NewRecorder()75 data := map[string]interface{}{75 data := map[string]any{76 "foo": "bar",77 }7879 (SecureJSON{"while(1);", data}).WriteContentType(w1)
5 unmodified lines
85 assert.Equal(t, "{\"foo\":\"bar\"}", w1.Body.String())86 assert.Equal(t, "application/json; charset=utf-8", w1.Header().Get("Content-Type"))8788 w2 := httptest.NewRecorder()89 datas := []map[string]interface{}{{89 datas := []map[string]any{{90 "foo": "bar",91 }, {92 "bar": "foo",93 }}
14 unmodified lines
108}109110func TestRenderJsonpJSON(t *testing.T) {111 w1 := httptest.NewRecorder()112 data := map[string]interface{}{112 data := map[string]any{113 "foo": "bar",114 }115116 (JsonpJSON{"x", data}).WriteContentType(w1)
5 unmodified lines
122 assert.Equal(t, "x({\"foo\":\"bar\"});", w1.Body.String())123 assert.Equal(t, "application/javascript; charset=utf-8", w1.Header().Get("Content-Type"))124125 w2 := httptest.NewRecorder()126 datas := []map[string]interface{}{{126 datas := []map[string]any{{127 "foo": "bar",128 }, {129 "bar": "foo",130 }}
5 unmodified lines
136}137138func 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 lines
160}161162func 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 lines
189}190191func 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 line
199 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}202203type xmlmap map[string]interface{}203type xmlmap map[string]any204205// Allows type H to be used with xml.Marshal206func (h xmlmap) MarshalXML(e *xml.Encoder, start xml.StartElement) error {207 start.Name = xml.Name{
35 unmodified lines
243244type fail struct{}245246// Hook MarshalYAML247func (ft *fail) MarshalYAML() (interface{}, error) {247func (ft *fail) MarshalYAML() (any, error) {248 return nil, errors.New("fail")249}250251func TestRenderYAMLFail(t *testing.T) {
105 unmodified lines
357 w := httptest.NewRecorder()358359 (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"))364365 err := (String{366 Format: "hola %s %d",367 Data: []interface{}{"manu", 2},367 Data: []any{"manu", 2},368 }).Render(w)369370 assert.NoError(t, err)371 assert.Equal(t, "hola manu 2", w.Body.String())
4 unmodified lines
376 w := httptest.NewRecorder()377378 err := (String{379 Format: "hola %s %d",380 Data: []interface{}{},380 Data: []any{},381 }).Render(w)382383 assert.NoError(t, err)384 assert.Equal(t, "hola %s %d", w.Body.String())
4 unmodified lines
389 w := httptest.NewRecorder()390 templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))391392 htmlRender := HTMLProduction{Template: templ}393 instance := htmlRender.Instance("t", map[string]interface{}{393 instance := htmlRender.Instance("t", map[string]any{394 "name": "alexandernyquist",395 })396397 err := instance.Render(w)
7 unmodified lines
405 w := httptest.NewRecorder()406 templ := template.Must(template.New("").Parse(`Hello {{.name}}`))407408 htmlRender := HTMLProduction{Template: templ}409 instance := htmlRender.Instance("", map[string]interface{}{409 instance := htmlRender.Instance("", map[string]any{410 "name": "alexandernyquist",411 })412413 err := instance.Render(w)
10 unmodified lines
424 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 })431432 err := instance.Render(w)
10 unmodified lines
443 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 })450451 err := instance.Render(w)
61 unmodified lines
modified:render/text.go+2 added-2 removed
12 unmodified lines
1314// String contains the given interface object slice and its format.15type String struct {16 Format string17 Data []interface{}17 Data []any18}1920var plainContentType = []string{"text/plain; charset=utf-8"}21
7 unmodified lines
29 writeContentType(w, plainContentType)30}3132// WriteString writes data according to its format and write custom ContentType.33func WriteString(w http.ResponseWriter, format string, data []interface{}) (err error) {33func 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 return
4 unmodified lines
modified:render/xml.go+1 added-1 removed
9 unmodified lines
10)1112// XML contains the given interface object.13type XML struct {14 Data interface{}14 Data any15}1617var xmlContentType = []string{"application/xml; charset=utf-8"}18
10 unmodified lines
modified:render/yaml.go+1 added-1 removed
10 unmodified lines
11)1213// YAML contains the given interface object.14type YAML struct {15 Data interface{}15 Data any16}1718var yamlContentType = []string{"application/x-yaml; charset=utf-8"}19
17 unmodified lines
added: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.45//go:build !go1.186// +build !go1.1878package protoexample910type any = interface{}
modified:testdata/protoexample/test.pb.go+3 added-3 removed
229 unmodified lines
230}231232var file_test_proto_enumTypes = make([]protoimpl.EnumInfo, 1)233var file_test_proto_msgTypes = make([]protoimpl.MessageInfo, 2)234var file_test_proto_goTypes = []interface{}{234var 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 lines
250 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 lines
262 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 lines
added: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.45//go:build !go1.186// +build !go1.1878package gin910type any = interface{}
modified:context_test.go+8 added-8 removed
210 unmodified lines
211 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)217218 assert.Exactly(t, c.MustGet("string").(string), "this is a string")219 assert.Exactly(t, c.MustGet("int32").(int32), int32(-42))
66 unmodified lines
286}287288func 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)293294 assert.Equal(t, m, c.GetStringMap("map"))
1829 unmodified lines
21242125func 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 lines
2140 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 line
2150 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 lines
modified:context.go+44 added-44 removed
60 unmodified lines
61 // This mutex protects Keys map.62 mu sync.RWMutex6364 // Keys is a key/value pair exclusively for the context of each request.65 Keys map[string]interface{}65 Keys map[string]any6667 // Errors is a list of errors attached to all the handlers/middlewares who used this context.68 Errors errorMsgs69
44 unmodified lines
114 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 lines
193194// 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".197func (c *Context) AbortWithStatusJSON(code int, jsonObj interface{}) {197func (c *Context) AbortWithStatusJSON(code int, jsonObj any) {198 c.Abort()199 c.JSON(code, jsonObj)200}201
37 unmodified lines
239/************************************/240241// 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.243func (c *Context) Set(key string, value interface{}) {243func (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 }248249 c.Keys[key] = value250 c.mu.Unlock()251}252253// Get returns the value for the given key, ie: (value, true).254// If the value does not exist it returns (nil, false)255func (c *Context) Get(key string) (value interface{}, exists bool) {255func (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}261262// MustGet returns the value for the given key if it exists, otherwise it panics.263func (c *Context) MustGet(key string) interface{} {263func (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 lines
347 return348}349350// GetStringMap returns the value associated with the key as a map of interfaces.351func (c *Context) GetStringMap(key string) (sm map[string]interface{}) {351func (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 lines
606// "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.610func (c *Context) Bind(obj interface{}) error {610func (c *Context) Bind(obj any) error {611 b := binding.Default(c.Request.Method, c.ContentType())612 return c.MustBindWith(obj, b)613}614615// BindJSON is a shortcut for c.MustBindWith(obj, binding.JSON).616func (c *Context) BindJSON(obj interface{}) error {616func (c *Context) BindJSON(obj any) error {617 return c.MustBindWith(obj, binding.JSON)618}619620// BindXML is a shortcut for c.MustBindWith(obj, binding.BindXML).621func (c *Context) BindXML(obj interface{}) error {621func (c *Context) BindXML(obj any) error {622 return c.MustBindWith(obj, binding.XML)623}624625// BindQuery is a shortcut for c.MustBindWith(obj, binding.Query).626func (c *Context) BindQuery(obj interface{}) error {626func (c *Context) BindQuery(obj any) error {627 return c.MustBindWith(obj, binding.Query)628}629630// BindYAML is a shortcut for c.MustBindWith(obj, binding.YAML).631func (c *Context) BindYAML(obj interface{}) error {631func (c *Context) BindYAML(obj any) error {632 return c.MustBindWith(obj, binding.YAML)633}634635// BindHeader is a shortcut for c.MustBindWith(obj, binding.Header).636func (c *Context) BindHeader(obj interface{}) error {636func (c *Context) BindHeader(obj any) error {637 return c.MustBindWith(obj, binding.Header)638}639640// BindUri binds the passed struct pointer using binding.Uri.641// It will abort the request with HTTP 400 if any error occurs.642func (c *Context) BindUri(obj interface{}) error {642func (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 lines
649650// 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.653func (c *Context) MustBindWith(obj interface{}, b binding.Binding) error {653func (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 lines
664// "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.668func (c *Context) ShouldBind(obj interface{}) error {668func (c *Context) ShouldBind(obj any) error {669 b := binding.Default(c.Request.Method, c.ContentType())670 return c.ShouldBindWith(obj, b)671}672673// ShouldBindJSON is a shortcut for c.ShouldBindWith(obj, binding.JSON).674func (c *Context) ShouldBindJSON(obj interface{}) error {674func (c *Context) ShouldBindJSON(obj any) error {675 return c.ShouldBindWith(obj, binding.JSON)676}677678// ShouldBindXML is a shortcut for c.ShouldBindWith(obj, binding.XML).679func (c *Context) ShouldBindXML(obj interface{}) error {679func (c *Context) ShouldBindXML(obj any) error {680 return c.ShouldBindWith(obj, binding.XML)681}682683// ShouldBindQuery is a shortcut for c.ShouldBindWith(obj, binding.Query).684func (c *Context) ShouldBindQuery(obj interface{}) error {684func (c *Context) ShouldBindQuery(obj any) error {685 return c.ShouldBindWith(obj, binding.Query)686}687688// ShouldBindYAML is a shortcut for c.ShouldBindWith(obj, binding.YAML).689func (c *Context) ShouldBindYAML(obj interface{}) error {689func (c *Context) ShouldBindYAML(obj any) error {690 return c.ShouldBindWith(obj, binding.YAML)691}692693// ShouldBindHeader is a shortcut for c.ShouldBindWith(obj, binding.Header).694func (c *Context) ShouldBindHeader(obj interface{}) error {694func (c *Context) ShouldBindHeader(obj any) error {695 return c.ShouldBindWith(obj, binding.Header)696}697698// ShouldBindUri binds the passed struct pointer using the specified binding engine.699func (c *Context) ShouldBindUri(obj interface{}) error {699func (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 line
705}706707// ShouldBindWith binds the passed struct pointer using the specified binding engine.708// See the binding package.709func (c *Context) ShouldBindWith(obj interface{}, b binding.Binding) error {709func (c *Context) ShouldBindWith(obj any, b binding.Binding) error {710 return b.Bind(c.Request, obj)711}712713// 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.718func (c *Context) ShouldBindBodyWith(obj interface{}, bb binding.BindingBody) (err error) {718func (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 = cbb
176 unmodified lines
899900// 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/903func (c *Context) HTML(code int, name string, obj interface{}) {903func (c *Context) HTML(code int, name string, obj any) {904 instance := c.engine.HTMLRender.Instance(name, obj)905 c.Render(code, instance)906}907908// 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.912func (c *Context) IndentedJSON(code int, obj interface{}) {912func (c *Context) IndentedJSON(code int, obj any) {913 c.Render(code, render.IndentedJSON{Data: obj})914}915916// 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".919func (c *Context) SecureJSON(code int, obj interface{}) {919func (c *Context) SecureJSON(code int, obj any) {920 c.Render(code, render.SecureJSON{Prefix: c.engine.secureJSONPrefix, Data: obj})921}922923// 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".926func (c *Context) JSONP(code int, obj interface{}) {926func (c *Context) JSONP(code int, obj any) {927 callback := c.DefaultQuery("callback", "")928 if callback == "" {929 c.Render(code, render.JSON{Data: obj})930 return
2 unmodified lines
933}934935// JSON serializes the given struct as JSON into the response body.936// It also sets the Content-Type as "application/json".937func (c *Context) JSON(code int, obj interface{}) {937func (c *Context) JSON(code int, obj any) {938 c.Render(code, render.JSON{Data: obj})939}940941// 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".943func (c *Context) AsciiJSON(code int, obj interface{}) {943func (c *Context) AsciiJSON(code int, obj any) {944 c.Render(code, render.AsciiJSON{Data: obj})945}946947// 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.949func (c *Context) PureJSON(code int, obj interface{}) {949func (c *Context) PureJSON(code int, obj any) {950 c.Render(code, render.PureJSON{Data: obj})951}952953// XML serializes the given struct as XML into the response body.954// It also sets the Content-Type as "application/xml".955func (c *Context) XML(code int, obj interface{}) {955func (c *Context) XML(code int, obj any) {956 c.Render(code, render.XML{Data: obj})957}958959// YAML serializes the given struct as YAML into the response body.960func (c *Context) YAML(code int, obj interface{}) {960func (c *Context) YAML(code int, obj any) {961 c.Render(code, render.YAML{Data: obj})962}963964// ProtoBuf serializes the given struct as ProtoBuf into the response body.965func (c *Context) ProtoBuf(code int, obj interface{}) {965func (c *Context) ProtoBuf(code int, obj any) {966 c.Render(code, render.ProtoBuf{Data: obj})967}968969// String writes the given string into the response body.970func (c *Context) String(code int, format string, values ...interface{}) {970func (c *Context) String(code int, format string, values ...any) {971 c.Render(code, render.String{Format: format, Data: values})972}973974// Redirect returns an HTTP redirect to the specific location.
50 unmodified lines
1025 http.ServeFile(c.Writer, c.Request, filepath)1026}10271028// SSEvent writes a Server-Sent Event into the body stream.1029func (c *Context) SSEvent(name string, message interface{}) {1029func (c *Context) SSEvent(name string, message any) {1030 c.Render(-1, sse.Event{1031 Event: name,1032 Data: message,1033 })
25 unmodified lines
1059// Negotiate contains all negotiations data.1060type 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}10691070// Negotiate calls different Render according to acceptable Accept format.1071func (c *Context) Negotiate(code int, config Negotiate) {
85 unmodified lines
11571158// 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.1161func (c *Context) Value(key interface{}) interface{} {1161func (c *Context) Value(key any) any {1162 if key == 0 {1163 return c.Request1164 }1165 if keyAsString, ok := key.(string); ok {
9 unmodified lines
modified:debug.go+1 added-1 removed
45 unmodified lines
46 debugPrint("Loaded HTML Templates (%d): \n%s\n", len(tmpl.Templates()), buf.String())47 }48}4950func debugPrint(format string, values ...interface{}) {50func debugPrint(format string, values ...any) {51 if IsDebugging() {52 if !strings.HasSuffix(format, "\n") {53 format += "\n"54 }
47 unmodified lines
modified:deprecated.go+1 added-1 removed
10 unmodified lines
11)1213// BindWith binds the passed struct pointer using the specified binding engine.14// See the binding package.15func (c *Context) BindWith(obj interface{}, b binding.Binding) error {15func (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 lines
modified:errors_test.go+1 added-1 removed
84 unmodified lines
85 Meta: some data86Error #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 lines
modified:errors.go+5 added-5 removed
32 unmodified lines
33// Error represents a error's specification.34type Error struct {35 Err error36 Type ErrorType37 Meta interface{}37 Meta any38}3940type errorMsgs []*Error41
5 unmodified lines
47 return msg48}4950// SetMeta sets the error's meta data.51func (msg *Error) SetMeta(data interface{}) *Error {51func (msg *Error) SetMeta(data any) *Error {52 msg.Meta = data53 return msg54}5556// JSON creates a properly formatted JSON57func (msg *Error) JSON() interface{} {57func (msg *Error) JSON() any {58 jsonData := H{}59 if msg.Meta != nil {60 value := reflect.ValueOf(msg.Meta)61 switch value.Kind() {
76 unmodified lines
138 }139 return errorStrings140}141142func (a errorMsgs) JSON() interface{} {142func (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 jsonData
21 unmodified lines
modified:gin_test.go+2 added-2 removed
41 unmodified lines
42 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 lines
466 compareFunc(t, router.allNoMethod[1], middleware1)467 compareFunc(t, router.allNoMethod[2], middleware0)468}469470func compareFunc(t *testing.T, a, b interface{}) {470func 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 lines
modified:gin.go+1 added-1 removed
196 unmodified lines
197 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 lines
modified:logger_test.go+1 added-1 removed
179 unmodified lines
180}181182func TestLoggerWithConfigFormatting(t *testing.T) {183 var gotParam LogFormatterParams184 var gotKeys map[string]interface{}184 var gotKeys map[string]any185 buffer := new(bytes.Buffer)186187 router := New()188 router.engine.trustedCIDRs, _ = router.engine.prepareTrustedCIDRs()
246 unmodified lines
modified:logger.go+1 added-1 removed
73 unmodified lines
74 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}8081// StatusCodeColor is the ANSI color for appropriately logging http status code to a terminal.82func (p *LogFormatterParams) StatusCodeColor() string {
188 unmodified lines
modified:recovery_test.go+3 added-3 removed
146 unmodified lines
147func 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 lines
182 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 lines
217 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 lines
modified:recovery.go+2 added-2 removed
26 unmodified lines
27 slash = []byte("/")28)2930// RecoveryFunc defines the function passable to CustomRecovery.31type RecoveryFunc func(c *Context, err interface{})31type RecoveryFunc func(c *Context, err any)3233// Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.34func Recovery() HandlerFunc {35 return RecoveryWithWriter(DefaultErrorWriter)
65 unmodified lines
101 c.Next()102 }103}104105func defaultHandleRecovery(c *Context, err interface{}) {105func defaultHandleRecovery(c *Context, err any) {106 c.AbortWithStatus(http.StatusInternalServerError)107}108109// stack returns a nicely formatted stack frame, skipping skip frames.
64 unmodified lines
modified:tree_test.go+1 added-1 removed
355 unmodified lines
356357 checkPriorities(t, tree)358}359360func catchPanic(testFunc func()) (recv interface{}) {360func catchPanic(testFunc func()) (recv any) {361 defer func() {362 recv = recover()363 }()364
559 unmodified lines
modified:utils.go+4 added-4 removed
17 unmodified lines
18// BindKey indicates a default bind key.19const BindKey = "_gin-gonic/gin/bindkey"2021// Bind is a helper function for given interface object and returns a Gin middleware.22func Bind(val interface{}) HandlerFunc {22func 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 lines
50 }51}5253// H is a shortcut for map[string]interface{}54type H map[string]interface{}54type H map[string]any5556// MarshalXML allows type H to be used with xml.Marshal.57func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error {58 start.Name = xml.Name{
30 unmodified lines
89 }90 return content91}9293func chooseData(custom, wildcard interface{}) interface{} {93func chooseData(custom, wildcard any) any {94 if custom != nil {95 return custom96 }97 if wildcard != nil {
22 unmodified lines
120 }121 return str[len(str)-1]122}123124func nameOfFunction(f interface{}) string {124func nameOfFunction(f any) string {125 return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()126}127128func joinPaths(absolutePath, relativePath string) string {
36 unmodified lines