diff --git a/api/metadata/server.go b/api/metadata/server.go index 3b9d7c34f..201007422 100644 --- a/api/metadata/server.go +++ b/api/metadata/server.go @@ -139,7 +139,7 @@ func (s *Server) GetServiceDesc(_ context.Context, in *GetServiceDescRequest) (* // For SupportPackageIsVersion4, m is the name of the proto file, we // call proto.FileDescriptor to get the byte slice. // For SupportPackageIsVersion3, m is a byte slice itself. -func parseMetadata(meta interface{}) (*dpb.FileDescriptorProto, error) { +func parseMetadata(meta any) (*dpb.FileDescriptorProto, error) { // Check if meta is the file name. if fileNameForMeta, ok := meta.(string); ok { return fileDescriptorProto(fileNameForMeta) diff --git a/config/config.go b/config/config.go index 1160fb1e3..2b398c95b 100644 --- a/config/config.go +++ b/config/config.go @@ -27,7 +27,7 @@ type Observer func(string, Value) // Config is a config interface. type Config interface { Load() error - Scan(v interface{}) error + Scan(v any) error Value(key string) Value Watch(key string, o Observer) error Close() error @@ -46,7 +46,7 @@ func New(opts ...Option) Config { o := options{ decoder: defaultDecoder, resolver: defaultResolver, - merge: func(dst, src interface{}) error { + merge: func(dst, src any) error { return mergo.Map(dst, src, mergo.WithOverride) }, } @@ -79,7 +79,7 @@ func (c *config) watch(w Watcher) { log.Errorf("failed to resolve next config: %v", err) continue } - c.cached.Range(func(key, value interface{}) bool { + c.cached.Range(func(key, value any) bool { k := key.(string) v := value.(Value) if n, ok := c.reader.Value(k); ok && reflect.TypeOf(n.Load()) == reflect.TypeOf(v.Load()) && !reflect.DeepEqual(n.Load(), v.Load()) { @@ -132,7 +132,7 @@ func (c *config) Value(key string) Value { return &errValue{err: ErrNotFound} } -func (c *config) Scan(v interface{}) error { +func (c *config) Scan(v any) error { data, err := c.reader.Source() if err != nil { return err diff --git a/config/config_test.go b/config/config_test.go index ec7fc9f7f..094757562 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -133,7 +133,7 @@ func TestConfig(t *testing.T) { sources: []Source{jSource}, decoder: defaultDecoder, resolver: defaultResolver, - merge: func(dst, src interface{}) error { + merge: func(dst, src any) error { return mergo.Map(dst, src, mergo.WithOverride) }, } diff --git a/config/env/env_test.go b/config/env/env_test.go index 72fcff31d..ecb736bc5 100644 --- a/config/env/env_test.go +++ b/config/env/env_test.go @@ -68,7 +68,7 @@ func TestEnvWithPrefix(t *testing.T) { tests := []struct { name string path string - expect interface{} + expect any }{ { name: "test $KEY", @@ -88,8 +88,8 @@ func TestEnvWithPrefix(t *testing.T) { { name: "test ${KEY} in array", path: "foo", - expect: []interface{}{ - map[string]interface{}{ + expect: []any{ + map[string]any{ "name": "Tom", "age": "20", }, @@ -102,7 +102,7 @@ func TestEnvWithPrefix(t *testing.T) { var err error v := c.Value(test.path) if v.Load() != nil { - var actual interface{} + var actual any switch test.expect.(type) { case int: if actual, err = v.Int(); err == nil { @@ -182,7 +182,7 @@ func TestEnvWithoutPrefix(t *testing.T) { tests := []struct { name string path string - expect interface{} + expect any }{ { name: "test $KEY", @@ -202,8 +202,8 @@ func TestEnvWithoutPrefix(t *testing.T) { { name: "test ${KEY} in array", path: "foo", - expect: []interface{}{ - map[string]interface{}{ + expect: []any{ + map[string]any{ "name": "Tom", "age": "20", }, @@ -216,7 +216,7 @@ func TestEnvWithoutPrefix(t *testing.T) { var err error v := c.Value(test.path) if v.Load() != nil { - var actual interface{} + var actual any switch test.expect.(type) { case int: if actual, err = v.Int(); err == nil { diff --git a/config/file/file_test.go b/config/file/file_test.go index ac6ad8435..7354c0181 100644 --- a/config/file/file_test.go +++ b/config/file/file_test.go @@ -206,7 +206,7 @@ func TestConfig(t *testing.T) { } func testConfig(t *testing.T, c config.Config) { - expected := map[string]interface{}{ + expected := map[string]any{ "test.settings.int_key": int64(1000), "test.settings.float_key": 1000.1, "test.settings.string_key": "string_value", diff --git a/config/options.go b/config/options.go index 7395660d5..bdf6780c2 100644 --- a/config/options.go +++ b/config/options.go @@ -10,13 +10,13 @@ import ( ) // Decoder is config decoder. -type Decoder func(*KeyValue, map[string]interface{}) error +type Decoder func(*KeyValue, map[string]any) error // Resolver resolve placeholder in config. -type Resolver func(map[string]interface{}) error +type Resolver func(map[string]any) error // Merge is config merge func. -type Merge func(dst, src interface{}) error +type Merge func(dst, src any) error // Option is config option. type Option func(*options) @@ -70,7 +70,7 @@ func WithMergeFunc(m Merge) Option { // defaultDecoder decode config from source KeyValue // to target map[string]interface{} using src.Format codec. -func defaultDecoder(src *KeyValue, target map[string]interface{}) error { +func defaultDecoder(src *KeyValue, target map[string]any) error { if src.Format == "" { // expand key "aaa.bbb" into map[aaa]map[bbb]interface{} keys := strings.Split(src.Key, ".") @@ -78,7 +78,7 @@ func defaultDecoder(src *KeyValue, target map[string]interface{}) error { if i == len(keys)-1 { target[k] = src.Value } else { - sub := make(map[string]interface{}) + sub := make(map[string]any) target[k] = sub target = sub } @@ -91,8 +91,8 @@ func defaultDecoder(src *KeyValue, target map[string]interface{}) error { return fmt.Errorf("unsupported key: %s format: %s", src.Key, src.Format) } -func newActualTypesResolver(enableConvertToType bool) func(map[string]interface{}) error { - return func(input map[string]interface{}) error { +func newActualTypesResolver(enableConvertToType bool) func(map[string]any) error { + return func(input map[string]any) error { mapper := mapper(input) return resolver(input, mapper, enableConvertToType) } @@ -100,28 +100,28 @@ func newActualTypesResolver(enableConvertToType bool) func(map[string]interface{ // defaultResolver resolve placeholder in map value, // placeholder format in ${key:default}. -func defaultResolver(input map[string]interface{}) error { +func defaultResolver(input map[string]any) error { mapper := mapper(input) return resolver(input, mapper, false) } -func resolver(input map[string]interface{}, mapper func(name string) string, toType bool) error { - var resolve func(map[string]interface{}) error - resolve = func(sub map[string]interface{}) error { +func resolver(input map[string]any, mapper func(name string) string, toType bool) error { + var resolve func(map[string]any) error + resolve = func(sub map[string]any) error { for k, v := range sub { switch vt := v.(type) { case string: sub[k] = expand(vt, mapper, toType) - case map[string]interface{}: + case map[string]any: if err := resolve(vt); err != nil { return err } - case []interface{}: + case []any: for i, iface := range vt { switch it := iface.(type) { case string: vt[i] = expand(it, mapper, toType) - case map[string]interface{}: + case map[string]any: if err := resolve(it); err != nil { return err } @@ -135,7 +135,7 @@ func resolver(input map[string]interface{}, mapper func(name string) string, toT return resolve(input) } -func mapper(input map[string]interface{}) func(name string) string { +func mapper(input map[string]any) func(name string) string { mapper := func(name string) string { args := strings.SplitN(strings.TrimSpace(name), ":", 2) //nolint:mnd if v, has := readValue(input, args[0]); has { @@ -149,7 +149,7 @@ func mapper(input map[string]interface{}) func(name string) string { return mapper } -func convertToType(input string) interface{} { +func convertToType(input string) any { // Check if the input is a string with quotes if strings.HasPrefix(input, "\"") && strings.HasSuffix(input, "\"") { // Trim the quotes and return the string value @@ -178,10 +178,10 @@ func convertToType(input string) interface{} { return input } -func expand(s string, mapping func(string) string, toType bool) interface{} { +func expand(s string, mapping func(string) string, toType bool) any { r := regexp.MustCompile(`\${(.*?)}`) re := r.FindAllStringSubmatch(s, -1) - var ct interface{} + var ct any for _, i := range re { if len(i) == 2 { //nolint:mnd m := mapping(i[1]) diff --git a/config/options_test.go b/config/options_test.go index aebc673af..c9af321e5 100644 --- a/config/options_test.go +++ b/config/options_test.go @@ -12,12 +12,12 @@ func TestDefaultDecoder(t *testing.T) { Value: []byte("config"), Format: "", } - target := make(map[string]interface{}) + target := make(map[string]any) err := defaultDecoder(src, target) if err != nil { t.Fatal(err) } - if !reflect.DeepEqual(target, map[string]interface{}{"service": []byte("config")}) { + if !reflect.DeepEqual(target, map[string]any{"service": []byte("config")}) { t.Fatal(`target is not equal to map[string]interface{}{"service": "config"}`) } @@ -26,14 +26,14 @@ func TestDefaultDecoder(t *testing.T) { Value: []byte("2233"), Format: "", } - target = make(map[string]interface{}) + target = make(map[string]any) err = defaultDecoder(src, target) if err != nil { t.Fatal(err) } - if !reflect.DeepEqual(map[string]interface{}{ - "service": map[string]interface{}{ - "name": map[string]interface{}{ + if !reflect.DeepEqual(map[string]any{ + "service": map[string]any{ + "name": map[string]any{ "alias": []byte("2233"), }, }, @@ -49,9 +49,9 @@ func TestDefaultResolver(t *testing.T) { rateFloat = 0.9 ) - data := map[string]interface{}{ - "foo": map[string]interface{}{ - "bar": map[string]interface{}{ + data := map[string]any{ + "foo": map[string]any{ + "bar": map[string]any{ "notexist": "${NOTEXIST:100}", "port": "${PORT:8081}", "count": "${COUNT:0}", @@ -59,9 +59,9 @@ func TestDefaultResolver(t *testing.T) { "rate": "${RATE}", "empty": "${EMPTY:foobar}", "url": "${URL:http://example.com}", - "array": []interface{}{ + "array": []any{ "${PORT}", - map[string]interface{}{"foobar": "${NOTEXIST:8081}"}, + map[string]any{"foobar": "${NOTEXIST:8081}"}, }, "value1": "${test.value}", "value2": "$PORT", @@ -69,7 +69,7 @@ func TestDefaultResolver(t *testing.T) { "value4": "${foo${bar}}", }, }, - "test": map[string]interface{}{ + "test": map[string]any{ "value": "foobar", }, "PORT": "8080", @@ -82,7 +82,7 @@ func TestDefaultResolver(t *testing.T) { tests := []struct { name string path string - expect interface{} + expect any }{ { name: "test not exist int env with default", @@ -122,7 +122,7 @@ func TestDefaultResolver(t *testing.T) { { name: "test array", path: "foo.bar.array", - expect: []interface{}{portString, map[string]interface{}{"foobar": "8081"}}, + expect: []any{portString, map[string]any{"foobar": "8081"}}, }, { name: "test ${test.value}", @@ -156,7 +156,7 @@ func TestDefaultResolver(t *testing.T) { values: data, } if v, ok := rd.Value(test.path); ok { - var actual interface{} + var actual any switch test.expect.(type) { case int: if actual, err = v.Int(); err == nil { @@ -206,9 +206,9 @@ func TestNewDefaultResolver(t *testing.T) { rateFloat = 0.9 ) - data := map[string]interface{}{ - "foo": map[string]interface{}{ - "bar": map[string]interface{}{ + data := map[string]any{ + "foo": map[string]any{ + "bar": map[string]any{ "notexist": "${NOTEXIST:100}", "port": "${PORT:\"8081\"}", "count": "${COUNT:\"0\"}", @@ -216,9 +216,9 @@ func TestNewDefaultResolver(t *testing.T) { "rate": "${RATE}", "empty": "${EMPTY:foobar}", "url": "${URL:\"http://example.com\"}", - "array": []interface{}{ + "array": []any{ "${PORT}", - map[string]interface{}{"foobar": "${NOTEXIST:\"8081\"}"}, + map[string]any{"foobar": "${NOTEXIST:\"8081\"}"}, }, "value1": "${test.value}", "value2": "$PORT", @@ -226,7 +226,7 @@ func TestNewDefaultResolver(t *testing.T) { "value4": "${foo${bar}}", }, }, - "test": map[string]interface{}{ + "test": map[string]any{ "value": "foobar", }, "PORT": "\"8080\"", @@ -239,7 +239,7 @@ func TestNewDefaultResolver(t *testing.T) { tests := []struct { name string path string - expect interface{} + expect any }{ { name: "test not exist int env with default", @@ -279,7 +279,7 @@ func TestNewDefaultResolver(t *testing.T) { { name: "test array", path: "foo.bar.array", - expect: []interface{}{portString, map[string]interface{}{"foobar": "8081"}}, + expect: []any{portString, map[string]any{"foobar": "8081"}}, }, { name: "test ${test.value}", @@ -314,7 +314,7 @@ func TestNewDefaultResolver(t *testing.T) { values: data, } if v, ok := rd.Value(test.path); ok { - var actual interface{} + var actual any switch test.expect.(type) { case int: if actual, err = v.Int(); err == nil { diff --git a/config/reader.go b/config/reader.go index 129705052..cd9e146ad 100644 --- a/config/reader.go +++ b/config/reader.go @@ -24,14 +24,14 @@ type Reader interface { type reader struct { opts options - values map[string]interface{} + values map[string]any lock sync.Mutex } func newReader(opts options) Reader { return &reader{ opts: opts, - values: make(map[string]interface{}), + values: make(map[string]any), lock: sync.Mutex{}, } } @@ -42,7 +42,7 @@ func (r *reader) Merge(kvs ...*KeyValue) error { return err } for _, kv := range kvs { - next := make(map[string]interface{}) + next := make(map[string]any) if err := r.opts.decoder(kv, next); err != nil { log.Errorf("Failed to config decode error: %v key: %s value: %s", err, kv.Key, string(kv.Value)) return err @@ -76,24 +76,24 @@ func (r *reader) Resolve() error { return r.opts.resolver(r.values) } -func (r *reader) cloneMap() (map[string]interface{}, error) { +func (r *reader) cloneMap() (map[string]any, error) { r.lock.Lock() defer r.lock.Unlock() return cloneMap(r.values) } -func cloneMap(src map[string]interface{}) (map[string]interface{}, error) { +func cloneMap(src map[string]any) (map[string]any, error) { // https://gist.github.com/soroushjp/0ec92102641ddfc3ad5515ca76405f4d var buf bytes.Buffer - gob.Register(map[string]interface{}{}) - gob.Register([]interface{}{}) + gob.Register(map[string]any{}) + gob.Register([]any{}) enc := gob.NewEncoder(&buf) dec := gob.NewDecoder(&buf) err := enc.Encode(src) if err != nil { return nil, err } - var clone map[string]interface{} + var clone map[string]any err = dec.Decode(&clone) if err != nil { return nil, err @@ -101,22 +101,22 @@ func cloneMap(src map[string]interface{}) (map[string]interface{}, error) { return clone, nil } -func convertMap(src interface{}) interface{} { +func convertMap(src any) any { switch m := src.(type) { - case map[string]interface{}: - dst := make(map[string]interface{}, len(m)) + case map[string]any: + dst := make(map[string]any, len(m)) for k, v := range m { dst[k] = convertMap(v) } return dst - case map[interface{}]interface{}: - dst := make(map[string]interface{}, len(m)) + case map[any]any: + dst := make(map[string]any, len(m)) for k, v := range m { dst[fmt.Sprint(k)] = convertMap(v) } return dst - case []interface{}: - dst := make([]interface{}, len(m)) + case []any: + dst := make([]any, len(m)) for k, v := range m { dst[k] = convertMap(v) } @@ -131,7 +131,7 @@ func convertMap(src interface{}) interface{} { // readValue read Value in given map[string]interface{} // by the given path, will return false if not found. -func readValue(values map[string]interface{}, path string) (Value, bool) { +func readValue(values map[string]any, path string) (Value, bool) { var ( next = values keys = strings.Split(path, ".") @@ -148,7 +148,7 @@ func readValue(values map[string]interface{}, path string) (Value, bool) { return av, true } switch vm := value.(type) { - case map[string]interface{}: + case map[string]any: next = vm default: return nil, false @@ -157,14 +157,14 @@ func readValue(values map[string]interface{}, path string) (Value, bool) { return nil, false } -func marshalJSON(v interface{}) ([]byte, error) { +func marshalJSON(v any) ([]byte, error) { if m, ok := v.(proto.Message); ok { return protojson.MarshalOptions{EmitUnpopulated: true}.Marshal(m) } return json.Marshal(v) } -func unmarshalJSON(data []byte, v interface{}) error { +func unmarshalJSON(data []byte, v any) error { if m, ok := v.(proto.Message); ok { return protojson.UnmarshalOptions{DiscardUnknown: true}.Unmarshal(data, m) } diff --git a/config/reader_test.go b/config/reader_test.go index 663b50ac2..af7607840 100644 --- a/config/reader_test.go +++ b/config/reader_test.go @@ -16,14 +16,14 @@ func TestReader_Merge(t *testing.T) { ok bool ) opts := options{ - decoder: func(kv *KeyValue, v map[string]interface{}) error { + decoder: func(kv *KeyValue, v map[string]any) error { if codec := encoding.GetCodec(kv.Format); codec != nil { return codec.Unmarshal(kv.Value, &v) } return fmt.Errorf("unsupported key: %s format: %s", kv.Key, kv.Format) }, resolver: defaultResolver, - merge: func(dst, src interface{}) error { + merge: func(dst, src any) error { return mergo.Map(dst, src, mergo.WithOverride) }, } @@ -80,14 +80,14 @@ func TestReader_Merge(t *testing.T) { func TestReader_Value(t *testing.T) { opts := options{ - decoder: func(kv *KeyValue, v map[string]interface{}) error { + decoder: func(kv *KeyValue, v map[string]any) error { if codec := encoding.GetCodec(kv.Format); codec != nil { return codec.Unmarshal(kv.Value, &v) } return fmt.Errorf("unsupported key: %s format: %s", kv.Key, kv.Format) }, resolver: defaultResolver, - merge: func(dst, src interface{}) error { + merge: func(dst, src any) error { return mergo.Map(dst, src, mergo.WithOverride) }, } @@ -185,14 +185,14 @@ a: func TestReader_Source(t *testing.T) { var err error opts := options{ - decoder: func(kv *KeyValue, v map[string]interface{}) error { + decoder: func(kv *KeyValue, v map[string]any) error { if codec := encoding.GetCodec(kv.Format); codec != nil { return codec.Unmarshal(kv.Value, &v) } return fmt.Errorf("unsupported key: %s format: %s", kv.Key, kv.Format) }, resolver: defaultResolver, - merge: func(dst, src interface{}) error { + merge: func(dst, src any) error { return mergo.Map(dst, src, mergo.WithOverride) }, } @@ -216,28 +216,28 @@ func TestReader_Source(t *testing.T) { func TestCloneMap(t *testing.T) { tests := []struct { - input map[string]interface{} - want map[string]interface{} + input map[string]any + want map[string]any }{ { - input: map[string]interface{}{ + input: map[string]any{ "a": 1, "b": "2", "c": true, }, - want: map[string]interface{}{ + want: map[string]any{ "a": 1, "b": "2", "c": true, }, }, { - input: map[string]interface{}{}, - want: map[string]interface{}{}, + input: map[string]any{}, + want: map[string]any{}, }, { input: nil, - want: map[string]interface{}{}, + want: map[string]any{}, }, } for _, tt := range tests { @@ -251,17 +251,17 @@ func TestCloneMap(t *testing.T) { func TestConvertMap(t *testing.T) { tests := []struct { - input interface{} - want interface{} + input any + want any }{ { - input: map[string]interface{}{ + input: map[string]any{ "a": 1, "b": "2", "c": true, "d": []byte{65, 66, 67}, }, - want: map[string]interface{}{ + want: map[string]any{ "a": 1, "b": "2", "c": true, @@ -269,8 +269,8 @@ func TestConvertMap(t *testing.T) { }, }, { - input: []interface{}{1, 2.0, "3", true, nil, []interface{}{1, 2.0, "3", true, nil}}, - want: []interface{}{1, 2.0, "3", true, nil, []interface{}{1, 2.0, "3", true, nil}}, + input: []any{1, 2.0, "3", true, nil, []any{1, 2.0, "3", true, nil}}, + want: []any{1, 2.0, "3", true, nil, []any{1, 2.0, "3", true, nil}}, }, { input: []byte{65, 66, 67}, @@ -285,11 +285,11 @@ func TestConvertMap(t *testing.T) { } func TestReadValue(t *testing.T) { - m := map[string]interface{}{ + m := map[string]any{ "a": 1, - "b": map[string]interface{}{ + "b": map[string]any{ "c": "3", - "d": map[string]interface{}{ + "d": map[string]any{ "e": true, }, }, diff --git a/config/value.go b/config/value.go index 11de2e897..a9930cedb 100644 --- a/config/value.go +++ b/config/value.go @@ -27,9 +27,9 @@ type Value interface { Duration() (time.Duration, error) Slice() ([]Value, error) Map() (map[string]Value, error) - Scan(interface{}) error - Load() interface{} - Store(interface{}) + Scan(any) error + Load() any + Store(any) } type atomicValue struct { @@ -83,7 +83,7 @@ func (v *atomicValue) Int() (int64, error) { } func (v *atomicValue) Slice() ([]Value, error) { - vals, ok := v.Load().([]interface{}) + vals, ok := v.Load().([]any) if !ok { return nil, v.typeAssertError() } @@ -97,7 +97,7 @@ func (v *atomicValue) Slice() ([]Value, error) { } func (v *atomicValue) Map() (map[string]Value, error) { - vals, ok := v.Load().(map[string]interface{}) + vals, ok := v.Load().(map[string]any) if !ok { return nil, v.typeAssertError() } @@ -164,7 +164,7 @@ func (v *atomicValue) Duration() (time.Duration, error) { return time.Duration(val), nil } -func (v *atomicValue) Scan(obj interface{}) error { +func (v *atomicValue) Scan(obj any) error { data, err := json.Marshal(v.Load()) if err != nil { return err @@ -184,8 +184,8 @@ func (v errValue) Int() (int64, error) { return 0, v.err } func (v errValue) Float() (float64, error) { return 0.0, v.err } func (v errValue) Duration() (time.Duration, error) { return 0, v.err } func (v errValue) String() (string, error) { return "", v.err } -func (v errValue) Scan(interface{}) error { return v.err } -func (v errValue) Load() interface{} { return nil } -func (v errValue) Store(interface{}) {} +func (v errValue) Scan(any) error { return v.err } +func (v errValue) Load() any { return nil } +func (v errValue) Store(any) {} func (v errValue) Slice() ([]Value, error) { return nil, v.err } func (v errValue) Map() (map[string]Value, error) { return nil, v.err } diff --git a/config/value_test.go b/config/value_test.go index df771757b..cb1fcc767 100644 --- a/config/value_test.go +++ b/config/value_test.go @@ -7,7 +7,7 @@ import ( ) func TestAtomicValue_Bool(t *testing.T) { - vlist := []interface{}{"1", "t", "T", "true", "TRUE", "True", true, 1, int32(1)} + vlist := []any{"1", "t", "T", "true", "TRUE", "True", true, 1, int32(1)} for _, x := range vlist { v := atomicValue{} v.Store(x) @@ -20,7 +20,7 @@ func TestAtomicValue_Bool(t *testing.T) { } } - vlist = []interface{}{"0", "f", "F", "false", "FALSE", "False", false, 0, int32(0)} + vlist = []any{"0", "f", "F", "false", "FALSE", "False", false, 0, int32(0)} for _, x := range vlist { v := atomicValue{} v.Store(x) @@ -33,7 +33,7 @@ func TestAtomicValue_Bool(t *testing.T) { } } - vlist = []interface{}{"bbb", "-1"} + vlist = []any{"bbb", "-1"} for _, x := range vlist { v := atomicValue{} v.Store(x) @@ -45,7 +45,7 @@ func TestAtomicValue_Bool(t *testing.T) { } func TestAtomicValue_Int(t *testing.T) { - vlist := []interface{}{"123123", float64(123123), int64(123123), int32(123123), 123123} + vlist := []any{"123123", float64(123123), int64(123123), int32(123123), 123123} for _, x := range vlist { v := atomicValue{} v.Store(x) @@ -58,7 +58,7 @@ func TestAtomicValue_Int(t *testing.T) { } } - vlist = []interface{}{"bbb", "-x1", true} + vlist = []any{"bbb", "-x1", true} for _, x := range vlist { v := atomicValue{} v.Store(x) @@ -70,7 +70,7 @@ func TestAtomicValue_Int(t *testing.T) { } func TestAtomicValue_Float(t *testing.T) { - vlist := []interface{}{"123123.1", 123123.1} + vlist := []any{"123123.1", 123123.1} for _, x := range vlist { v := atomicValue{} v.Store(x) @@ -83,7 +83,7 @@ func TestAtomicValue_Float(t *testing.T) { } } - vlist = []interface{}{"bbb", "-x1"} + vlist = []any{"bbb", "-x1"} for _, x := range vlist { v := atomicValue{} v.Store(x) @@ -104,7 +104,7 @@ func (t ts) String() string { } func TestAtomicValue_String(t *testing.T) { - vlist := []interface{}{"1", float64(1), int64(1), 1, int64(1)} + vlist := []any{"1", float64(1), int64(1), 1, int64(1)} for _, x := range vlist { v := atomicValue{} v.Store(x) @@ -142,7 +142,7 @@ func TestAtomicValue_String(t *testing.T) { } func TestAtomicValue_Duration(t *testing.T) { - vlist := []interface{}{int64(5)} + vlist := []any{int64(5)} for _, x := range vlist { v := atomicValue{} v.Store(x) @@ -157,7 +157,7 @@ func TestAtomicValue_Duration(t *testing.T) { } func TestAtomicValue_Slice(t *testing.T) { - vlist := []interface{}{int64(5)} + vlist := []any{int64(5)} v := atomicValue{} v.Store(vlist) slices, err := v.Slice() @@ -176,7 +176,7 @@ func TestAtomicValue_Slice(t *testing.T) { } func TestAtomicValue_Map(t *testing.T) { - vlist := make(map[string]interface{}) + vlist := make(map[string]any) vlist["5"] = int64(5) vlist["text"] = "text" v := atomicValue{} diff --git a/contrib/config/apollo/apollo.go b/contrib/config/apollo/apollo.go index 1734fdb02..8e15b9011 100644 --- a/contrib/config/apollo/apollo.go +++ b/contrib/config/apollo/apollo.go @@ -178,8 +178,8 @@ func (e *apollo) load() []*config.KeyValue { } func (e *apollo) getConfig(ns string) (*config.KeyValue, error) { - next := map[string]interface{}{} - e.client.GetConfigCache(ns).Range(func(key, value interface{}) bool { + next := map[string]any{} + e.client.GetConfigCache(ns).Range(func(key, value any) bool { // all values are out properties format resolve(genKey(ns, key.(string)), value, next) return true @@ -224,7 +224,7 @@ func (e *apollo) Watch() (config.Watcher, error) { // resolve convert kv pair into one map[string]interface{} by split key into different // map level. such as: app.name = "application" => map[app][name] = "application" -func resolve(key string, value interface{}, target map[string]interface{}) { +func resolve(key string, value any, target map[string]any) { // expand key "aaa.bbb" into map[aaa]map[bbb]interface{} keys := strings.Split(key, ".") last := len(keys) - 1 @@ -240,7 +240,7 @@ func resolve(key string, value interface{}, target map[string]interface{}) { v, ok := cursor[k] if !ok { // create a new map - deeper := make(map[string]interface{}) + deeper := make(map[string]any) cursor[k] = deeper cursor = deeper continue @@ -248,7 +248,7 @@ func resolve(key string, value interface{}, target map[string]interface{}) { // current exists, then check existing value type, if it's not map // that means duplicate keys, and at least one is not map instance. - if cursor, ok = v.(map[string]interface{}); !ok { + if cursor, ok = v.(map[string]any); !ok { log.Warnf("duplicate key: %v\n", strings.Join(keys[:i+1], ".")) break } diff --git a/contrib/config/apollo/parser.go b/contrib/config/apollo/parser.go index 2b1abb991..501fc79d2 100644 --- a/contrib/config/apollo/parser.go +++ b/contrib/config/apollo/parser.go @@ -2,12 +2,12 @@ package apollo type jsonExtParser struct{} -func (parser jsonExtParser) Parse(configContent interface{}) (map[string]interface{}, error) { - return map[string]interface{}{"content": configContent}, nil +func (parser jsonExtParser) Parse(configContent any) (map[string]any, error) { + return map[string]any{"content": configContent}, nil } type yamlExtParser struct{} -func (parser yamlExtParser) Parse(configContent interface{}) (map[string]interface{}, error) { - return map[string]interface{}{"content": configContent}, nil +func (parser yamlExtParser) Parse(configContent any) (map[string]any, error) { + return map[string]any{"content": configContent}, nil } diff --git a/contrib/config/apollo/watcher.go b/contrib/config/apollo/watcher.go index 8431fca27..055c9bdc9 100644 --- a/contrib/config/apollo/watcher.go +++ b/contrib/config/apollo/watcher.go @@ -38,7 +38,7 @@ func (c *customChangeListener) onChange(namespace string, changes map[string]*st } } - next := make(map[string]interface{}) + next := make(map[string]any) for key, change := range changes { resolve(genKey(namespace, key), change.NewValue, next) diff --git a/contrib/config/consul/watcher.go b/contrib/config/consul/watcher.go index 6a8db3a53..acda766d1 100644 --- a/contrib/config/consul/watcher.go +++ b/contrib/config/consul/watcher.go @@ -20,7 +20,7 @@ type watcher struct { cancel context.CancelFunc } -func (w *watcher) handle(_ uint64, data interface{}) { +func (w *watcher) handle(_ uint64, data any) { if data == nil { return } @@ -68,7 +68,7 @@ func newWatcher(s *source) (*watcher, error) { cancel: cancel, } - wp, err := watch.Parse(map[string]interface{}{"type": "keyprefix", "prefix": s.options.path}) + wp, err := watch.Parse(map[string]any{"type": "keyprefix", "prefix": s.options.path}) if err != nil { return nil, err } diff --git a/contrib/encoding/msgpack/msgpack.go b/contrib/encoding/msgpack/msgpack.go index 4272b16b8..f6dce4c04 100644 --- a/contrib/encoding/msgpack/msgpack.go +++ b/contrib/encoding/msgpack/msgpack.go @@ -16,11 +16,11 @@ func init() { // codec is a Codec implementation with msgpack. type codec struct{} -func (codec) Marshal(v interface{}) ([]byte, error) { +func (codec) Marshal(v any) ([]byte, error) { return msgpack.Marshal(v) } -func (codec) Unmarshal(data []byte, v interface{}) error { +func (codec) Unmarshal(data []byte, v any) error { return msgpack.Unmarshal(data, v) } diff --git a/contrib/errortracker/sentry/sentry.go b/contrib/errortracker/sentry/sentry.go index 2aedfcdd6..a2282594a 100644 --- a/contrib/errortracker/sentry/sentry.go +++ b/contrib/errortracker/sentry/sentry.go @@ -25,7 +25,7 @@ type options struct { repanic bool waitForDelivery bool timeout time.Duration - tags map[string]interface{} + tags map[string]any } // WithRepanic repanic configures whether Sentry should repanic after recovery, in most cases it should be set to true. @@ -50,7 +50,7 @@ func WithTimeout(timeout time.Duration) Option { } // WithTags global tags injection, the value type must be string or log.Valuer -func WithTags(kvs map[string]interface{}) Option { +func WithTags(kvs map[string]any) Option { return func(opts *options) { opts.tags = kvs } @@ -66,7 +66,7 @@ func Server(opts ...Option) middleware.Middleware { conf.timeout = 2 * time.Second } return func(handler middleware.Handler) middleware.Handler { - return func(ctx context.Context, req interface{}) (reply interface{}, err error) { + return func(ctx context.Context, req any) (reply any, err error) { hub := GetHubFromContext(ctx) scope := hub.Scope() @@ -83,11 +83,11 @@ func Server(opts ...Option) middleware.Middleware { switch tr.Kind() { case transport.KindGRPC: gtr := tr.(*grpc.Transport) - scope.SetContext("gRPC", map[string]interface{}{ + scope.SetContext("gRPC", map[string]any{ "endpoint": gtr.Endpoint(), "operation": gtr.Operation(), }) - headers := make(map[string]interface{}) + headers := make(map[string]any) for _, k := range gtr.RequestHeader().Keys() { headers[k] = gtr.RequestHeader().Get(k) } @@ -106,7 +106,7 @@ func Server(opts ...Option) middleware.Middleware { } } -func recoverWithSentry(ctx context.Context, opts options, hub *sentry.Hub, req interface{}) { +func recoverWithSentry(ctx context.Context, opts options, hub *sentry.Hub, req any) { if err := recover(); err != nil { if !isBrokenPipeError(err) { eventID := hub.RecoverWithContext( @@ -123,7 +123,7 @@ func recoverWithSentry(ctx context.Context, opts options, hub *sentry.Hub, req i } } -func isBrokenPipeError(err interface{}) bool { +func isBrokenPipeError(err any) bool { if netErr, ok := err.(*net.OpError); ok { if sysErr, ok := netErr.Err.(*os.SyscallError); ok { if strings.Contains(strings.ToLower(sysErr.Error()), "broken pipe") || diff --git a/contrib/errortracker/sentry/sentry_test.go b/contrib/errortracker/sentry/sentry_test.go index 210c17628..5016ee3de 100644 --- a/contrib/errortracker/sentry/sentry_test.go +++ b/contrib/errortracker/sentry/sentry_test.go @@ -8,7 +8,7 @@ import ( func TestWithTags(t *testing.T) { opts := new(options) strval := "bar" - kvs := map[string]interface{}{ + kvs := map[string]any{ "foo": strval, } funcTags := WithTags(kvs) diff --git a/contrib/log/aliyun/aliyun.go b/contrib/log/aliyun/aliyun.go index 946cb5908..0d69bf970 100644 --- a/contrib/log/aliyun/aliyun.go +++ b/contrib/log/aliyun/aliyun.go @@ -81,7 +81,7 @@ func (a *aliyunLog) Close() error { return a.producer.Close(5000) } -func (a *aliyunLog) Log(level log.Level, keyvals ...interface{}) error { +func (a *aliyunLog) Log(level log.Level, keyvals ...any) error { contents := make([]*sls.LogContent, 0, len(keyvals)/2+1) contents = append(contents, &sls.LogContent{ @@ -127,7 +127,7 @@ func newString(s string) *string { } // toString convert any type to string -func toString(v interface{}) string { +func toString(v any) string { var key string if v == nil { return key diff --git a/contrib/log/aliyun/aliyun_test.go b/contrib/log/aliyun/aliyun_test.go index d8c914bad..752704b4f 100644 --- a/contrib/log/aliyun/aliyun_test.go +++ b/contrib/log/aliyun/aliyun_test.go @@ -110,7 +110,7 @@ func TestNewString(t *testing.T) { func TestToString(t *testing.T) { tests := []struct { name string - in interface{} + in any out string }{ {"float64", 6.66, "6.66"}, diff --git a/contrib/log/fluent/fluent.go b/contrib/log/fluent/fluent.go index 86e86993e..58fd1642a 100644 --- a/contrib/log/fluent/fluent.go +++ b/contrib/log/fluent/fluent.go @@ -151,7 +151,7 @@ func NewLogger(addr string, opts ...Option) (*Logger, error) { } // Log print the kv pairs log. -func (l *Logger) Log(level log.Level, keyvals ...interface{}) error { +func (l *Logger) Log(level log.Level, keyvals ...any) error { if len(keyvals) == 0 { return nil } diff --git a/contrib/log/logrus/logrus.go b/contrib/log/logrus/logrus.go index 6fda38c50..a3aac851f 100644 --- a/contrib/log/logrus/logrus.go +++ b/contrib/log/logrus/logrus.go @@ -18,10 +18,10 @@ func NewLogger(logger *logrus.Logger) log.Logger { } } -func (l *Logger) Log(level log.Level, keyvals ...interface{}) (err error) { +func (l *Logger) Log(level log.Level, keyvals ...any) (err error) { var ( logrusLevel logrus.Level - fields logrus.Fields = make(map[string]interface{}) + fields logrus.Fields = make(map[string]any) msg string ) diff --git a/contrib/log/logrus/logrus_test.go b/contrib/log/logrus/logrus_test.go index 45fe9da2d..21dbbe673 100644 --- a/contrib/log/logrus/logrus_test.go +++ b/contrib/log/logrus/logrus_test.go @@ -15,35 +15,35 @@ func TestLoggerLog(t *testing.T) { level logrus.Level formatter logrus.Formatter logLevel log.Level - kvs []interface{} + kvs []any want string }{ "json format": { level: logrus.InfoLevel, formatter: &logrus.JSONFormatter{}, logLevel: log.LevelInfo, - kvs: []interface{}{"case", "json format", "msg", "1"}, + kvs: []any{"case", "json format", "msg", "1"}, want: `{"case":"json format","level":"info","msg":"1"`, }, "level unmatch": { level: logrus.InfoLevel, formatter: &logrus.JSONFormatter{}, logLevel: log.LevelDebug, - kvs: []interface{}{"case", "level unmatch", "msg", "1"}, + kvs: []any{"case", "level unmatch", "msg", "1"}, want: "", }, "fatal level": { level: logrus.InfoLevel, formatter: &logrus.JSONFormatter{}, logLevel: log.LevelFatal, - kvs: []interface{}{"case", "json format", "msg", "1"}, + kvs: []any{"case", "json format", "msg", "1"}, want: `{"case":"json format","level":"fatal","msg":"1"`, }, "no tags": { level: logrus.InfoLevel, formatter: &logrus.JSONFormatter{}, logLevel: log.LevelInfo, - kvs: []interface{}{"msg", "1"}, + kvs: []any{"msg", "1"}, want: `{"level":"info","msg":"1"`, }, } diff --git a/contrib/log/tencent/tencent.go b/contrib/log/tencent/tencent.go index 460b85c60..6f9aa6c39 100644 --- a/contrib/log/tencent/tencent.go +++ b/contrib/log/tencent/tencent.go @@ -69,7 +69,7 @@ func (log *tencentLog) Close() error { return log.producer.Close(5000) } -func (log *tencentLog) Log(level log.Level, keyvals ...interface{}) error { +func (log *tencentLog) Log(level log.Level, keyvals ...any) error { contents := make([]*cls.Log_Content, 0, len(keyvals)/2+1) contents = append(contents, &cls.Log_Content{ @@ -115,7 +115,7 @@ func newString(s string) *string { } // toString convert any type to string -func toString(v interface{}) string { +func toString(v any) string { var key string if v == nil { return key diff --git a/contrib/log/tencent/tencent_test.go b/contrib/log/tencent/tencent_test.go index df1fe367c..3c5e31cc3 100644 --- a/contrib/log/tencent/tencent_test.go +++ b/contrib/log/tencent/tencent_test.go @@ -114,7 +114,7 @@ func TestNewString(t *testing.T) { func TestToString(t *testing.T) { tests := []struct { name string - in interface{} + in any out string }{ {"float64", 6.66, "6.66"}, diff --git a/contrib/log/zap/zap.go b/contrib/log/zap/zap.go index 812afb95a..168a15cc5 100644 --- a/contrib/log/zap/zap.go +++ b/contrib/log/zap/zap.go @@ -32,7 +32,7 @@ func NewLogger(zlog *zap.Logger) *Logger { } } -func (l *Logger) Log(level log.Level, keyvals ...interface{}) error { +func (l *Logger) Log(level log.Level, keyvals ...any) error { // If logging at this level is completely disabled, skip the overhead of // string formatting. if zapcore.Level(level) < zapcore.DPanicLevel && !l.log.Core().Enabled(zapcore.Level(level)) { diff --git a/contrib/log/zerolog/zerolog.go b/contrib/log/zerolog/zerolog.go index bca49ba0e..de4266de8 100644 --- a/contrib/log/zerolog/zerolog.go +++ b/contrib/log/zerolog/zerolog.go @@ -18,7 +18,7 @@ func NewLogger(logger *zerolog.Logger) log.Logger { } } -func (l *Logger) Log(level log.Level, keyvals ...interface{}) (err error) { +func (l *Logger) Log(level log.Level, keyvals ...any) (err error) { var event *zerolog.Event if len(keyvals) == 0 { return nil diff --git a/contrib/middleware/validate/validate.go b/contrib/middleware/validate/validate.go index 6aaf7f19f..57c20d2ba 100644 --- a/contrib/middleware/validate/validate.go +++ b/contrib/middleware/validate/validate.go @@ -23,7 +23,7 @@ func ProtoValidate() middleware.Middleware { } return func(handler middleware.Handler) middleware.Handler { - return func(ctx context.Context, req interface{}) (reply interface{}, err error) { + return func(ctx context.Context, req any) (reply any, err error) { if msg, ok := req.(proto.Message); ok { if err := validator.Validate(msg); err != nil { return nil, errors.BadRequest("VALIDATOR", err.Error()).WithCause(err) diff --git a/contrib/middleware/validate/validate_test.go b/contrib/middleware/validate/validate_test.go index 860018206..164c724b5 100644 --- a/contrib/middleware/validate/validate_test.go +++ b/contrib/middleware/validate/validate_test.go @@ -18,7 +18,7 @@ type testcase struct { } func TestTable(t *testing.T) { - var mock middleware.Handler = func(context.Context, interface{}) (interface{}, error) { return nil, nil } + var mock middleware.Handler = func(context.Context, any) (any, error) { return nil, nil } tests := []testcase{ { diff --git a/contrib/opensergo/opensergo.go b/contrib/opensergo/opensergo.go index cbf7d79ef..bb31c5d73 100644 --- a/contrib/opensergo/opensergo.go +++ b/contrib/opensergo/opensergo.go @@ -184,7 +184,7 @@ func listDescriptors() (services []*v1.ServiceDescriptor, types []*v1.TypeDescri return } -func HTTPPatternInfo(pattern interface{}) (method string, path string) { +func HTTPPatternInfo(pattern any) (method string, path string) { switch p := pattern.(type) { case *annotations.HttpRule_Get: return http.MethodGet, p.Get diff --git a/contrib/opensergo/opensergo_test.go b/contrib/opensergo/opensergo_test.go index 322c2c7e3..530c86ca2 100644 --- a/contrib/opensergo/opensergo_test.go +++ b/contrib/opensergo/opensergo_test.go @@ -183,7 +183,7 @@ func TestListDescriptors(t *testing.T) { func TestHTTPPatternInfo(t *testing.T) { type args struct { - pattern interface{} + pattern any } tests := []struct { name string diff --git a/contrib/polaris/ratelimit.go b/contrib/polaris/ratelimit.go index f59938e9a..8f9351318 100644 --- a/contrib/polaris/ratelimit.go +++ b/contrib/polaris/ratelimit.go @@ -22,7 +22,7 @@ var ( // Ratelimit Request rate limit middleware func Ratelimit(l Limiter) middleware.Middleware { return func(handler middleware.Handler) middleware.Handler { - return func(ctx context.Context, req interface{}) (reply interface{}, err error) { + return func(ctx context.Context, req any) (reply any, err error) { if tr, ok := transport.FromServerContext(ctx); ok { var args []model.Argument headers := tr.RequestHeader() diff --git a/contrib/registry/eureka/client.go b/contrib/registry/eureka/client.go index 0c19cd3f1..68b041be6 100644 --- a/contrib/registry/eureka/client.go +++ b/contrib/registry/eureka/client.go @@ -307,7 +307,7 @@ func (e *Client) buildAPI(currentTimes int, params ...string) string { return strings.Join(params, "/") } -func (e *Client) request(ctx context.Context, method string, params []string, input io.Reader, output interface{}, i int) (bool, error) { +func (e *Client) request(ctx context.Context, method string, params []string, input io.Reader, output any, i int) (bool, error) { request, err := http.NewRequestWithContext(ctx, method, e.buildAPI(i, params...), input) if err != nil { return false, err @@ -342,7 +342,7 @@ func (e *Client) request(ctx context.Context, method string, params []string, in return false, nil } -func (e *Client) do(ctx context.Context, method string, params []string, input io.Reader, output interface{}) error { +func (e *Client) do(ctx context.Context, method string, params []string, input io.Reader, output any) error { for i := 0; i < e.maxRetry; i++ { retry, err := e.request(ctx, method, params, input, output, i) if retry { diff --git a/contrib/registry/kubernetes/registry.go b/contrib/registry/kubernetes/registry.go index f01c5e574..6adcbf0ab 100644 --- a/contrib/registry/kubernetes/registry.go +++ b/contrib/registry/kubernetes/registry.go @@ -127,7 +127,7 @@ func (s *Registry) Register(ctx context.Context, service *registry.ServiceInstan return err } - patchBytes, err := jsoniter.Marshal(map[string]interface{}{ + patchBytes, err := jsoniter.Marshal(map[string]any{ "metadata": metav1.ObjectMeta{ Labels: map[string]string{ LabelsKeyServiceID: service.ID, @@ -195,7 +195,7 @@ func (s *Registry) Watch(ctx context.Context, name string) (registry.Watcher, er stopCh := make(chan struct{}, 1) announcement := make(chan []*registry.ServiceInstance, 1) s.podInformer.AddEventHandler(cache.FilteringResourceEventHandler{ - FilterFunc: func(obj interface{}) bool { + FilterFunc: func(obj any) bool { select { case <-stopCh: return false @@ -208,13 +208,13 @@ func (s *Registry) Watch(ctx context.Context, name string) (registry.Watcher, er } }, Handler: cache.ResourceEventHandlerFuncs{ - AddFunc: func(interface{}) { + AddFunc: func(any) { s.sendLatestInstances(ctx, name, announcement) }, - UpdateFunc: func(interface{}, interface{}) { + UpdateFunc: func(any, any) { s.sendLatestInstances(ctx, name, announcement) }, - DeleteFunc: func(interface{}) { + DeleteFunc: func(any) { s.sendLatestInstances(ctx, name, announcement) }, }, @@ -315,11 +315,11 @@ func (iter *Iterator) Stop() error { // //////////// Helper Func //////////// -func marshal(in interface{}) (string, error) { +func marshal(in any) (string, error) { return jsoniter.MarshalToString(in) } -func unmarshal(data string, in interface{}) error { +func unmarshal(data string, in any) error { return jsoniter.UnmarshalFromString(data, in) } diff --git a/contrib/registry/servicecomb/registry_test.go b/contrib/registry/servicecomb/registry_test.go index 9e1394925..82712cd3f 100644 --- a/contrib/registry/servicecomb/registry_test.go +++ b/contrib/registry/servicecomb/registry_test.go @@ -23,7 +23,7 @@ func (receiver *mockClient) WatchMicroService(_ string, _ func(*sc.MicroServiceI return nil } -//nolint +// nolint func (receiver *mockClient) FindMicroServiceInstances(_, _, microServiceName, _ string, _ ...sc.CallOption, ) ([]*pb.MicroServiceInstance, error) { diff --git a/contrib/registry/zookeeper/register.go b/contrib/registry/zookeeper/register.go index 116d344ce..77ca6cc7c 100644 --- a/contrib/registry/zookeeper/register.go +++ b/contrib/registry/zookeeper/register.go @@ -102,7 +102,7 @@ func (r *Registry) Deregister(ctx context.Context, service *registry.ServiceInst // GetService get services from zookeeper func (r *Registry) GetService(_ context.Context, serviceName string) ([]*registry.ServiceInstance, error) { - instances, err, _ := r.group.Do(serviceName, func() (interface{}, error) { + instances, err, _ := r.group.Do(serviceName, func() (any, error) { serviceNamePath := path.Join(r.opts.namespace, serviceName) servicesID, _, err := r.conn.Children(serviceNamePath) if err != nil { diff --git a/encoding/encoding.go b/encoding/encoding.go index f9defe602..55fc93f92 100644 --- a/encoding/encoding.go +++ b/encoding/encoding.go @@ -9,9 +9,9 @@ import ( // methods can be called from concurrent goroutines. type Codec interface { // Marshal returns the wire format of v. - Marshal(v interface{}) ([]byte, error) + Marshal(v any) ([]byte, error) // Unmarshal parses the wire format into v. - Unmarshal(data []byte, v interface{}) error + Unmarshal(data []byte, v any) error // Name returns the name of the Codec implementation. The returned string // will be used as part of content type in transmission. The result must be // static; the result cannot change between calls. diff --git a/encoding/encoding_test.go b/encoding/encoding_test.go index 98640ff46..a010dc355 100644 --- a/encoding/encoding_test.go +++ b/encoding/encoding_test.go @@ -8,11 +8,11 @@ import ( type codec struct{} -func (c codec) Marshal(_ interface{}) ([]byte, error) { +func (c codec) Marshal(_ any) ([]byte, error) { panic("implement me") } -func (c codec) Unmarshal(_ []byte, _ interface{}) error { +func (c codec) Unmarshal(_ []byte, _ any) error { panic("implement me") } @@ -23,11 +23,11 @@ func (c codec) Name() string { // codec2 is a Codec implementation with xml. type codec2 struct{} -func (codec2) Marshal(v interface{}) ([]byte, error) { +func (codec2) Marshal(v any) ([]byte, error) { return xml.Marshal(v) } -func (codec2) Unmarshal(data []byte, v interface{}) error { +func (codec2) Unmarshal(data []byte, v any) error { return xml.Unmarshal(data, v) } @@ -67,9 +67,9 @@ func TestRegisterCodec(t *testing.T) { type PanicTestFunc func() // didPanic returns true if the function passed to it panics. Otherwise, it returns false. -func didPanic(f PanicTestFunc) (bool, interface{}, string) { +func didPanic(f PanicTestFunc) (bool, any, string) { didPanic := false - var message interface{} + var message any var stack string func() { defer func() { diff --git a/encoding/form/form.go b/encoding/form/form.go index 2e4a4b201..22b554af0 100644 --- a/encoding/form/form.go +++ b/encoding/form/form.go @@ -37,7 +37,7 @@ type codec struct { decoder *form.Decoder } -func (c codec) Marshal(v interface{}) ([]byte, error) { +func (c codec) Marshal(v any) ([]byte, error) { var vs url.Values var err error if m, ok := v.(proto.Message); ok { @@ -59,7 +59,7 @@ func (c codec) Marshal(v interface{}) ([]byte, error) { return []byte(vs.Encode()), nil } -func (c codec) Unmarshal(data []byte, v interface{}) error { +func (c codec) Unmarshal(data []byte, v any) error { vs, err := url.ParseQuery(string(data)) if err != nil { return err diff --git a/encoding/form/proto_encode.go b/encoding/form/proto_encode.go index 67b92f927..c0622acaf 100644 --- a/encoding/form/proto_encode.go +++ b/encoding/form/proto_encode.go @@ -14,7 +14,7 @@ import ( ) // EncodeValues encode a message into url values. -func EncodeValues(msg interface{}) (url.Values, error) { +func EncodeValues(msg any) (url.Values, error) { if msg == nil || (reflect.ValueOf(msg).Kind() == reflect.Ptr && reflect.ValueOf(msg).IsNil()) { return url.Values{}, nil } diff --git a/encoding/json/json.go b/encoding/json/json.go index c1982190e..b3274a366 100644 --- a/encoding/json/json.go +++ b/encoding/json/json.go @@ -31,7 +31,7 @@ func init() { // codec is a Codec implementation with json. type codec struct{} -func (codec) Marshal(v interface{}) ([]byte, error) { +func (codec) Marshal(v any) ([]byte, error) { switch m := v.(type) { case json.Marshaler: return m.MarshalJSON() @@ -42,7 +42,7 @@ func (codec) Marshal(v interface{}) ([]byte, error) { } } -func (codec) Unmarshal(data []byte, v interface{}) error { +func (codec) Unmarshal(data []byte, v any) error { switch m := v.(type) { case json.Unmarshaler: return m.UnmarshalJSON(data) diff --git a/encoding/json/json_test.go b/encoding/json/json_test.go index b43e4ef70..527d73701 100644 --- a/encoding/json/json_test.go +++ b/encoding/json/json_test.go @@ -65,7 +65,7 @@ func (a *mock) MarshalJSON() ([]byte, error) { func TestJSON_Marshal(t *testing.T) { tests := []struct { - input interface{} + input any expect string }{ { @@ -107,7 +107,7 @@ func TestJSON_Unmarshal(t *testing.T) { p4 := &mock{} tests := []struct { input string - expect interface{} + expect any }{ { input: `{"a":"","b":"","c":""}`, diff --git a/encoding/proto/proto.go b/encoding/proto/proto.go index 8c6ae58d1..03486a161 100644 --- a/encoding/proto/proto.go +++ b/encoding/proto/proto.go @@ -21,11 +21,11 @@ func init() { // codec is a Codec implementation with protobuf. It is the default codec for Transport. type codec struct{} -func (codec) Marshal(v interface{}) ([]byte, error) { +func (codec) Marshal(v any) ([]byte, error) { return proto.Marshal(v.(proto.Message)) } -func (codec) Unmarshal(data []byte, v interface{}) error { +func (codec) Unmarshal(data []byte, v any) error { pm, err := getProtoMessage(v) if err != nil { return err @@ -37,7 +37,7 @@ func (codec) Name() string { return Name } -func getProtoMessage(v interface{}) (proto.Message, error) { +func getProtoMessage(v any) (proto.Message, error) { if msg, ok := v.(proto.Message); ok { return msg, nil } diff --git a/encoding/proto/proto_test.go b/encoding/proto/proto_test.go index 2c2ffece9..bd51a7049 100644 --- a/encoding/proto/proto_test.go +++ b/encoding/proto/proto_test.go @@ -80,7 +80,7 @@ func TestCodec2(t *testing.T) { func Test_getProtoMessage(t *testing.T) { p := &testData.TestModel{Id: 1} type args struct { - v interface{} + v any } tests := []struct { name string diff --git a/encoding/xml/xml.go b/encoding/xml/xml.go index 3352fdfaf..a41ada82f 100644 --- a/encoding/xml/xml.go +++ b/encoding/xml/xml.go @@ -16,11 +16,11 @@ func init() { // codec is a Codec implementation with xml. type codec struct{} -func (codec) Marshal(v interface{}) ([]byte, error) { +func (codec) Marshal(v any) ([]byte, error) { return xml.Marshal(v) } -func (codec) Unmarshal(data []byte, v interface{}) error { +func (codec) Unmarshal(data []byte, v any) error { return xml.Unmarshal(data, v) } diff --git a/encoding/xml/xml_test.go b/encoding/xml/xml_test.go index 09e7d03b9..c2c21afc7 100644 --- a/encoding/xml/xml_test.go +++ b/encoding/xml/xml_test.go @@ -7,7 +7,7 @@ import ( ) type Plain struct { - V interface{} + V any } type NestedOrder struct { @@ -19,7 +19,7 @@ type NestedOrder struct { func TestCodec_Marshal(t *testing.T) { tests := []struct { - Value interface{} + Value any ExpectXML string }{ // Test value types @@ -54,7 +54,7 @@ func TestCodec_Marshal(t *testing.T) { func TestCodec_Unmarshal(t *testing.T) { tests := []struct { - want interface{} + want any InputXML string }{ { @@ -85,7 +85,7 @@ func TestCodec_Unmarshal(t *testing.T) { func TestCodec_NilUnmarshal(t *testing.T) { tests := []struct { - want interface{} + want any InputXML string }{ { diff --git a/encoding/yaml/yaml.go b/encoding/yaml/yaml.go index 1364b24c1..74e6ad1a6 100644 --- a/encoding/yaml/yaml.go +++ b/encoding/yaml/yaml.go @@ -16,11 +16,11 @@ func init() { // codec is a Codec implementation with yaml. type codec struct{} -func (codec) Marshal(v interface{}) ([]byte, error) { +func (codec) Marshal(v any) ([]byte, error) { return yaml.Marshal(v) } -func (codec) Unmarshal(data []byte, v interface{}) error { +func (codec) Unmarshal(data []byte, v any) error { return yaml.Unmarshal(data, v) } diff --git a/encoding/yaml/yaml_test.go b/encoding/yaml/yaml_test.go index 5cb746497..0cb75275a 100644 --- a/encoding/yaml/yaml_test.go +++ b/encoding/yaml/yaml_test.go @@ -9,7 +9,7 @@ import ( func TestCodec_Unmarshal(t *testing.T) { tests := []struct { data string - value interface{} + value any }{ { "", @@ -23,7 +23,7 @@ func TestCodec_Unmarshal(t *testing.T) { map[string]string{"v": "hi"}, }, { - "v: hi", map[string]interface{}{"v": "hi"}, + "v: hi", map[string]any{"v": "hi"}, }, { "v: true", @@ -31,19 +31,19 @@ func TestCodec_Unmarshal(t *testing.T) { }, { "v: true", - map[string]interface{}{"v": true}, + map[string]any{"v": true}, }, { "v: 10", - map[string]interface{}{"v": 10}, + map[string]any{"v": 10}, }, { "v: 0b10", - map[string]interface{}{"v": 2}, + map[string]any{"v": 2}, }, { "v: 0xA", - map[string]interface{}{"v": 10}, + map[string]any{"v": 10}, }, { "v: 4294967296", @@ -51,27 +51,27 @@ func TestCodec_Unmarshal(t *testing.T) { }, { "v: 0.1", - map[string]interface{}{"v": 0.1}, + map[string]any{"v": 0.1}, }, { "v: .1", - map[string]interface{}{"v": 0.1}, + map[string]any{"v": 0.1}, }, { "v: .Inf", - map[string]interface{}{"v": math.Inf(+1)}, + map[string]any{"v": math.Inf(+1)}, }, { "v: -.Inf", - map[string]interface{}{"v": math.Inf(-1)}, + map[string]any{"v": math.Inf(-1)}, }, { "v: -10", - map[string]interface{}{"v": -10}, + map[string]any{"v": -10}, }, { "v: -.1", - map[string]interface{}{"v": -0.1}, + map[string]any{"v": -0.1}, }, } for _, tt := range tests { @@ -84,7 +84,7 @@ func TestCodec_Unmarshal(t *testing.T) { } spec := struct { A string - B map[string]interface{} + B map[string]any }{A: "a"} err := (codec{}).Unmarshal([]byte("v: hi"), &spec.B) if err != nil { diff --git a/errors/errors.go b/errors/errors.go index ae0764f8f..aaffa282c 100644 --- a/errors/errors.go +++ b/errors/errors.go @@ -76,12 +76,12 @@ func New(code int, reason, message string) *Error { } // Newf New(code fmt.Sprintf(format, a...)) -func Newf(code int, reason, format string, a ...interface{}) *Error { +func Newf(code int, reason, format string, a ...any) *Error { return New(code, reason, fmt.Sprintf(format, a...)) } // Errorf returns an error object for the code, message and error info. -func Errorf(code int, reason, format string, a ...interface{}) error { +func Errorf(code int, reason, format string, a ...any) error { return New(code, reason, fmt.Sprintf(format, a...)) } diff --git a/errors/wrap.go b/errors/wrap.go index 65480a8d7..0158e9663 100644 --- a/errors/wrap.go +++ b/errors/wrap.go @@ -26,7 +26,7 @@ func Is(err, target error) bool { return stderrors.Is(err, target) } // // As will panic if target is not a non-nil pointer to either a type that implements // error, or to any interface type. As returns false if err is nil. -func As(err error, target interface{}) bool { return stderrors.As(err, target) } +func As(err error, target any) bool { return stderrors.As(err, target) } // Unwrap returns the result of calling the Unwrap method on err, if err's // type contains an Unwrap method returning error. diff --git a/internal/context/context.go b/internal/context/context.go index 3c15f7a61..302777f48 100644 --- a/internal/context/context.go +++ b/internal/context/context.go @@ -107,7 +107,7 @@ func (mc *mergeCtx) Deadline() (time.Time, bool) { } // Value implements context.Context. -func (mc *mergeCtx) Value(key interface{}) interface{} { +func (mc *mergeCtx) Value(key any) any { if v := mc.parent1.Value(key); v != nil { return v } diff --git a/internal/group/example_test.go b/internal/group/example_test.go index dc90f229a..edab42614 100644 --- a/internal/group/example_test.go +++ b/internal/group/example_test.go @@ -11,7 +11,7 @@ func (c *Counter) Incr() { } func ExampleGroup_Get() { - group := NewGroup(func() interface{} { + group := NewGroup(func() any { fmt.Println("Only Once") return &Counter{} }) @@ -26,12 +26,12 @@ func ExampleGroup_Get() { } func ExampleGroup_Reset() { - group := NewGroup(func() interface{} { + group := NewGroup(func() any { return &Counter{} }) // Reset the new function and clear all created objects. - group.Reset(func() interface{} { + group.Reset(func() any { fmt.Println("reset") return &Counter{} }) diff --git a/internal/group/group.go b/internal/group/group.go index c97496d14..04340e371 100644 --- a/internal/group/group.go +++ b/internal/group/group.go @@ -7,24 +7,24 @@ import "sync" // Group is a lazy load container. type Group struct { - new func() interface{} - vals map[string]interface{} + new func() any + vals map[string]any sync.RWMutex } // NewGroup news a group container. -func NewGroup(new func() interface{}) *Group { +func NewGroup(new func() any) *Group { if new == nil { panic("container.group: can't assign a nil to the new function") } return &Group{ new: new, - vals: make(map[string]interface{}), + vals: make(map[string]any), } } // Get gets the object by the given key. -func (g *Group) Get(key string) interface{} { +func (g *Group) Get(key string) any { g.RLock() v, ok := g.vals[key] if ok { @@ -46,7 +46,7 @@ func (g *Group) Get(key string) interface{} { } // Reset resets the new function and deletes all existing objects. -func (g *Group) Reset(new func() interface{}) { +func (g *Group) Reset(new func() any) { if new == nil { panic("container.group: can't assign a nil to the new function") } @@ -59,6 +59,6 @@ func (g *Group) Reset(new func() interface{}) { // Clear deletes all objects. func (g *Group) Clear() { g.Lock() - g.vals = make(map[string]interface{}) + g.vals = make(map[string]any) g.Unlock() } diff --git a/internal/group/group_test.go b/internal/group/group_test.go index 8ce2276e1..53a973da5 100644 --- a/internal/group/group_test.go +++ b/internal/group/group_test.go @@ -7,7 +7,7 @@ import ( func TestGroupGet(t *testing.T) { count := 0 - g := NewGroup(func() interface{} { + g := NewGroup(func() any { count++ return count }) @@ -31,12 +31,12 @@ func TestGroupGet(t *testing.T) { } func TestGroupReset(t *testing.T) { - g := NewGroup(func() interface{} { + g := NewGroup(func() any { return 1 }) g.Get("key") call := false - g.Reset(func() interface{} { + g.Reset(func() any { call = true return 1 }) @@ -56,7 +56,7 @@ func TestGroupReset(t *testing.T) { } func TestGroupClear(t *testing.T) { - g := NewGroup(func() interface{} { + g := NewGroup(func() any { return 1 }) g.Get("key") diff --git a/internal/matcher/middleware_test.go b/internal/matcher/middleware_test.go index 20575768d..0d25cf6d1 100644 --- a/internal/matcher/middleware_test.go +++ b/internal/matcher/middleware_test.go @@ -9,7 +9,7 @@ import ( func logging(module string) middleware.Middleware { return func(middleware.Handler) middleware.Handler { - return func(context.Context, interface{}) (reply interface{}, err error) { + return func(context.Context, any) (reply any, err error) { return module, nil } } diff --git a/log/filter.go b/log/filter.go index 993fa926e..d08421a67 100644 --- a/log/filter.go +++ b/log/filter.go @@ -31,7 +31,7 @@ func FilterValue(value ...string) FilterOption { } // FilterFunc with filter func. -func FilterFunc(f func(level Level, keyvals ...interface{}) bool) FilterOption { +func FilterFunc(f func(level Level, keyvals ...any) bool) FilterOption { return func(o *Filter) { o.filter = f } @@ -41,17 +41,17 @@ func FilterFunc(f func(level Level, keyvals ...interface{}) bool) FilterOption { type Filter struct { logger Logger level Level - key map[interface{}]struct{} - value map[interface{}]struct{} - filter func(level Level, keyvals ...interface{}) bool + key map[any]struct{} + value map[any]struct{} + filter func(level Level, keyvals ...any) bool } // NewFilter new a logger filter. func NewFilter(logger Logger, opts ...FilterOption) *Filter { options := Filter{ logger: logger, - key: make(map[interface{}]struct{}), - value: make(map[interface{}]struct{}), + key: make(map[any]struct{}), + value: make(map[any]struct{}), } for _, o := range opts { o(&options) @@ -60,15 +60,15 @@ func NewFilter(logger Logger, opts ...FilterOption) *Filter { } // Log Print log by level and keyvals. -func (f *Filter) Log(level Level, keyvals ...interface{}) error { +func (f *Filter) Log(level Level, keyvals ...any) error { if level < f.level { return nil } // prefixkv contains the slice of arguments defined as prefixes during the log initialization - var prefixkv []interface{} + var prefixkv []any l, ok := f.logger.(*logger) if ok && len(l.prefix) > 0 { - prefixkv = make([]interface{}, 0, len(l.prefix)) + prefixkv = make([]any, 0, len(l.prefix)) prefixkv = append(prefixkv, l.prefix...) } diff --git a/log/filter_test.go b/log/filter_test.go index 91133c1b7..e2188e975 100644 --- a/log/filter_test.go +++ b/log/filter_test.go @@ -83,7 +83,7 @@ func BenchmarkFilterFunc(b *testing.B) { } } -func testFilterFunc(level Level, keyvals ...interface{}) bool { +func testFilterFunc(level Level, keyvals ...any) bool { if level == LevelWarn { return true } @@ -130,7 +130,7 @@ func TestFilterFuncWitchLoggerPrefix(t *testing.T) { } } -func testFilterFuncWithLoggerPrefix(level Level, keyvals ...interface{}) bool { +func testFilterFuncWithLoggerPrefix(level Level, keyvals ...any) bool { if level == LevelWarn { return true } @@ -153,7 +153,7 @@ func TestFilterWithContext(t *testing.T) { ctxValue := "filter test value" v1 := func() Valuer { - return func(ctx context.Context) interface{} { + return func(ctx context.Context) any { return ctx.Value(ctxKey) } } diff --git a/log/global.go b/log/global.go index ae9244dff..76c655157 100644 --- a/log/global.go +++ b/log/global.go @@ -41,7 +41,7 @@ func GetLogger() Logger { } // Log Print log by level and keyvals. -func Log(level Level, keyvals ...interface{}) { +func Log(level Level, keyvals ...any) { _ = global.Log(level, keyvals...) } @@ -51,79 +51,79 @@ func Context(ctx context.Context) *Helper { } // Debug logs a message at debug level. -func Debug(a ...interface{}) { +func Debug(a ...any) { _ = global.Log(LevelDebug, DefaultMessageKey, fmt.Sprint(a...)) } // Debugf logs a message at debug level. -func Debugf(format string, a ...interface{}) { +func Debugf(format string, a ...any) { _ = global.Log(LevelDebug, DefaultMessageKey, fmt.Sprintf(format, a...)) } // Debugw logs a message at debug level. -func Debugw(keyvals ...interface{}) { +func Debugw(keyvals ...any) { _ = global.Log(LevelDebug, keyvals...) } // Info logs a message at info level. -func Info(a ...interface{}) { +func Info(a ...any) { _ = global.Log(LevelInfo, DefaultMessageKey, fmt.Sprint(a...)) } // Infof logs a message at info level. -func Infof(format string, a ...interface{}) { +func Infof(format string, a ...any) { _ = global.Log(LevelInfo, DefaultMessageKey, fmt.Sprintf(format, a...)) } // Infow logs a message at info level. -func Infow(keyvals ...interface{}) { +func Infow(keyvals ...any) { _ = global.Log(LevelInfo, keyvals...) } // Warn logs a message at warn level. -func Warn(a ...interface{}) { +func Warn(a ...any) { _ = global.Log(LevelWarn, DefaultMessageKey, fmt.Sprint(a...)) } // Warnf logs a message at warnf level. -func Warnf(format string, a ...interface{}) { +func Warnf(format string, a ...any) { _ = global.Log(LevelWarn, DefaultMessageKey, fmt.Sprintf(format, a...)) } // Warnw logs a message at warnf level. -func Warnw(keyvals ...interface{}) { +func Warnw(keyvals ...any) { _ = global.Log(LevelWarn, keyvals...) } // Error logs a message at error level. -func Error(a ...interface{}) { +func Error(a ...any) { _ = global.Log(LevelError, DefaultMessageKey, fmt.Sprint(a...)) } // Errorf logs a message at error level. -func Errorf(format string, a ...interface{}) { +func Errorf(format string, a ...any) { _ = global.Log(LevelError, DefaultMessageKey, fmt.Sprintf(format, a...)) } // Errorw logs a message at error level. -func Errorw(keyvals ...interface{}) { +func Errorw(keyvals ...any) { _ = global.Log(LevelError, keyvals...) } // Fatal logs a message at fatal level. -func Fatal(a ...interface{}) { +func Fatal(a ...any) { _ = global.Log(LevelFatal, DefaultMessageKey, fmt.Sprint(a...)) os.Exit(1) } // Fatalf logs a message at fatal level. -func Fatalf(format string, a ...interface{}) { +func Fatalf(format string, a ...any) { _ = global.Log(LevelFatal, DefaultMessageKey, fmt.Sprintf(format, a...)) os.Exit(1) } // Fatalw logs a message at fatal level. -func Fatalw(keyvals ...interface{}) { +func Fatalw(keyvals ...any) { _ = global.Log(LevelFatal, keyvals...) os.Exit(1) } diff --git a/log/global_test.go b/log/global_test.go index 469fae311..bbcdbec85 100644 --- a/log/global_test.go +++ b/log/global_test.go @@ -20,31 +20,31 @@ func TestGlobalLog(t *testing.T) { testCases := []struct { level Level - content []interface{} + content []any }{ { LevelDebug, - []interface{}{"test debug"}, + []any{"test debug"}, }, { LevelInfo, - []interface{}{"test info"}, + []any{"test info"}, }, { LevelInfo, - []interface{}{"test %s", "info"}, + []any{"test %s", "info"}, }, { LevelWarn, - []interface{}{"test warn"}, + []any{"test warn"}, }, { LevelError, - []interface{}{"test error"}, + []any{"test error"}, }, { LevelError, - []interface{}{"test %s", "error"}, + []any{"test %s", "error"}, }, } @@ -123,7 +123,7 @@ func TestContextWithGlobalLog(t *testing.T) { type traceKey struct{} // set "trace-id" Valuer - newLogger := With(NewStdLogger(buffer), "trace-id", Valuer(func(ctx context.Context) interface{} { + newLogger := With(NewStdLogger(buffer), "trace-id", Valuer(func(ctx context.Context) any { return ctx.Value(traceKey{}) })) diff --git a/log/helper.go b/log/helper.go index 7eb5b25de..3c10ce889 100644 --- a/log/helper.go +++ b/log/helper.go @@ -16,8 +16,8 @@ type Option func(*Helper) type Helper struct { logger Logger msgKey string - sprint func(...interface{}) string - sprintf func(format string, a ...interface{}) string + sprint func(...any) string + sprintf func(format string, a ...any) string } // WithMessageKey with message key. @@ -28,14 +28,14 @@ func WithMessageKey(k string) Option { } // WithSprint with sprint -func WithSprint(sprint func(...interface{}) string) Option { +func WithSprint(sprint func(...any) string) Option { return func(opts *Helper) { opts.sprint = sprint } } // WithSprintf with sprintf -func WithSprintf(sprintf func(format string, a ...interface{}) string) Option { +func WithSprintf(sprintf func(format string, a ...any) string) Option { return func(opts *Helper) { opts.sprintf = sprintf } @@ -81,12 +81,12 @@ func (h *Helper) Logger() Logger { } // Log Print log by level and keyvals. -func (h *Helper) Log(level Level, keyvals ...interface{}) { +func (h *Helper) Log(level Level, keyvals ...any) { _ = h.logger.Log(level, keyvals...) } // Debug logs a message at debug level. -func (h *Helper) Debug(a ...interface{}) { +func (h *Helper) Debug(a ...any) { if !h.Enabled(LevelDebug) { return } @@ -94,7 +94,7 @@ func (h *Helper) Debug(a ...interface{}) { } // Debugf logs a message at debug level. -func (h *Helper) Debugf(format string, a ...interface{}) { +func (h *Helper) Debugf(format string, a ...any) { if !h.Enabled(LevelDebug) { return } @@ -102,12 +102,12 @@ func (h *Helper) Debugf(format string, a ...interface{}) { } // Debugw logs a message at debug level. -func (h *Helper) Debugw(keyvals ...interface{}) { +func (h *Helper) Debugw(keyvals ...any) { _ = h.logger.Log(LevelDebug, keyvals...) } // Info logs a message at info level. -func (h *Helper) Info(a ...interface{}) { +func (h *Helper) Info(a ...any) { if !h.Enabled(LevelInfo) { return } @@ -115,7 +115,7 @@ func (h *Helper) Info(a ...interface{}) { } // Infof logs a message at info level. -func (h *Helper) Infof(format string, a ...interface{}) { +func (h *Helper) Infof(format string, a ...any) { if !h.Enabled(LevelInfo) { return } @@ -123,12 +123,12 @@ func (h *Helper) Infof(format string, a ...interface{}) { } // Infow logs a message at info level. -func (h *Helper) Infow(keyvals ...interface{}) { +func (h *Helper) Infow(keyvals ...any) { _ = h.logger.Log(LevelInfo, keyvals...) } // Warn logs a message at warn level. -func (h *Helper) Warn(a ...interface{}) { +func (h *Helper) Warn(a ...any) { if !h.Enabled(LevelWarn) { return } @@ -136,7 +136,7 @@ func (h *Helper) Warn(a ...interface{}) { } // Warnf logs a message at warnf level. -func (h *Helper) Warnf(format string, a ...interface{}) { +func (h *Helper) Warnf(format string, a ...any) { if !h.Enabled(LevelWarn) { return } @@ -144,12 +144,12 @@ func (h *Helper) Warnf(format string, a ...interface{}) { } // Warnw logs a message at warnf level. -func (h *Helper) Warnw(keyvals ...interface{}) { +func (h *Helper) Warnw(keyvals ...any) { _ = h.logger.Log(LevelWarn, keyvals...) } // Error logs a message at error level. -func (h *Helper) Error(a ...interface{}) { +func (h *Helper) Error(a ...any) { if !h.Enabled(LevelError) { return } @@ -157,7 +157,7 @@ func (h *Helper) Error(a ...interface{}) { } // Errorf logs a message at error level. -func (h *Helper) Errorf(format string, a ...interface{}) { +func (h *Helper) Errorf(format string, a ...any) { if !h.Enabled(LevelError) { return } @@ -165,24 +165,24 @@ func (h *Helper) Errorf(format string, a ...interface{}) { } // Errorw logs a message at error level. -func (h *Helper) Errorw(keyvals ...interface{}) { +func (h *Helper) Errorw(keyvals ...any) { _ = h.logger.Log(LevelError, keyvals...) } // Fatal logs a message at fatal level. -func (h *Helper) Fatal(a ...interface{}) { +func (h *Helper) Fatal(a ...any) { _ = h.logger.Log(LevelFatal, h.msgKey, h.sprint(a...)) os.Exit(1) } // Fatalf logs a message at fatal level. -func (h *Helper) Fatalf(format string, a ...interface{}) { +func (h *Helper) Fatalf(format string, a ...any) { _ = h.logger.Log(LevelFatal, h.msgKey, h.sprintf(format, a...)) os.Exit(1) } // Fatalw logs a message at fatal level. -func (h *Helper) Fatalw(keyvals ...interface{}) { +func (h *Helper) Fatalw(keyvals ...any) { _ = h.logger.Log(LevelFatal, keyvals...) os.Exit(1) } diff --git a/log/helper_test.go b/log/helper_test.go index c056fd88a..8687a8acc 100644 --- a/log/helper_test.go +++ b/log/helper_test.go @@ -97,7 +97,7 @@ func TestContext(_ *testing.T) { } func Trace() Valuer { - return func(ctx context.Context) interface{} { + return func(ctx context.Context) any { s, ok := ctx.Value(traceKey{}).(string) if !ok { return nil diff --git a/log/log.go b/log/log.go index b3c34d37c..13628d0ca 100644 --- a/log/log.go +++ b/log/log.go @@ -10,18 +10,18 @@ var DefaultLogger = NewStdLogger(log.Writer()) // Logger is a logger interface. type Logger interface { - Log(level Level, keyvals ...interface{}) error + Log(level Level, keyvals ...any) error } type logger struct { logger Logger - prefix []interface{} + prefix []any hasValuer bool ctx context.Context } -func (c *logger) Log(level Level, keyvals ...interface{}) error { - kvs := make([]interface{}, 0, len(c.prefix)+len(keyvals)) +func (c *logger) Log(level Level, keyvals ...any) error { + kvs := make([]any, 0, len(c.prefix)+len(keyvals)) kvs = append(kvs, c.prefix...) if c.hasValuer { bindValues(c.ctx, kvs) @@ -31,12 +31,12 @@ func (c *logger) Log(level Level, keyvals ...interface{}) error { } // With with logger fields. -func With(l Logger, kv ...interface{}) Logger { +func With(l Logger, kv ...any) Logger { c, ok := l.(*logger) if !ok { return &logger{logger: l, prefix: kv, hasValuer: containsValuer(kv), ctx: context.Background()} } - kvs := make([]interface{}, 0, len(c.prefix)+len(kv)) + kvs := make([]any, 0, len(c.prefix)+len(kv)) kvs = append(kvs, c.prefix...) kvs = append(kvs, kv...) return &logger{ diff --git a/log/std.go b/log/std.go index 24ee6acbc..4b2e0a4f7 100644 --- a/log/std.go +++ b/log/std.go @@ -24,7 +24,7 @@ func NewStdLogger(w io.Writer) Logger { w: w, isDiscard: w == io.Discard, pool: &sync.Pool{ - New: func() interface{} { + New: func() any { return new(bytes.Buffer) }, }, @@ -32,7 +32,7 @@ func NewStdLogger(w io.Writer) Logger { } // Log print the kv pairs log. -func (l *stdLogger) Log(level Level, keyvals ...interface{}) error { +func (l *stdLogger) Log(level Level, keyvals ...any) error { if l.isDiscard || len(keyvals) == 0 { return nil } diff --git a/log/value.go b/log/value.go index 66f0b81c0..b2a14fab8 100644 --- a/log/value.go +++ b/log/value.go @@ -17,10 +17,10 @@ var ( ) // Valuer is returns a log value. -type Valuer func(ctx context.Context) interface{} +type Valuer func(ctx context.Context) any // Value return the function value. -func Value(ctx context.Context, v interface{}) interface{} { +func Value(ctx context.Context, v any) any { if v, ok := v.(Valuer); ok { return v(ctx) } @@ -29,7 +29,7 @@ func Value(ctx context.Context, v interface{}) interface{} { // Caller returns a Valuer that returns a pkg/file:line description of the caller. func Caller(depth int) Valuer { - return func(context.Context) interface{} { + return func(context.Context) any { _, file, line, _ := runtime.Caller(depth) idx := strings.LastIndexByte(file, '/') if idx == -1 { @@ -42,12 +42,12 @@ func Caller(depth int) Valuer { // Timestamp returns a timestamp Valuer with a custom time format. func Timestamp(layout string) Valuer { - return func(context.Context) interface{} { + return func(context.Context) any { return time.Now().Format(layout) } } -func bindValues(ctx context.Context, keyvals []interface{}) { +func bindValues(ctx context.Context, keyvals []any) { for i := 1; i < len(keyvals); i += 2 { if v, ok := keyvals[i].(Valuer); ok { keyvals[i] = v(ctx) @@ -55,7 +55,7 @@ func bindValues(ctx context.Context, keyvals []interface{}) { } } -func containsValuer(keyvals []interface{}) bool { +func containsValuer(keyvals []any) bool { for i := 1; i < len(keyvals); i += 2 { if _, ok := keyvals[i].(Valuer); ok { return true diff --git a/log/value_test.go b/log/value_test.go index defbbf74f..780b1bf50 100644 --- a/log/value_test.go +++ b/log/value_test.go @@ -14,12 +14,12 @@ func TestValue(t *testing.T) { logger = With(logger) _ = logger.Log(LevelDebug, "msg", "helloworld") - var v1 interface{} + var v1 any got := Value(context.Background(), v1) if got != v1 { t.Errorf("Value() = %v, want %v", got, v1) } - var v2 Valuer = func(context.Context) interface{} { + var v2 Valuer = func(context.Context) any { return 3 } got = Value(context.Background(), v2) diff --git a/middleware/auth/jwt/jwt.go b/middleware/auth/jwt/jwt.go index 62e05e230..d39ec8029 100644 --- a/middleware/auth/jwt/jwt.go +++ b/middleware/auth/jwt/jwt.go @@ -49,7 +49,7 @@ type Option func(*options) type options struct { signingMethod jwt.SigningMethod claims func() jwt.Claims - tokenHeader map[string]interface{} + tokenHeader map[string]any } // WithSigningMethod with signing method option. @@ -69,7 +69,7 @@ func WithClaims(f func() jwt.Claims) Option { } // WithTokenHeader withe customer tokenHeader for client side -func WithTokenHeader(header map[string]interface{}) Option { +func WithTokenHeader(header map[string]any) Option { return func(o *options) { o.tokenHeader = header } @@ -84,7 +84,7 @@ func Server(keyFunc jwt.Keyfunc, opts ...Option) middleware.Middleware { opt(o) } return func(handler middleware.Handler) middleware.Handler { - return func(ctx context.Context, req interface{}) (interface{}, error) { + return func(ctx context.Context, req any) (any, error) { if header, ok := transport.FromServerContext(ctx); ok { if keyFunc == nil { return nil, ErrMissingKeyFunc @@ -138,7 +138,7 @@ func Client(keyProvider jwt.Keyfunc, opts ...Option) middleware.Middleware { opt(o) } return func(handler middleware.Handler) middleware.Handler { - return func(ctx context.Context, req interface{}) (interface{}, error) { + return func(ctx context.Context, req any) (any, error) { if keyProvider == nil { return nil, ErrNeedTokenProvider } diff --git a/middleware/auth/jwt/jwt_test.go b/middleware/auth/jwt/jwt_test.go index 84a558e23..314f681c1 100644 --- a/middleware/auth/jwt/jwt_test.go +++ b/middleware/auth/jwt/jwt_test.go @@ -129,7 +129,7 @@ func TestJWTServerParse(t *testing.T) { }, } - next := func(ctx context.Context, _ interface{}) (interface{}, error) { + next := func(ctx context.Context, _ any) (any, error) { testToken, _ := FromContext(ctx) var name string if customerClaims, ok := testToken.(*CustomerClaims); ok { @@ -154,7 +154,7 @@ func TestJWTServerParse(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { server := Server( - func(*jwt.Token) (interface{}, error) { return []byte(testKey), nil }, + func(*jwt.Token) (any, error) { return []byte(testKey), nil }, WithClaims(test.claims), )(next) wg := sync.WaitGroup{} @@ -240,18 +240,18 @@ func TestServer(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { var testToken jwt.Claims - next := func(ctx context.Context, req interface{}) (interface{}, error) { + next := func(ctx context.Context, req any) (any, error) { t.Log(req) testToken, _ = FromContext(ctx) return "reply", nil } var server middleware.Handler if test.signingMethod != nil { - server = Server(func(*jwt.Token) (interface{}, error) { + server = Server(func(*jwt.Token) (any, error) { return []byte(test.key), nil }, WithSigningMethod(test.signingMethod))(next) } else { - server = Server(func(*jwt.Token) (interface{}, error) { + server = Server(func(*jwt.Token) (any, error) { return []byte(test.key), nil })(next) } @@ -280,7 +280,7 @@ func TestClient(t *testing.T) { if err != nil { panic(err) } - tProvider := func(*jwt.Token) (interface{}, error) { + tProvider := func(*jwt.Token) (any, error) { return []byte(testKey), nil } tests := []struct { @@ -301,7 +301,7 @@ func TestClient(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - next := func(context.Context, any) (interface{}, error) { + next := func(context.Context, any) (any, error) { return "reply", nil } handler := Client(test.tokenProvider)(next) @@ -330,12 +330,12 @@ func TestTokenExpire(t *testing.T) { } token = fmt.Sprintf(bearerFormat, token) time.Sleep(time.Second) - next := func(_ context.Context, req interface{}) (interface{}, error) { + next := func(_ context.Context, req any) (any, error) { t.Log(req) return "reply", nil } ctx := transport.NewServerContext(context.Background(), &Transport{reqHeader: newTokenHeader(authorizationKey, token)}) - server := Server(func(*jwt.Token) (interface{}, error) { + server := Server(func(*jwt.Token) (any, error) { return []byte(testKey), nil }, WithSigningMethod(jwt.SigningMethodHS256))(next) _, err2 := server(ctx, "test expire token") @@ -369,7 +369,7 @@ func TestMissingKeyFunc(t *testing.T) { } var testToken jwt.Claims - next := func(ctx context.Context, req interface{}) (interface{}, error) { + next := func(ctx context.Context, req any) (any, error) { t.Log(req) testToken, _ = FromContext(ctx) return "reply", nil @@ -396,7 +396,7 @@ func TestClientWithClaims(t *testing.T) { if err != nil { panic(err) } - tProvider := func(*jwt.Token) (interface{}, error) { + tProvider := func(*jwt.Token) (any, error) { return []byte(testKey), nil } test := struct { @@ -410,7 +410,7 @@ func TestClientWithClaims(t *testing.T) { } t.Run(test.name, func(t *testing.T) { - next := func(context.Context, interface{}) (interface{}, error) { + next := func(context.Context, any) (any, error) { return "reply", nil } handler := Client(test.tokenProvider, WithClaims(mapClaimsFunc))(next) @@ -432,7 +432,7 @@ func TestClientWithHeader(t *testing.T) { mapClaims := jwt.MapClaims{} mapClaims["name"] = "xiaoli" mapClaimsFunc := func() jwt.Claims { return mapClaims } - tokenHeader := map[string]interface{}{ + tokenHeader := map[string]any{ "test": "test", } claims := jwt.NewWithClaims(jwt.SigningMethodHS256, mapClaims) @@ -443,10 +443,10 @@ func TestClientWithHeader(t *testing.T) { if err != nil { panic(err) } - tProvider := func(*jwt.Token) (interface{}, error) { + tProvider := func(*jwt.Token) (any, error) { return []byte(testKey), nil } - next := func(context.Context, interface{}) (interface{}, error) { + next := func(context.Context, any) (any, error) { return "reply", nil } handler := Client(tProvider, WithClaims(mapClaimsFunc), WithTokenHeader(tokenHeader))(next) @@ -470,7 +470,7 @@ func TestClientMissKey(t *testing.T) { if err != nil { panic(err) } - tProvider := func(*jwt.Token) (interface{}, error) { + tProvider := func(*jwt.Token) (any, error) { return nil, errors.New("some error") } test := struct { @@ -484,7 +484,7 @@ func TestClientMissKey(t *testing.T) { } t.Run(test.name, func(t *testing.T) { - next := func(context.Context, interface{}) (interface{}, error) { + next := func(context.Context, any) (any, error) { return "reply", nil } handler := Client(test.tokenProvider, WithClaims(mapClaimsFunc))(next) diff --git a/middleware/circuitbreaker/circuitbreaker.go b/middleware/circuitbreaker/circuitbreaker.go index 76f261fd2..33fc1fd06 100644 --- a/middleware/circuitbreaker/circuitbreaker.go +++ b/middleware/circuitbreaker/circuitbreaker.go @@ -29,7 +29,7 @@ func WithGroup(g *group.Group) Option { // WithCircuitBreaker with circuit breaker genFunc. func WithCircuitBreaker(genBreakerFunc func() circuitbreaker.CircuitBreaker) Option { return func(o *options) { - o.group = group.NewGroup(func() interface{} { + o.group = group.NewGroup(func() any { return genBreakerFunc() }) } @@ -43,7 +43,7 @@ type options struct { // breaker is triggered and the request is rejected directly. func Client(opts ...Option) middleware.Middleware { opt := &options{ - group: group.NewGroup(func() interface{} { + group: group.NewGroup(func() any { return sre.NewBreaker() }), } @@ -51,7 +51,7 @@ func Client(opts ...Option) middleware.Middleware { o(opt) } return func(handler middleware.Handler) middleware.Handler { - return func(ctx context.Context, req interface{}) (interface{}, error) { + return func(ctx context.Context, req any) (any, error) { info, _ := transport.FromClientContext(ctx) breaker := opt.group.Get(info.Operation()).(circuitbreaker.CircuitBreaker) if err := breaker.Allow(); err != nil { diff --git a/middleware/circuitbreaker/circuitbreaker_test.go b/middleware/circuitbreaker/circuitbreaker_test.go index 3daca9f24..01ce43b91 100644 --- a/middleware/circuitbreaker/circuitbreaker_test.go +++ b/middleware/circuitbreaker/circuitbreaker_test.go @@ -46,7 +46,7 @@ func (c *circuitBreakerMock) MarkFailed() {} func Test_WithGroup(t *testing.T) { o := options{ - group: group.NewGroup(func() interface{} { + group: group.NewGroup(func() any { return "" }), } @@ -58,17 +58,17 @@ func Test_WithGroup(t *testing.T) { } func TestServer(_ *testing.T) { - nextValid := func(context.Context, interface{}) (interface{}, error) { + nextValid := func(context.Context, any) (any, error) { return "Hello valid", nil } - nextInvalid := func(context.Context, interface{}) (interface{}, error) { + nextInvalid := func(context.Context, any) (any, error) { return nil, kratoserrors.InternalServer("", "") } ctx := transport.NewClientContext(context.Background(), &transportMock{}) _, _ = Client(func(o *options) { - o.group = group.NewGroup(func() interface{} { + o.group = group.NewGroup(func() any { return &circuitBreakerMock{err: errors.New("circuitbreaker error")} }) })(nextValid)(ctx, nil) diff --git a/middleware/logging/logging.go b/middleware/logging/logging.go index a4dff3386..4e67d00be 100644 --- a/middleware/logging/logging.go +++ b/middleware/logging/logging.go @@ -22,7 +22,7 @@ type Redacter interface { // Server is an server logging middleware. func Server(logger log.Logger) middleware.Middleware { return func(handler middleware.Handler) middleware.Handler { - return func(ctx context.Context, req interface{}) (reply interface{}, err error) { + return func(ctx context.Context, req any) (reply any, err error) { var ( code int32 reason string @@ -62,7 +62,7 @@ func Server(logger log.Logger) middleware.Middleware { // Client is a client logging middleware. func Client(logger log.Logger) middleware.Middleware { return func(handler middleware.Handler) middleware.Handler { - return func(ctx context.Context, req interface{}) (reply interface{}, err error) { + return func(ctx context.Context, req any) (reply any, err error) { var ( code int32 reason string @@ -100,7 +100,7 @@ func Client(logger log.Logger) middleware.Middleware { } // extractArgs returns the string of the req -func extractArgs(req interface{}) string { +func extractArgs(req any) string { if redacter, ok := req.(Redacter); ok { return redacter.Redact() } diff --git a/middleware/logging/logging_test.go b/middleware/logging/logging_test.go index 87e3959ab..4b01bc790 100644 --- a/middleware/logging/logging_test.go +++ b/middleware/logging/logging_test.go @@ -87,7 +87,7 @@ func TestHTTP(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { bf.Reset() - next := func(context.Context, interface{}) (interface{}, error) { + next := func(context.Context, any) (any, error) { return "reply", test.err } next = test.kind(logger)(next) @@ -125,7 +125,7 @@ func (d *dummyStringerRedacter) Redact() string { func TestExtractArgs(t *testing.T) { tests := []struct { name string - req interface{} + req any expected string }{ { diff --git a/middleware/metadata/metadata.go b/middleware/metadata/metadata.go index 30cb8df90..8380f3d74 100644 --- a/middleware/metadata/metadata.go +++ b/middleware/metadata/metadata.go @@ -50,7 +50,7 @@ func Server(opts ...Option) middleware.Middleware { o(options) } return func(handler middleware.Handler) middleware.Handler { - return func(ctx context.Context, req interface{}) (reply interface{}, err error) { + return func(ctx context.Context, req any) (reply any, err error) { tr, ok := transport.FromServerContext(ctx) if !ok { return handler(ctx, req) @@ -80,7 +80,7 @@ func Client(opts ...Option) middleware.Middleware { o(options) } return func(handler middleware.Handler) middleware.Handler { - return func(ctx context.Context, req interface{}) (reply interface{}, err error) { + return func(ctx context.Context, req any) (reply any, err error) { tr, ok := transport.FromClientContext(ctx) if !ok { return handler(ctx, req) diff --git a/middleware/metadata/metadata_test.go b/middleware/metadata/metadata_test.go index 9e9436d75..61bed510c 100644 --- a/middleware/metadata/metadata_test.go +++ b/middleware/metadata/metadata_test.go @@ -53,7 +53,7 @@ var ( ) func TestSever(t *testing.T) { - hs := func(ctx context.Context, in interface{}) (interface{}, error) { + hs := func(ctx context.Context, in any) (any, error) { md, ok := metadata.FromServerContext(ctx) if !ok { return nil, errors.New("no md") @@ -86,7 +86,7 @@ func TestSever(t *testing.T) { } func TestClient(t *testing.T) { - hs := func(ctx context.Context, in interface{}) (interface{}, error) { + hs := func(ctx context.Context, in any) (any, error) { tr, ok := transport.FromClientContext(ctx) if !ok { return nil, errors.New("no md") diff --git a/middleware/metrics/metrics.go b/middleware/metrics/metrics.go index 7a76c57ae..5cb1ff03b 100644 --- a/middleware/metrics/metrics.go +++ b/middleware/metrics/metrics.go @@ -105,7 +105,7 @@ func Server(opts ...Option) middleware.Middleware { o(&op) } return func(handler middleware.Handler) middleware.Handler { - return func(ctx context.Context, req interface{}) (interface{}, error) { + return func(ctx context.Context, req any) (any, error) { // if requests and seconds are nil, return directly if op.requests == nil && op.seconds == nil { return handler(ctx, req) @@ -163,7 +163,7 @@ func Client(opts ...Option) middleware.Middleware { o(&op) } return func(handler middleware.Handler) middleware.Handler { - return func(ctx context.Context, req interface{}) (interface{}, error) { + return func(ctx context.Context, req any) (any, error) { var ( code int reason string diff --git a/middleware/metrics/metrics_test.go b/middleware/metrics/metrics_test.go index 348fdaeee..11494fb38 100644 --- a/middleware/metrics/metrics_test.go +++ b/middleware/metrics/metrics_test.go @@ -139,10 +139,10 @@ func TestServer(t *testing.T) { defer span.End() e := errors.New("got an error") - nextError := func(context.Context, interface{}) (interface{}, error) { + nextError := func(context.Context, any) (any, error) { return nil, e } - nextValid := func(context.Context, interface{}) (interface{}, error) { + nextValid := func(context.Context, any) (any, error) { time.Sleep(time.Millisecond * time.Duration(rand.Int31n(100))) return "Hello valid", nil } @@ -201,10 +201,10 @@ func TestClient(t *testing.T) { defer span.End() e := errors.New("got an error") - nextError := func(context.Context, interface{}) (interface{}, error) { + nextError := func(context.Context, any) (any, error) { return nil, e } - nextValid := func(context.Context, interface{}) (interface{}, error) { + nextValid := func(context.Context, any) (any, error) { return "Hello valid", nil } diff --git a/middleware/middleware.go b/middleware/middleware.go index 8a514ad97..5568fb5a8 100644 --- a/middleware/middleware.go +++ b/middleware/middleware.go @@ -5,7 +5,7 @@ import ( ) // Handler defines the handler invoked by Middleware. -type Handler func(ctx context.Context, req interface{}) (interface{}, error) +type Handler func(ctx context.Context, req any) (any, error) // Middleware is HTTP/gRPC transport middleware. type Middleware func(Handler) Handler diff --git a/middleware/middleware_test.go b/middleware/middleware_test.go index 4714ff978..2218bbd5c 100644 --- a/middleware/middleware_test.go +++ b/middleware/middleware_test.go @@ -10,7 +10,7 @@ import ( var i int func TestChain(t *testing.T) { - next := func(_ context.Context, req interface{}) (interface{}, error) { + next := func(_ context.Context, req any) (any, error) { if req != "hello kratos!" { t.Errorf("expect %v, got %v", "hello kratos!", req) } @@ -31,7 +31,7 @@ func TestChain(t *testing.T) { } func test1Middleware(handler Handler) Handler { - return func(ctx context.Context, req interface{}) (reply interface{}, err error) { + return func(ctx context.Context, req any) (reply any, err error) { fmt.Println("test1 before") i++ reply, err = handler(ctx, req) @@ -41,7 +41,7 @@ func test1Middleware(handler Handler) Handler { } func test2Middleware(handler Handler) Handler { - return func(ctx context.Context, req interface{}) (reply interface{}, err error) { + return func(ctx context.Context, req any) (reply any, err error) { fmt.Println("test2 before") i += 2 reply, err = handler(ctx, req) @@ -51,7 +51,7 @@ func test2Middleware(handler Handler) Handler { } func test3Middleware(handler Handler) Handler { - return func(ctx context.Context, req interface{}) (reply interface{}, err error) { + return func(ctx context.Context, req any) (reply any, err error) { fmt.Println("test3 before") i += 3 reply, err = handler(ctx, req) diff --git a/middleware/ratelimit/ratelimit.go b/middleware/ratelimit/ratelimit.go index 23f217530..9439d62de 100644 --- a/middleware/ratelimit/ratelimit.go +++ b/middleware/ratelimit/ratelimit.go @@ -37,7 +37,7 @@ func Server(opts ...Option) middleware.Middleware { o(options) } return func(handler middleware.Handler) middleware.Handler { - return func(ctx context.Context, req interface{}) (reply interface{}, err error) { + return func(ctx context.Context, req any) (reply any, err error) { done, e := options.limiter.Allow() if e != nil { // rejected diff --git a/middleware/ratelimit/ratelimit_test.go b/middleware/ratelimit/ratelimit_test.go index 20cf9934d..9d837cfc7 100644 --- a/middleware/ratelimit/ratelimit_test.go +++ b/middleware/ratelimit/ratelimit_test.go @@ -41,7 +41,7 @@ func Test_WithLimiter(t *testing.T) { } func TestServer(t *testing.T) { - nextValid := func(context.Context, interface{}) (interface{}, error) { + nextValid := func(context.Context, any) (any, error) { return "Hello valid", nil } diff --git a/middleware/recovery/recovery.go b/middleware/recovery/recovery.go index 4c02820e4..c57267d4b 100644 --- a/middleware/recovery/recovery.go +++ b/middleware/recovery/recovery.go @@ -17,7 +17,7 @@ type Latency struct{} var ErrUnknownRequest = errors.InternalServer("UNKNOWN", "unknown request error") // HandlerFunc is recovery handler func. -type HandlerFunc func(ctx context.Context, req, err interface{}) error +type HandlerFunc func(ctx context.Context, req, err any) error // Option is recovery option. type Option func(*options) @@ -44,7 +44,7 @@ func Recovery(opts ...Option) middleware.Middleware { o(&op) } return func(handler middleware.Handler) middleware.Handler { - return func(ctx context.Context, req interface{}) (reply interface{}, err error) { + return func(ctx context.Context, req any) (reply any, err error) { startTime := time.Now() defer func() { if rerr := recover(); rerr != nil { diff --git a/middleware/recovery/recovery_test.go b/middleware/recovery/recovery_test.go index 915861a20..3a9712cd5 100644 --- a/middleware/recovery/recovery_test.go +++ b/middleware/recovery/recovery_test.go @@ -15,10 +15,10 @@ func TestOnce(t *testing.T) { } }() - next := func(context.Context, interface{}) (interface{}, error) { + next := func(context.Context, any) (any, error) { panic("panic reason") } - _, e := Recovery(WithHandler(func(ctx context.Context, _, err interface{}) error { + _, e := Recovery(WithHandler(func(ctx context.Context, _, err any) error { _, ok := ctx.Value(Latency{}).(float64) if !ok { t.Errorf("not latency") @@ -29,7 +29,7 @@ func TestOnce(t *testing.T) { } func TestNotPanic(t *testing.T) { - next := func(_ context.Context, req interface{}) (interface{}, error) { + next := func(_ context.Context, req any) (any, error) { return req.(string) + "https://go-kratos.dev", nil } diff --git a/middleware/selector/selector.go b/middleware/selector/selector.go index 9cbf520bb..10f2cc414 100644 --- a/middleware/selector/selector.go +++ b/middleware/selector/selector.go @@ -118,7 +118,7 @@ func (b *Builder) matches(ctx context.Context, transporter transporter) bool { // selector middleware func selector(transporter transporter, match func(context.Context, transporter) bool, ms ...middleware.Middleware) middleware.Middleware { return func(handler middleware.Handler) middleware.Handler { - return func(ctx context.Context, req interface{}) (reply interface{}, err error) { + return func(ctx context.Context, req any) (reply any, err error) { if !match(ctx, transporter) { return handler(ctx, req) } diff --git a/middleware/selector/selector_test.go b/middleware/selector/selector_test.go index 1769f7c0f..be26b8dd1 100644 --- a/middleware/selector/selector_test.go +++ b/middleware/selector/selector_test.go @@ -96,7 +96,7 @@ func TestMatch(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - next := func(_ context.Context, req interface{}) (interface{}, error) { + next := func(_ context.Context, req any) (any, error) { t.Log(req) return "reply", nil } @@ -132,7 +132,7 @@ func TestMatchClient(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - next := func(_ context.Context, req interface{}) (interface{}, error) { + next := func(_ context.Context, req any) (any, error) { t.Log(req) return "reply", nil } @@ -167,7 +167,7 @@ func TestFunc(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - next := func(_ context.Context, req interface{}) (interface{}, error) { + next := func(_ context.Context, req any) (any, error) { t.Log(req) return "reply", nil } @@ -224,7 +224,7 @@ func TestHeaderFunc(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - next := func(_ context.Context, req interface{}) (interface{}, error) { + next := func(_ context.Context, req any) (any, error) { t.Log(req) return "reply", nil } @@ -253,7 +253,7 @@ func TestHeaderFunc(t *testing.T) { } func testMiddleware(handler middleware.Handler) middleware.Handler { - return func(ctx context.Context, req interface{}) (reply interface{}, err error) { + return func(ctx context.Context, req any) (reply any, err error) { reply, err = handler(ctx, req) return } diff --git a/middleware/tracing/span.go b/middleware/tracing/span.go index 1fa241ec3..d25a8b387 100644 --- a/middleware/tracing/span.go +++ b/middleware/tracing/span.go @@ -17,7 +17,7 @@ import ( "google.golang.org/protobuf/proto" ) -func setClientSpan(ctx context.Context, span trace.Span, m interface{}) { +func setClientSpan(ctx context.Context, span trace.Span, m any) { var ( attrs []attribute.KeyValue remote string @@ -56,7 +56,7 @@ func setClientSpan(ctx context.Context, span trace.Span, m interface{}) { span.SetAttributes(attrs...) } -func setServerSpan(ctx context.Context, span trace.Span, m interface{}) { +func setServerSpan(ctx context.Context, span trace.Span, m any) { var ( attrs []attribute.KeyValue remote string diff --git a/middleware/tracing/tracer.go b/middleware/tracing/tracer.go index 67f1a2d95..ff4018577 100644 --- a/middleware/tracing/tracer.go +++ b/middleware/tracing/tracer.go @@ -60,7 +60,7 @@ func (t *Tracer) Start(ctx context.Context, operation string, carrier propagatio } // End finish tracing span -func (t *Tracer) End(_ context.Context, span trace.Span, m interface{}, err error) { +func (t *Tracer) End(_ context.Context, span trace.Span, m any, err error) { if err != nil { span.RecordError(err) if e := errors.FromError(err); e != nil { diff --git a/middleware/tracing/tracing.go b/middleware/tracing/tracing.go index 7d9b53a1b..e43903ad1 100644 --- a/middleware/tracing/tracing.go +++ b/middleware/tracing/tracing.go @@ -47,7 +47,7 @@ func WithTracerName(tracerName string) Option { func Server(opts ...Option) middleware.Middleware { tracer := NewTracer(trace.SpanKindServer, opts...) return func(handler middleware.Handler) middleware.Handler { - return func(ctx context.Context, req interface{}) (reply interface{}, err error) { + return func(ctx context.Context, req any) (reply any, err error) { if tr, ok := transport.FromServerContext(ctx); ok { var span trace.Span ctx, span = tracer.Start(ctx, tr.Operation(), tr.RequestHeader()) @@ -63,7 +63,7 @@ func Server(opts ...Option) middleware.Middleware { func Client(opts ...Option) middleware.Middleware { tracer := NewTracer(trace.SpanKindClient, opts...) return func(handler middleware.Handler) middleware.Handler { - return func(ctx context.Context, req interface{}) (reply interface{}, err error) { + return func(ctx context.Context, req any) (reply any, err error) { if tr, ok := transport.FromClientContext(ctx); ok { var span trace.Span ctx, span = tracer.Start(ctx, tr.Operation(), tr.RequestHeader()) @@ -77,7 +77,7 @@ func Client(opts ...Option) middleware.Middleware { // TraceID returns a traceid valuer. func TraceID() log.Valuer { - return func(ctx context.Context) interface{} { + return func(ctx context.Context) any { if span := trace.SpanContextFromContext(ctx); span.HasTraceID() { return span.TraceID().String() } @@ -87,7 +87,7 @@ func TraceID() log.Valuer { // SpanID returns a spanid valuer. func SpanID() log.Valuer { - return func(ctx context.Context) interface{} { + return func(ctx context.Context) any { if span := trace.SpanContextFromContext(ctx); span.HasSpanID() { return span.SpanID().String() } diff --git a/middleware/tracing/tracing_test.go b/middleware/tracing/tracing_test.go index fe9028028..4070daf7e 100644 --- a/middleware/tracing/tracing_test.go +++ b/middleware/tracing/tracing_test.go @@ -127,7 +127,7 @@ func TestServer(t *testing.T) { childSpanID string childTraceID string ) - next := func(ctx context.Context, req interface{}) (interface{}, error) { + next := func(ctx context.Context, req any) (any, error) { _ = log.WithContext(ctx, logger).Log(log.LevelInfo, "kind", "server", ) @@ -198,7 +198,7 @@ func TestClient(t *testing.T) { childSpanID string childTraceID string ) - next := func(ctx context.Context, req interface{}) (interface{}, error) { + next := func(ctx context.Context, req any) (any, error) { _ = log.WithContext(ctx, logger).Log(log.LevelInfo, "kind", "client", ) diff --git a/middleware/validate/validate.go b/middleware/validate/validate.go index 788a7ae4c..aa69bc808 100644 --- a/middleware/validate/validate.go +++ b/middleware/validate/validate.go @@ -16,7 +16,7 @@ type validator interface { // Deprecated: use github.com/go-kratos/kratos/contrib/middleware/validate/v2.ProtoValidate instead. func Validator() middleware.Middleware { return func(handler middleware.Handler) middleware.Handler { - return func(ctx context.Context, req interface{}) (reply interface{}, err error) { + return func(ctx context.Context, req any) (reply any, err error) { if v, ok := req.(validator); ok { if err := v.Validate(); err != nil { return nil, errors.BadRequest("VALIDATOR", err.Error()).WithCause(err) diff --git a/middleware/validate/validate_test.go b/middleware/validate/validate_test.go index 34bea3014..193524e2b 100644 --- a/middleware/validate/validate_test.go +++ b/middleware/validate/validate_test.go @@ -24,7 +24,7 @@ func (v protoVali) Validate() error { } func TestTable(t *testing.T) { - var mock middleware.Handler = func(context.Context, interface{}) (interface{}, error) { return nil, nil } + var mock middleware.Handler = func(context.Context, any) (any, error) { return nil, nil } tests := []protoVali{ {"v1", 365, false}, diff --git a/registry/registry.go b/registry/registry.go index 95d3123ac..381dbfb8a 100644 --- a/registry/registry.go +++ b/registry/registry.go @@ -55,7 +55,7 @@ func (i *ServiceInstance) String() string { } // Equal returns whether i and o are equivalent. -func (i *ServiceInstance) Equal(o interface{}) bool { +func (i *ServiceInstance) Equal(o any) bool { if i == nil && o == nil { return true } diff --git a/transport/grpc/client.go b/transport/grpc/client.go index 42ad5d724..8503ff6c3 100644 --- a/transport/grpc/client.go +++ b/transport/grpc/client.go @@ -208,7 +208,7 @@ func dial(ctx context.Context, insecure bool, opts ...ClientOption) (*grpc.Clien } func unaryClientInterceptor(ms []middleware.Middleware, timeout time.Duration, filters []selector.NodeFilter) grpc.UnaryClientInterceptor { - return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { + return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { ctx = transport.NewClientContext(ctx, &Transport{ endpoint: cc.Target(), operation: method, @@ -220,7 +220,7 @@ func unaryClientInterceptor(ms []middleware.Middleware, timeout time.Duration, f ctx, cancel = context.WithTimeout(ctx, timeout) defer cancel() } - h := func(ctx context.Context, req interface{}) (interface{}, error) { + h := func(ctx context.Context, req any) (any, error) { if tr, ok := transport.FromClientContext(ctx); ok { header := tr.RequestHeader() keys := header.Keys() @@ -253,8 +253,8 @@ func (w *wrappedClientStream) Context() context.Context { return w.ctx } -func (w *wrappedClientStream) SendMsg(m interface{}) error { - h := func(_ context.Context, req interface{}) (interface{}, error) { +func (w *wrappedClientStream) SendMsg(m any) error { + h := func(_ context.Context, req any) (any, error) { return req, w.ClientStream.SendMsg(m) } @@ -271,8 +271,8 @@ func (w *wrappedClientStream) SendMsg(m interface{}) error { return err } -func (w *wrappedClientStream) RecvMsg(m interface{}) error { - h := func(_ context.Context, req interface{}) (interface{}, error) { +func (w *wrappedClientStream) RecvMsg(m any) error { + h := func(_ context.Context, req any) (any, error) { return req, w.ClientStream.RecvMsg(m) } @@ -305,7 +305,7 @@ func streamClientInterceptor(ms []middleware.Middleware, filters []selector.Node return nil, err } - h := func(_ context.Context, _ interface{}) (interface{}, error) { + h := func(_ context.Context, _ any) (any, error) { return streamer, nil } diff --git a/transport/grpc/client_test.go b/transport/grpc/client_test.go index cdbee6007..b49794a11 100644 --- a/transport/grpc/client_test.go +++ b/transport/grpc/client_test.go @@ -72,7 +72,7 @@ func TestWithTLSConfig(t *testing.T) { func EmptyMiddleware() middleware.Middleware { return func(handler middleware.Handler) middleware.Handler { - return func(ctx context.Context, req interface{}) (reply interface{}, err error) { + return func(ctx context.Context, req any) (reply any, err error) { return handler(ctx, req) } } diff --git a/transport/grpc/codec.go b/transport/grpc/codec.go index 231f114f8..b88295887 100644 --- a/transport/grpc/codec.go +++ b/transport/grpc/codec.go @@ -17,7 +17,7 @@ func init() { // codec is a Codec implementation with protobuf. It is the default codec for gRPC. type codec struct{} -func (codec) Marshal(v interface{}) ([]byte, error) { +func (codec) Marshal(v any) ([]byte, error) { vv, ok := v.(proto.Message) if !ok { return nil, fmt.Errorf("failed to marshal, message is %T, want proto.Message", v) @@ -25,7 +25,7 @@ func (codec) Marshal(v interface{}) ([]byte, error) { return enc.GetCodec(json.Name).Marshal(vv) } -func (codec) Unmarshal(data []byte, v interface{}) error { +func (codec) Unmarshal(data []byte, v any) error { vv, ok := v.(proto.Message) if !ok { return fmt.Errorf("failed to unmarshal, message is %T, want proto.Message", v) diff --git a/transport/grpc/codec_test.go b/transport/grpc/codec_test.go index 534439ff9..5d4c17f91 100644 --- a/transport/grpc/codec_test.go +++ b/transport/grpc/codec_test.go @@ -8,7 +8,7 @@ import ( ) func TestCodec(t *testing.T) { - in, err := structpb.NewStruct(map[string]interface{}{"Golang": "Kratos"}) + in, err := structpb.NewStruct(map[string]any{"Golang": "Kratos"}) if err != nil { t.Errorf("grpc codec create input data error:%v", err) } diff --git a/transport/grpc/interceptor.go b/transport/grpc/interceptor.go index f84b4bcfc..cde508cd3 100644 --- a/transport/grpc/interceptor.go +++ b/transport/grpc/interceptor.go @@ -15,7 +15,7 @@ import ( // unaryServerInterceptor is a gRPC unary server interceptor func (s *Server) unaryServerInterceptor() grpc.UnaryServerInterceptor { - return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { + return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { ctx, cancel := ic.Merge(ctx, s.baseCtx) defer cancel() md, _ := grpcmd.FromIncomingContext(ctx) @@ -33,7 +33,7 @@ func (s *Server) unaryServerInterceptor() grpc.UnaryServerInterceptor { ctx, cancel = context.WithTimeout(ctx, s.timeout) defer cancel() } - h := func(ctx context.Context, req interface{}) (interface{}, error) { + h := func(ctx context.Context, req any) (any, error) { return handler(ctx, req) } if next := s.middleware.Match(tr.Operation()); len(next) > 0 { @@ -68,7 +68,7 @@ func (w *wrappedStream) Context() context.Context { // streamServerInterceptor is a gRPC stream server interceptor func (s *Server) streamServerInterceptor() grpc.StreamServerInterceptor { - return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { ctx, cancel := ic.Merge(ss.Context(), s.baseCtx) defer cancel() md, _ := grpcmd.FromIncomingContext(ctx) @@ -80,7 +80,7 @@ func (s *Server) streamServerInterceptor() grpc.StreamServerInterceptor { replyHeader: headerCarrier(replyHeader), }) - h := func(_ context.Context, _ interface{}) (interface{}, error) { + h := func(_ context.Context, _ any) (any, error) { return handler(srv, ss), nil } @@ -111,8 +111,8 @@ func GetStream(ctx context.Context) grpc.ServerStream { return ctx.Value(stream{}).(grpc.ServerStream) } -func (w *wrappedStream) SendMsg(m interface{}) error { - h := func(_ context.Context, req interface{}) (interface{}, error) { +func (w *wrappedStream) SendMsg(m any) error { + h := func(_ context.Context, req any) (any, error) { return req, w.ServerStream.SendMsg(m) } @@ -129,8 +129,8 @@ func (w *wrappedStream) SendMsg(m interface{}) error { return err } -func (w *wrappedStream) RecvMsg(m interface{}) error { - h := func(_ context.Context, req interface{}) (interface{}, error) { +func (w *wrappedStream) RecvMsg(m any) error { + h := func(_ context.Context, req any) (any, error) { return req, w.ServerStream.RecvMsg(m) } diff --git a/transport/grpc/server_test.go b/transport/grpc/server_test.go index 382709227..8932eb349 100644 --- a/transport/grpc/server_test.go +++ b/transport/grpc/server_test.go @@ -78,7 +78,7 @@ func TestServer(t *testing.T) { srv := NewServer( Middleware( func(handler middleware.Handler) middleware.Handler { - return func(ctx context.Context, req interface{}) (reply interface{}, err error) { + return func(ctx context.Context, req any) (reply any, err error) { if tr, ok := transport.FromServerContext(ctx); ok { if tr.ReplyHeader() != nil { tr.ReplyHeader().Set("req_id", "3344") @@ -87,7 +87,7 @@ func TestServer(t *testing.T) { return handler(ctx, req) } }), - UnaryInterceptor(func(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { + UnaryInterceptor(func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { return handler(ctx, req) }), Options(grpc.InitialConnWindowSize(0)), @@ -119,11 +119,11 @@ func testClient(t *testing.T, srv *Server) { WithEndpoint(u.Host), WithOptions(grpc.WithBlock()), WithUnaryInterceptor( - func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { + func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { return invoker(ctx, method, req, reply, cc, opts...) }), WithMiddleware(func(handler middleware.Handler) middleware.Handler { - return func(ctx context.Context, req interface{}) (reply interface{}, err error) { + return func(ctx context.Context, req any) (reply any, err error) { if tr, ok := transport.FromClientContext(ctx); ok { header := tr.RequestHeader() header.Set("x-md-trace", "2233") @@ -216,10 +216,10 @@ func TestTLSConfig(t *testing.T) { func TestUnaryInterceptor(t *testing.T) { o := &Server{} v := []grpc.UnaryServerInterceptor{ - func(context.Context, interface{}, *grpc.UnaryServerInfo, grpc.UnaryHandler) (resp interface{}, err error) { + func(context.Context, any, *grpc.UnaryServerInfo, grpc.UnaryHandler) (resp any, err error) { return nil, nil }, - func(context.Context, interface{}, *grpc.UnaryServerInfo, grpc.UnaryHandler) (resp interface{}, err error) { + func(context.Context, any, *grpc.UnaryServerInfo, grpc.UnaryHandler) (resp any, err error) { return nil, nil }, } @@ -232,10 +232,10 @@ func TestUnaryInterceptor(t *testing.T) { func TestStreamInterceptor(t *testing.T) { o := &Server{} v := []grpc.StreamServerInterceptor{ - func(interface{}, grpc.ServerStream, *grpc.StreamServerInfo, grpc.StreamHandler) error { + func(any, grpc.ServerStream, *grpc.StreamServerInfo, grpc.StreamHandler) error { return nil }, - func(interface{}, grpc.ServerStream, *grpc.StreamServerInfo, grpc.StreamHandler) error { + func(any, grpc.ServerStream, *grpc.StreamServerInfo, grpc.StreamHandler) error { return nil }, } @@ -273,7 +273,7 @@ func TestServer_unaryServerInterceptor(t *testing.T) { } srv.middleware.Use(EmptyMiddleware()) req := &struct{}{} - rv, err := srv.unaryServerInterceptor()(context.TODO(), req, &grpc.UnaryServerInfo{}, func(context.Context, interface{}) (interface{}, error) { + rv, err := srv.unaryServerInterceptor()(context.TODO(), req, &grpc.UnaryServerInfo{}, func(context.Context, any) (any, error) { return &testResp{Data: "hi"}, nil }) if err != nil { @@ -286,8 +286,8 @@ func TestServer_unaryServerInterceptor(t *testing.T) { type mockServerStream struct { ctx context.Context - sentMsg interface{} - recvMsg interface{} + sentMsg any + recvMsg any metadata metadata.MD grpc.ServerStream } @@ -310,12 +310,12 @@ func (m *mockServerStream) Context() context.Context { return m.ctx } -func (m *mockServerStream) SendMsg(msg interface{}) error { +func (m *mockServerStream) SendMsg(msg any) error { m.sentMsg = msg return nil } -func (m *mockServerStream) RecvMsg(msg interface{}) error { +func (m *mockServerStream) RecvMsg(msg any) error { m.recvMsg = msg return nil } @@ -339,7 +339,7 @@ func TestServer_streamServerInterceptor(t *testing.T) { ctx: srv.baseCtx, } - handler := func(_ interface{}, stream grpc.ServerStream) error { + handler := func(_ any, stream grpc.ServerStream) error { resp := &testResp{Data: "stream hi"} return stream.SendMsg(resp) } diff --git a/transport/http/binding/bind.go b/transport/http/binding/bind.go index 69534ada6..195dfe7af 100644 --- a/transport/http/binding/bind.go +++ b/transport/http/binding/bind.go @@ -10,7 +10,7 @@ import ( ) // BindQuery bind vars parameters to target. -func BindQuery(vars url.Values, target interface{}) error { +func BindQuery(vars url.Values, target any) error { if err := encoding.GetCodec(form.Name).Unmarshal([]byte(vars.Encode()), target); err != nil { return errors.BadRequest("CODEC", err.Error()) } @@ -18,7 +18,7 @@ func BindQuery(vars url.Values, target interface{}) error { } // BindForm bind form parameters to target. -func BindForm(req *http.Request, target interface{}) error { +func BindForm(req *http.Request, target any) error { if err := req.ParseForm(); err != nil { return err } diff --git a/transport/http/binding/bind_test.go b/transport/http/binding/bind_test.go index 962292c4a..dd5ccc71c 100644 --- a/transport/http/binding/bind_test.go +++ b/transport/http/binding/bind_test.go @@ -25,14 +25,14 @@ type ( func TestBindQuery(t *testing.T) { type args struct { vars url.Values - target interface{} + target any } tests := []struct { name string args args err error - want interface{} + want any }{ { name: "test", @@ -77,7 +77,7 @@ func TestBindQuery(t *testing.T) { func TestBindForm(t *testing.T) { type args struct { req *http.Request - target interface{} + target any } tests := []struct { diff --git a/transport/http/binding/encode.go b/transport/http/binding/encode.go index 2c1eda9ce..5e58ad404 100644 --- a/transport/http/binding/encode.go +++ b/transport/http/binding/encode.go @@ -12,7 +12,7 @@ import ( var reg = regexp.MustCompile(`{[\\.\w]+}`) // EncodeURL encode proto message to url path. -func EncodeURL(pathTemplate string, msg interface{}, needQuery bool) string { +func EncodeURL(pathTemplate string, msg any, needQuery bool) string { if msg == nil || (reflect.ValueOf(msg).Kind() == reflect.Ptr && reflect.ValueOf(msg).IsNil()) { return pathTemplate } diff --git a/transport/http/client.go b/transport/http/client.go index d7efbcc86..ccc761276 100644 --- a/transport/http/client.go +++ b/transport/http/client.go @@ -30,10 +30,10 @@ func init() { type DecodeErrorFunc func(ctx context.Context, res *http.Response) error // EncodeRequestFunc is request encode func. -type EncodeRequestFunc func(ctx context.Context, contentType string, in interface{}) (body []byte, err error) +type EncodeRequestFunc func(ctx context.Context, contentType string, in any) (body []byte, err error) // DecodeResponseFunc is response decode func. -type DecodeResponseFunc func(ctx context.Context, res *http.Response, out interface{}) error +type DecodeResponseFunc func(ctx context.Context, res *http.Response, out any) error // ClientOption is HTTP client option. type ClientOption func(*clientOptions) @@ -207,7 +207,7 @@ func NewClient(ctx context.Context, opts ...ClientOption) (*Client, error) { } // Invoke makes a rpc call procedure for remote service. -func (client *Client) Invoke(ctx context.Context, method, path string, args interface{}, reply interface{}, opts ...CallOption) error { +func (client *Client) Invoke(ctx context.Context, method, path string, args any, reply any, opts ...CallOption) error { var ( contentType string body io.Reader @@ -251,8 +251,8 @@ func (client *Client) Invoke(ctx context.Context, method, path string, args inte return client.invoke(ctx, req, args, reply, c, opts...) } -func (client *Client) invoke(ctx context.Context, req *http.Request, args interface{}, reply interface{}, c callInfo, opts ...CallOption) error { - h := func(ctx context.Context, _ interface{}) (interface{}, error) { +func (client *Client) invoke(ctx context.Context, req *http.Request, args any, reply any, c callInfo, opts ...CallOption) error { + h := func(ctx context.Context, _ any) (any, error) { res, err := client.do(req.WithContext(ctx)) if res != nil { cs := csAttempt{res: res} @@ -338,7 +338,7 @@ func (client *Client) Close() error { } // DefaultRequestEncoder is an HTTP request encoder. -func DefaultRequestEncoder(_ context.Context, contentType string, in interface{}) ([]byte, error) { +func DefaultRequestEncoder(_ context.Context, contentType string, in any) ([]byte, error) { name := httputil.ContentSubtype(contentType) body, err := encoding.GetCodec(name).Marshal(in) if err != nil { @@ -348,7 +348,7 @@ func DefaultRequestEncoder(_ context.Context, contentType string, in interface{} } // DefaultResponseDecoder is an HTTP response decoder. -func DefaultResponseDecoder(_ context.Context, res *http.Response, v interface{}) error { +func DefaultResponseDecoder(_ context.Context, res *http.Response, v any) error { defer res.Body.Close() data, err := io.ReadAll(res.Body) if err != nil { diff --git a/transport/http/client_test.go b/transport/http/client_test.go index 13bf4428b..091e0ebd2 100644 --- a/transport/http/client_test.go +++ b/transport/http/client_test.go @@ -123,7 +123,7 @@ func TestWithEndpoint(t *testing.T) { func TestWithRequestEncoder(t *testing.T) { o := &clientOptions{} - v := func(context.Context, string, interface{}) (body []byte, err error) { + v := func(context.Context, string, any) (body []byte, err error) { return nil, nil } WithRequestEncoder(v)(o) @@ -134,7 +134,7 @@ func TestWithRequestEncoder(t *testing.T) { func TestWithResponseDecoder(t *testing.T) { o := &clientOptions{} - v := func(context.Context, *http.Response, interface{}) error { return nil } + v := func(context.Context, *http.Response, any) error { return nil } WithResponseDecoder(v)(o) if o.decoder == nil { t.Errorf("expected encoder to be not nil") @@ -342,7 +342,7 @@ func TestNewClient(t *testing.T) { WithEndpoint("discovery:///go-kratos"), WithMiddleware(func(handler middleware.Handler) middleware.Handler { t.Logf("handle in middleware") - return func(ctx context.Context, req interface{}) (interface{}, error) { + return func(ctx context.Context, req any) (any, error) { return handler(ctx, req) } }), @@ -359,7 +359,7 @@ func TestNewClient(t *testing.T) { if err == nil { t.Error("err should be equal to callOption err") } - client.opts.encoder = func(context.Context, string, interface{}) (body []byte, err error) { + client.opts.encoder = func(context.Context, string, any) (body []byte, err error) { return nil, errors.New("mock test encoder error") } err = client.Invoke(context.Background(), http.MethodPost, "/go", map[string]string{"name": "kratos"}, nil, EmptyCallOption{}) diff --git a/transport/http/codec.go b/transport/http/codec.go index 39db4d211..9c026f833 100644 --- a/transport/http/codec.go +++ b/transport/http/codec.go @@ -34,16 +34,16 @@ type ResponseWriter = http.ResponseWriter type Flusher = http.Flusher // DecodeRequestFunc is decode request func. -type DecodeRequestFunc func(*http.Request, interface{}) error +type DecodeRequestFunc func(*http.Request, any) error // EncodeResponseFunc is encode response func. -type EncodeResponseFunc func(http.ResponseWriter, *http.Request, interface{}) error +type EncodeResponseFunc func(http.ResponseWriter, *http.Request, any) error // EncodeErrorFunc is encode error func. type EncodeErrorFunc func(http.ResponseWriter, *http.Request, error) // DefaultRequestVars decodes the request vars to object. -func DefaultRequestVars(r *http.Request, v interface{}) error { +func DefaultRequestVars(r *http.Request, v any) error { raws := mux.Vars(r) vars := make(url.Values, len(raws)) for k, v := range raws { @@ -53,12 +53,12 @@ func DefaultRequestVars(r *http.Request, v interface{}) error { } // DefaultRequestQuery decodes the request vars to object. -func DefaultRequestQuery(r *http.Request, v interface{}) error { +func DefaultRequestQuery(r *http.Request, v any) error { return binding.BindQuery(r.URL.Query(), v) } // DefaultRequestDecoder decodes the request body to object. -func DefaultRequestDecoder(r *http.Request, v interface{}) error { +func DefaultRequestDecoder(r *http.Request, v any) error { codec, ok := CodecForRequest(r, "Content-Type") if !ok { return errors.BadRequest("CODEC", fmt.Sprintf("unregister Content-Type: %s", r.Header.Get("Content-Type"))) @@ -81,7 +81,7 @@ func DefaultRequestDecoder(r *http.Request, v interface{}) error { } // DefaultResponseEncoder encodes the object to the HTTP response. -func DefaultResponseEncoder(w http.ResponseWriter, r *http.Request, v interface{}) error { +func DefaultResponseEncoder(w http.ResponseWriter, r *http.Request, v any) error { if v == nil { return nil } diff --git a/transport/http/context.go b/transport/http/context.go index 43ea78ced..4b021280d 100644 --- a/transport/http/context.go +++ b/transport/http/context.go @@ -28,14 +28,14 @@ type Context interface { Request() *http.Request Response() http.ResponseWriter Middleware(middleware.Handler) middleware.Handler - Bind(interface{}) error - BindVars(interface{}) error - BindQuery(interface{}) error - BindForm(interface{}) error - Returns(interface{}, error) error - Result(int, interface{}) error - JSON(int, interface{}) error - XML(int, interface{}) error + Bind(any) error + BindVars(any) error + BindQuery(any) error + BindForm(any) error + Returns(any, error) error + Result(int, any) error + JSON(int, any) error + XML(int, any) error String(int, string) error Blob(int, string, []byte) error Stream(int, string, io.Reader) error @@ -97,29 +97,29 @@ func (c *wrapper) Middleware(h middleware.Handler) middleware.Handler { } return middleware.Chain(c.router.srv.middleware.Match(c.req.URL.Path)...)(h) } -func (c *wrapper) Bind(v interface{}) error { return c.router.srv.decBody(c.req, v) } -func (c *wrapper) BindVars(v interface{}) error { return c.router.srv.decVars(c.req, v) } -func (c *wrapper) BindQuery(v interface{}) error { return c.router.srv.decQuery(c.req, v) } -func (c *wrapper) BindForm(v interface{}) error { return binding.BindForm(c.req, v) } -func (c *wrapper) Returns(v interface{}, err error) error { +func (c *wrapper) Bind(v any) error { return c.router.srv.decBody(c.req, v) } +func (c *wrapper) BindVars(v any) error { return c.router.srv.decVars(c.req, v) } +func (c *wrapper) BindQuery(v any) error { return c.router.srv.decQuery(c.req, v) } +func (c *wrapper) BindForm(v any) error { return binding.BindForm(c.req, v) } +func (c *wrapper) Returns(v any, err error) error { if err != nil { return err } return c.router.srv.enc(&c.w, c.req, v) } -func (c *wrapper) Result(code int, v interface{}) error { +func (c *wrapper) Result(code int, v any) error { c.w.WriteHeader(code) return c.router.srv.enc(&c.w, c.req, v) } -func (c *wrapper) JSON(code int, v interface{}) error { +func (c *wrapper) JSON(code int, v any) error { c.res.Header().Set("Content-Type", "application/json") c.res.WriteHeader(code) return json.NewEncoder(c.res).Encode(v) } -func (c *wrapper) XML(code int, v interface{}) error { +func (c *wrapper) XML(code int, v any) error { c.res.Header().Set("Content-Type", "application/xml") c.res.WriteHeader(code) return xml.NewEncoder(c.res).Encode(v) @@ -179,7 +179,7 @@ func (c *wrapper) Err() error { return c.req.Context().Err() } -func (c *wrapper) Value(key interface{}) interface{} { +func (c *wrapper) Value(key any) any { if c.req == nil { return nil } diff --git a/transport/http/context_test.go b/transport/http/context_test.go index b4949a02f..bb95c7c4d 100644 --- a/transport/http/context_test.go +++ b/transport/http/context_test.go @@ -102,7 +102,7 @@ func TestContextResponse(t *testing.T) { func TestResponseUnwrap(t *testing.T) { res := httptest.NewRecorder() - f := func(rw http.ResponseWriter, _ *http.Request, _ interface{}) error { + f := func(rw http.ResponseWriter, _ *http.Request, _ any) error { u, ok := rw.(interface { Unwrap() http.ResponseWriter }) diff --git a/transport/http/router_test.go b/transport/http/router_test.go index 00b1a7dd1..2ca1c12fd 100644 --- a/transport/http/router_test.go +++ b/transport/http/router_test.go @@ -75,7 +75,7 @@ func TestRoute(t *testing.T) { if err := ctx.Bind(u); err != nil { return err } - h := ctx.Middleware(func(context.Context, interface{}) (interface{}, error) { + h := ctx.Middleware(func(context.Context, any) (any, error) { return u, nil }) return ctx.Returns(h(ctx, u)) diff --git a/transport/http/server_test.go b/transport/http/server_test.go index 665ac0222..93bf7c7d3 100644 --- a/transport/http/server_test.go +++ b/transport/http/server_test.go @@ -313,7 +313,7 @@ func TestTimeout(t *testing.T) { func TestRequestDecoder(t *testing.T) { o := &Server{} - v := func(*http.Request, interface{}) error { return nil } + v := func(*http.Request, any) error { return nil } RequestDecoder(v)(o) if o.decBody == nil { t.Errorf("expected nil got %v", o.decBody) @@ -322,7 +322,7 @@ func TestRequestDecoder(t *testing.T) { func TestResponseEncoder(t *testing.T) { o := &Server{} - v := func(http.ResponseWriter, *http.Request, interface{}) error { return nil } + v := func(http.ResponseWriter, *http.Request, any) error { return nil } ResponseEncoder(v)(o) if o.enc == nil { t.Errorf("expected nil got %v", o.enc)