1
0
mirror of https://github.com/go-kratos/kratos.git synced 2025-10-30 23:47:59 +02:00

chore: replace interface{} with any (#3557)

Signed-off-by: Sasha Melentyev <sasha@m8.ru>
This commit is contained in:
Sasha Melentyev
2025-03-07 18:56:30 +03:00
committed by GitHub
parent 3a0bd50741
commit 7a9a72e951
106 changed files with 454 additions and 454 deletions

View File

@@ -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)

View File

@@ -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

View File

@@ -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)
},
}

View File

@@ -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 {

View File

@@ -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",

View File

@@ -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])

View File

@@ -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 {

View File

@@ -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)
}

View File

@@ -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,
},
},

View File

@@ -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 }

View File

@@ -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{}

View File

@@ -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
}

View File

@@ -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
}

View File

@@ -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)

View File

@@ -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
}

View File

@@ -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)
}

View File

@@ -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") ||

View File

@@ -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)

View File

@@ -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

View File

@@ -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"},

View File

@@ -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
}

View File

@@ -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
)

View File

@@ -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"`,
},
}

View File

@@ -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

View File

@@ -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"},

View File

@@ -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)) {

View File

@@ -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

View File

@@ -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)

View File

@@ -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{
{

View File

@@ -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

View File

@@ -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

View File

@@ -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()

View File

@@ -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 {

View File

@@ -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)
}

View File

@@ -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) {

View File

@@ -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 {

View File

@@ -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.

View File

@@ -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() {

View File

@@ -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

View File

@@ -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
}

View File

@@ -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)

View File

@@ -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":""}`,

View File

@@ -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
}

View File

@@ -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

View File

@@ -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)
}

View File

@@ -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
}{
{

View File

@@ -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)
}

View File

@@ -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 {

View File

@@ -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...))
}

View File

@@ -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.

View File

@@ -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
}

View File

@@ -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{}
})

View File

@@ -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()
}

View File

@@ -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")

View File

@@ -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
}
}

View File

@@ -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...)
}

View File

@@ -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)
}
}

View File

@@ -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)
}

View File

@@ -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{})
}))

View File

@@ -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)
}

View File

@@ -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

View File

@@ -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{

View File

@@ -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
}

View File

@@ -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

View File

@@ -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)

View File

@@ -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
}

View File

@@ -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)

View File

@@ -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 {

View File

@@ -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)

View File

@@ -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()
}

View File

@@ -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
}{
{

View File

@@ -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)

View File

@@ -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")

View File

@@ -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

View File

@@ -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
}

View File

@@ -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

View File

@@ -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)

View File

@@ -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

View File

@@ -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
}

View File

@@ -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 {

View File

@@ -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
}

View File

@@ -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)
}

View File

@@ -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
}

View File

@@ -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

View File

@@ -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 {

View File

@@ -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()
}

View File

@@ -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",
)

View File

@@ -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)

View File

@@ -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},

View File

@@ -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
}

View File

@@ -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
}

View File

@@ -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)
}
}

View File

@@ -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)

View File

@@ -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)
}

View File

@@ -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)
}

View File

@@ -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)
}

View File

@@ -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
}

View File

@@ -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 {

View File

@@ -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
}

View File

@@ -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 {

Some files were not shown because too many files have changed in this diff Show More