提交 a71424db authored 作者: mooncake's avatar mooncake

update

上级 bbbda169
...@@ -144,7 +144,7 @@ func MakeCondition(q odao.Query) func(db *gorm.DB) *gorm.DB { ...@@ -144,7 +144,7 @@ func MakeCondition(q odao.Query) func(db *gorm.DB) *gorm.DB {
} }
} }
func GetGormTags(obj interface{}) []string { func GetGormTags(obj any) []string {
var tags []string var tags []string
val := reflect.ValueOf(obj) val := reflect.ValueOf(obj)
......
...@@ -44,7 +44,7 @@ func HandleDictOptionsWithDict(c *gin.Context, d *EnumDictionary) { ...@@ -44,7 +44,7 @@ func HandleDictOptionsWithDict(c *gin.Context, d *EnumDictionary) {
type BaseReply struct { type BaseReply struct {
Code int `json:"code" form:"code" example:"1"` Code int `json:"code" form:"code" example:"1"`
Msg string `json:"message" form:"message" example:"OK"` Msg string `json:"message" form:"message" example:"OK"`
Data interface{} `json:"data"` Data any `json:"data"`
TimeStamp int64 `json:"timestamp" form:"data" example:"1718850053"` TimeStamp int64 `json:"timestamp" form:"data" example:"1718850053"`
TraceID string `json:"traceID" form:"traceID" example:"1988899757589794816"` TraceID string `json:"traceID" form:"traceID" example:"1988899757589794816"`
} }
......
...@@ -115,7 +115,7 @@ func URLFields() gin.HandlerFunc { ...@@ -115,7 +115,7 @@ func URLFields() gin.HandlerFunc {
} }
} }
type KV = map[string]interface{} type KV = map[string]any
func HeaderFields(keys []string) gin.HandlerFunc { func HeaderFields(keys []string) gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
......
...@@ -26,7 +26,7 @@ type circuitBreakerOptions struct { ...@@ -26,7 +26,7 @@ type circuitBreakerOptions struct {
func defaultCircuitBreakerOptions() *circuitBreakerOptions { func defaultCircuitBreakerOptions() *circuitBreakerOptions {
return &circuitBreakerOptions{ return &circuitBreakerOptions{
group: group.NewGroup(func() interface{} { group: group.NewGroup(func() any {
return circuitbreaker.NewBreaker() return circuitbreaker.NewBreaker()
}), }),
validCodes: map[int]struct{}{ validCodes: map[int]struct{}{
......
...@@ -27,7 +27,7 @@ func runCircuitBreakerHTTPServer() string { ...@@ -27,7 +27,7 @@ func runCircuitBreakerHTTPServer() string {
gin.SetMode(gin.ReleaseMode) gin.SetMode(gin.ReleaseMode)
r := gin.New() r := gin.New()
r.Use(CircuitBreaker(WithGroup(group.NewGroup(func() interface{} { r.Use(CircuitBreaker(WithGroup(group.NewGroup(func() any {
return circuitbreaker.NewBreaker() return circuitbreaker.NewBreaker()
})), })),
WithValidCode(http.StatusForbidden), WithValidCode(http.StatusForbidden),
......
...@@ -93,7 +93,7 @@ func TestRequest(t *testing.T) { ...@@ -93,7 +93,7 @@ func TestRequest(t *testing.T) {
}) })
t.Run("get hello", func(t *testing.T) { t.Run("get hello", func(t *testing.T) {
err := httpcli.New().SetURL(requestAddr + "/hello").SetParams(map[string]interface{}{"id": "100"}).GET(context.Background()).BindJSON(result).Err() err := httpcli.New().SetURL(requestAddr + "/hello").SetParams(map[string]any{"id": "100"}).GET(context.Background()).BindJSON(result).Err()
if err != nil { if err != nil {
t.Error(err) t.Error(err)
return return
...@@ -105,7 +105,7 @@ func TestRequest(t *testing.T) { ...@@ -105,7 +105,7 @@ func TestRequest(t *testing.T) {
}) })
t.Run("delete hello", func(t *testing.T) { t.Run("delete hello", func(t *testing.T) {
err := httpcli.New().SetURL(requestAddr + "/hello").SetParams(map[string]interface{}{"id": "100"}).DELETE(context.Background()).BindJSON(result).Err() err := httpcli.New().SetURL(requestAddr + "/hello").SetParams(map[string]any{"id": "100"}).DELETE(context.Background()).BindJSON(result).Err()
if err != nil { if err != nil {
t.Error(err) t.Error(err)
return return
......
...@@ -10,7 +10,7 @@ import ( ...@@ -10,7 +10,7 @@ import (
) )
func CustomRecoveryWithLogger(logger *zap.Logger) gin.HandlerFunc { func CustomRecoveryWithLogger(logger *zap.Logger) gin.HandlerFunc {
return gin.CustomRecovery(func(c *gin.Context, err interface{}) { return gin.CustomRecovery(func(c *gin.Context, err any) {
logger.Error("Recovered from panic", logger.Error("Recovered from panic",
zap.String("path", c.Request.URL.Path), zap.String("path", c.Request.URL.Path),
zap.String("method", c.Request.Method), zap.String("method", c.Request.Method),
......
...@@ -122,7 +122,7 @@ func AdaptCtx(ctx context.Context) (*gin.Context, context.Context) { ...@@ -122,7 +122,7 @@ func AdaptCtx(ctx context.Context) (*gin.Context, context.Context) {
} }
// GetFromCtx get value from context // GetFromCtx get value from context
func GetFromCtx(ctx context.Context, key string) interface{} { func GetFromCtx(ctx context.Context, key string) any {
return ctx.Value(key) return ctx.Value(key)
} }
......
...@@ -26,7 +26,7 @@ type Params struct { ...@@ -26,7 +26,7 @@ type Params struct {
type Column struct { type Column struct {
Name string `json:"name" comment:"name" encomment:"name" form:"name" validate:"required" example:"id"` // column name Name string `json:"name" comment:"name" encomment:"name" form:"name" validate:"required" example:"id"` // column name
Exp string `json:"exp" comment:"exp" encomment:"exp" form:"exp" validate:"required" example:"="` // expressions, which default to = when the value is null, have =, !=, >, >=, <, <=, like Exp string `json:"exp" comment:"exp" encomment:"exp" form:"exp" validate:"required" example:"="` // expressions, which default to = when the value is null, have =, !=, >, >=, <, <=, like
Value interface{} `json:"value" comment:"value" encomment:"value" form:"value" validate:"required" example:"102"` // column value Value any `json:"value" comment:"value" encomment:"value" form:"value" validate:"required" example:"102"` // column value
Logic string `json:"logic" comment:"logic" encomment:"logic" form:"logic" example:"and"` // logical type, default value is "and", support &, and, ||, or Logic string `json:"logic" comment:"logic" encomment:"logic" form:"logic" example:"and"` // logical type, default value is "and", support &, and, ||, or
} }
...@@ -34,10 +34,6 @@ type Conditions struct { ...@@ -34,10 +34,6 @@ type Conditions struct {
Columns []Column `json:"columns" comment:"columns" encomment:"columns" form:"columns"` // columns info Columns []Column `json:"columns" comment:"columns" encomment:"columns" form:"columns"` // columns info
} }
type BaseCreateReply struct {
ID xsf.ID `json:"id" comment:"id" encomment:"id" form:"id" example:"1924346047086211072"` // id
}
type BaseIDReq struct { type BaseIDReq struct {
ID xsf.ID `json:"id" comment:"id" encomment:"id" form:"id" swaggertype:"string" validate:"required" example:"1"` // id ID xsf.ID `json:"id" comment:"id" encomment:"id" form:"id" swaggertype:"string" validate:"required" example:"1"` // id
} }
......
...@@ -53,12 +53,12 @@ type BaseReply struct { ...@@ -53,12 +53,12 @@ type BaseReply struct {
type Result struct { type Result struct {
Code int `json:"code" form:"code" example:"1"` Code int `json:"code" form:"code" example:"1"`
Msg string `json:"message" form:"message" example:"OK"` Msg string `json:"message" form:"message" example:"OK"`
Data interface{} `json:"data"` Data any `json:"data" form:"data"`
TimeStamp int64 `json:"timestamp" form:"data" example:"1718850053"` TimeStamp int64 `json:"timestamp" form:"data" example:"1718850053"`
TraceID string `json:"traceID" form:"traceID" example:"1988899757589794816"` TraceID string `json:"traceID" form:"traceID" example:"1988899757589794816"`
} }
func newResp(c *gin.Context, code int, msg string, data interface{}) *Result { func newResp(c *gin.Context, code int, msg string, data any) *Result {
resp := &Result{ resp := &Result{
Code: code, Code: code,
Msg: msg, Msg: msg,
...@@ -87,7 +87,7 @@ func writeContentType(w http.ResponseWriter, value []string) { ...@@ -87,7 +87,7 @@ func writeContentType(w http.ResponseWriter, value []string) {
} }
} }
func writeJSON(c *gin.Context, code int, res interface{}) { func writeJSON(c *gin.Context, code int, res any) {
c.Writer.WriteHeader(code) c.Writer.WriteHeader(code)
writeContentType(c.Writer, jsonContentType) writeContentType(c.Writer, jsonContentType)
if res != nil { if res != nil {
...@@ -102,8 +102,8 @@ func writeJSON(c *gin.Context, code int, res interface{}) { ...@@ -102,8 +102,8 @@ func writeJSON(c *gin.Context, code int, res interface{}) {
//} //}
} }
func respJSONWithStatusCode(c *gin.Context, code int, msg string, data ...interface{}) { func respJSONWithStatusCode(c *gin.Context, code int, msg string, data ...any) {
var firstData interface{} var firstData any
if len(data) > 0 { if len(data) > 0 {
firstData = data[0] firstData = data[0]
} }
...@@ -113,7 +113,7 @@ func respJSONWithStatusCode(c *gin.Context, code int, msg string, data ...interf ...@@ -113,7 +113,7 @@ func respJSONWithStatusCode(c *gin.Context, code int, msg string, data ...interf
} }
// Output return standard HTTP status codes and message, parameter code is HTTP status code // Output return standard HTTP status codes and message, parameter code is HTTP status code
func Output(c *gin.Context, code int, data ...interface{}) { func Output(c *gin.Context, code int, data ...any) {
switch code { switch code {
case http.StatusOK: case http.StatusOK:
respJSONWithStatusCode(c, http.StatusOK, errcode.Success.Msg(), data...) respJSONWithStatusCode(c, http.StatusOK, errcode.Success.Msg(), data...)
...@@ -142,7 +142,7 @@ func Output(c *gin.Context, code int, data ...interface{}) { ...@@ -142,7 +142,7 @@ func Output(c *gin.Context, code int, data ...interface{}) {
} }
// Out returns the standard HTTP status code and message, parameter err is errcode.Error // Out returns the standard HTTP status code and message, parameter err is errcode.Error
func Out(c *gin.Context, err *errcode.Error, data ...interface{}) { func Out(c *gin.Context, err *errcode.Error, data ...any) {
code := err.ToHTTPCode() code := err.ToHTTPCode()
switch code { switch code {
case http.StatusOK: case http.StatusOK:
...@@ -172,7 +172,7 @@ func Out(c *gin.Context, err *errcode.Error, data ...interface{}) { ...@@ -172,7 +172,7 @@ func Out(c *gin.Context, err *errcode.Error, data ...interface{}) {
} }
// status code flat 200, custom error codes in data.code // status code flat 200, custom error codes in data.code
func respJSONWith200(c *gin.Context, code int, msg string, data ...interface{}) { func respJSONWith200(c *gin.Context, code int, msg string, data ...any) {
c.Writer.Header().Set(ctxutils.HeaderXTimestampKey, strconv.FormatInt(time.Now().Unix(), 10)) c.Writer.Header().Set(ctxutils.HeaderXTimestampKey, strconv.FormatInt(time.Now().Unix(), 10))
appName := c.GetString(ctxutils.KeyAppName) appName := c.GetString(ctxutils.KeyAppName)
stTime := c.GetTime(ctxutils.KeyApiStartTime) stTime := c.GetTime(ctxutils.KeyApiStartTime)
...@@ -187,7 +187,7 @@ func respJSONWith200(c *gin.Context, code int, msg string, data ...interface{}) ...@@ -187,7 +187,7 @@ func respJSONWith200(c *gin.Context, code int, msg string, data ...interface{})
} }
// Success return success // Success return success
func Success(c *gin.Context, data ...interface{}) { func Success(c *gin.Context, data ...any) {
c.Set(ctxutils.KeyRspCode, 1) c.Set(ctxutils.KeyRspCode, 1)
respJSONWith200(c, errcode.Success.Code(), errcode.Success.Msg(), data...) respJSONWith200(c, errcode.Success.Code(), errcode.Success.Msg(), data...)
} }
...@@ -258,7 +258,7 @@ func SuccessWithList[T any](c *gin.Context, list []*T) { ...@@ -258,7 +258,7 @@ func SuccessWithList[T any](c *gin.Context, list []*T) {
} }
// ErrorE return error // ErrorE return error
func ErrorE(c *gin.Context, err *errcode.Error, data ...interface{}) { func ErrorE(c *gin.Context, err *errcode.Error, data ...any) {
c.Set(ctxutils.KeyRspCode, 0) c.Set(ctxutils.KeyRspCode, 0)
respJSONWith200(c, err.Code(), err.Msg(), data...) respJSONWith200(c, err.Code(), err.Msg(), data...)
} }
......
...@@ -27,7 +27,7 @@ func NewCustomValidator() *CustomValidator { ...@@ -27,7 +27,7 @@ func NewCustomValidator() *CustomValidator {
} }
// ValidateStruct Instantiate struct valid // ValidateStruct Instantiate struct valid
func (v *CustomValidator) ValidateStruct(obj interface{}) error { func (v *CustomValidator) ValidateStruct(obj any) error {
if kindOfData(obj) == reflect.Struct { if kindOfData(obj) == reflect.Struct {
v.lazyinit() v.lazyinit()
if err := v.Validate.Struct(obj); err != nil { if err := v.Validate.Struct(obj); err != nil {
...@@ -39,7 +39,7 @@ func (v *CustomValidator) ValidateStruct(obj interface{}) error { ...@@ -39,7 +39,7 @@ func (v *CustomValidator) ValidateStruct(obj interface{}) error {
} }
// Engine Instantiate valid // Engine Instantiate valid
func (v *CustomValidator) Engine() interface{} { func (v *CustomValidator) Engine() any {
v.lazyinit() v.lazyinit()
return v.Validate return v.Validate
} }
...@@ -51,7 +51,7 @@ func (v *CustomValidator) lazyinit() { ...@@ -51,7 +51,7 @@ func (v *CustomValidator) lazyinit() {
}) })
} }
func kindOfData(data interface{}) reflect.Kind { func kindOfData(data any) reflect.Kind {
value := reflect.ValueOf(data) value := reflect.ValueOf(data)
valueType := value.Kind() valueType := value.Kind()
......
...@@ -378,7 +378,7 @@ func TestGetsValidate(t *testing.T) { ...@@ -378,7 +378,7 @@ func TestGetsValidate(t *testing.T) {
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
func do(method string, url string, body interface{}) ([]byte, error) { func do(method string, url string, body any) ([]byte, error) {
var reader io.Reader var reader io.Reader
if body == nil { if body == nil {
reader = nil reader = nil
......
...@@ -31,32 +31,32 @@ var ( ...@@ -31,32 +31,32 @@ var (
// Cache driver interface // Cache driver interface
type Cache interface { type Cache interface {
IncrBy(ctx context.Context, key string, value int64) (int64, error) IncrBy(ctx context.Context, key string, value int64) (int64, error)
Set(ctx context.Context, key string, val interface{}, expiration time.Duration) error Set(ctx context.Context, key string, val any, expiration time.Duration) error
Get(ctx context.Context, key string, val interface{}) error Get(ctx context.Context, key string, val any) error
MultiSet(ctx context.Context, valMap map[string]interface{}, expiration time.Duration) error MultiSet(ctx context.Context, valMap map[string]any, expiration time.Duration) error
MultiGet(ctx context.Context, keys []string, valueMap interface{}) error MultiGet(ctx context.Context, keys []string, valueMap any) error
MGet(ctx context.Context, keys []string) ([]any, error) MGet(ctx context.Context, keys []string) ([]any, error)
Del(ctx context.Context, keys ...string) error Del(ctx context.Context, keys ...string) error
SetCacheWithNotFound(ctx context.Context, key string) error SetCacheWithNotFound(ctx context.Context, key string) error
} }
// Set data // Set data
func Set(ctx context.Context, key string, val interface{}, expiration time.Duration) error { func Set(ctx context.Context, key string, val any, expiration time.Duration) error {
return DefaultClient.Set(ctx, key, val, expiration) return DefaultClient.Set(ctx, key, val, expiration)
} }
// Get data // Get data
func Get(ctx context.Context, key string, val interface{}) error { func Get(ctx context.Context, key string, val any) error {
return DefaultClient.Get(ctx, key, val) return DefaultClient.Get(ctx, key, val)
} }
// MultiSet multiple set data // MultiSet multiple set data
func MultiSet(ctx context.Context, valMap map[string]interface{}, expiration time.Duration) error { func MultiSet(ctx context.Context, valMap map[string]any, expiration time.Duration) error {
return DefaultClient.MultiSet(ctx, valMap, expiration) return DefaultClient.MultiSet(ctx, valMap, expiration)
} }
// MultiGet multiple get data // MultiGet multiple get data
func MultiGet(ctx context.Context, keys []string, valueMap interface{}) error { func MultiGet(ctx context.Context, keys []string, valueMap any) error {
return DefaultClient.MultiGet(ctx, keys, valueMap) return DefaultClient.MultiGet(ctx, keys, valueMap)
} }
......
...@@ -26,14 +26,14 @@ func newCache() *gotest.Cache { ...@@ -26,14 +26,14 @@ func newCache() *gotest.Cache {
Name: "bar", Name: "bar",
} }
testData := map[string]interface{}{ testData := map[string]any{
utils.Uint64ToStr(record1.ID): record1, utils.Uint64ToStr(record1.ID): record1,
utils.Uint64ToStr(record2.ID): record2, utils.Uint64ToStr(record2.ID): record2,
} }
c := gotest.NewCache(testData) c := gotest.NewCache(testData)
cachePrefix := "" cachePrefix := ""
DefaultClient = NewRedisCache(c.RedisClient, cachePrefix, encoding.JSONEncoding{}, func() interface{} { DefaultClient = NewRedisCache(c.RedisClient, cachePrefix, encoding.JSONEncoding{}, func() any {
return &cacheUser{} return &cacheUser{}
}) })
c.ICache = DefaultClient c.ICache = DefaultClient
......
...@@ -22,11 +22,11 @@ type memoryCache struct { ...@@ -22,11 +22,11 @@ type memoryCache struct {
KeyPrefix string KeyPrefix string
encoding encoding.Encoding encoding encoding.Encoding
DefaultExpireTime time.Duration DefaultExpireTime time.Duration
newObject func() interface{} newObject func() any
} }
// NewMemoryCache create a memory cache // NewMemoryCache create a memory cache
func NewMemoryCache(cache *ristretto.Cache, keyPrefix string, encode encoding.Encoding, newObject func() interface{}) Cache { func NewMemoryCache(cache *ristretto.Cache, keyPrefix string, encode encoding.Encoding, newObject func() any) Cache {
return &memoryCache{ return &memoryCache{
client: cache, client: cache,
KeyPrefix: keyPrefix, KeyPrefix: keyPrefix,
...@@ -38,7 +38,7 @@ func NewMemoryCache(cache *ristretto.Cache, keyPrefix string, encode encoding.En ...@@ -38,7 +38,7 @@ func NewMemoryCache(cache *ristretto.Cache, keyPrefix string, encode encoding.En
const logPrefix = "[memory]" const logPrefix = "[memory]"
// Set data // Set data
func (m *memoryCache) Set(ctx context.Context, key string, val interface{}, expiration time.Duration) error { func (m *memoryCache) Set(ctx context.Context, key string, val any, expiration time.Duration) error {
buf, err := encoding.Marshal(m.encoding, val) buf, err := encoding.Marshal(m.encoding, val)
if err != nil { if err != nil {
return xerror.Errorf("encoding.Marshal error: %v, key=%s, val=%+v ", err, key, val) return xerror.Errorf("encoding.Marshal error: %v, key=%s, val=%+v ", err, key, val)
...@@ -96,7 +96,7 @@ func (m *memoryCache) IncrBy(ctx context.Context, key string, val int64) (int64, ...@@ -96,7 +96,7 @@ func (m *memoryCache) IncrBy(ctx context.Context, key string, val int64) (int64,
} }
// Get data // Get data
func (m *memoryCache) Get(ctx context.Context, key string, val interface{}) error { func (m *memoryCache) Get(ctx context.Context, key string, val any) error {
cacheKey, err := BuildCacheKey(m.KeyPrefix, key) cacheKey, err := BuildCacheKey(m.KeyPrefix, key)
if err != nil { if err != nil {
return xerror.Errorf("BuildCacheKey error: %v, key=%s", err, key) return xerror.Errorf("BuildCacheKey error: %v, key=%s", err, key)
...@@ -163,7 +163,7 @@ func (m *memoryCache) Del(ctx context.Context, keys ...string) error { ...@@ -163,7 +163,7 @@ func (m *memoryCache) Del(ctx context.Context, keys ...string) error {
} }
// MultiSet multiple set data // MultiSet multiple set data
func (m *memoryCache) MultiSet(ctx context.Context, valueMap map[string]interface{}, expiration time.Duration) error { func (m *memoryCache) MultiSet(ctx context.Context, valueMap map[string]any, expiration time.Duration) error {
var err error var err error
for key, value := range valueMap { for key, value := range valueMap {
err = m.Set(ctx, key, value, expiration) err = m.Set(ctx, key, value, expiration)
...@@ -176,7 +176,7 @@ func (m *memoryCache) MultiSet(ctx context.Context, valueMap map[string]interfac ...@@ -176,7 +176,7 @@ func (m *memoryCache) MultiSet(ctx context.Context, valueMap map[string]interfac
// MultiGet multiple get data // MultiGet multiple get data
// deprecated // deprecated
func (m *memoryCache) MultiGet(ctx context.Context, keys []string, value interface{}) error { func (m *memoryCache) MultiGet(ctx context.Context, keys []string, value any) error {
valueMap := reflect.ValueOf(value) valueMap := reflect.ValueOf(value)
var err error var err error
for _, key := range keys { for _, key := range keys {
......
...@@ -25,14 +25,14 @@ func newMemoryCache() *gotest.Cache { ...@@ -25,14 +25,14 @@ func newMemoryCache() *gotest.Cache {
Name: "bar", Name: "bar",
} }
testData := map[string]interface{}{ testData := map[string]any{
utils.Uint64ToStr(record1.ID): record1, utils.Uint64ToStr(record1.ID): record1,
utils.Uint64ToStr(record2.ID): record2, utils.Uint64ToStr(record2.ID): record2,
} }
c := gotest.NewCache(testData) c := gotest.NewCache(testData)
//cachePrefix := "" //cachePrefix := ""
//c.ICache = NewMemoryCache(cachePrefix, encoding.JSONEncoding{}, func() interface{} { //c.ICache = NewMemoryCache(cachePrefix, encoding.JSONEncoding{}, func() any {
// return &memoryUser{} // return &memoryUser{}
//}) //})
......
...@@ -23,11 +23,11 @@ type redisCache struct { ...@@ -23,11 +23,11 @@ type redisCache struct {
KeyPrefix string KeyPrefix string
encoding encoding.Encoding encoding encoding.Encoding
DefaultExpireTime time.Duration DefaultExpireTime time.Duration
newObject func() interface{} newObject func() any
} }
// NewRedisCache new a cache, client parameter can be passed in for unit testing // NewRedisCache new a cache, client parameter can be passed in for unit testing
func NewRedisCache(client *redis.Client, keyPrefix string, encode encoding.Encoding, newObject func() interface{}) Cache { func NewRedisCache(client *redis.Client, keyPrefix string, encode encoding.Encoding, newObject func() any) Cache {
return &redisCache{ return &redisCache{
client: client, client: client,
KeyPrefix: keyPrefix, KeyPrefix: keyPrefix,
...@@ -49,7 +49,7 @@ func (c *redisCache) IncrBy(ctx context.Context, key string, val int64) (int64, ...@@ -49,7 +49,7 @@ func (c *redisCache) IncrBy(ctx context.Context, key string, val int64) (int64,
} }
// Set one value // Set one value
func (c *redisCache) Set(ctx context.Context, key string, val interface{}, expiration time.Duration) error { func (c *redisCache) Set(ctx context.Context, key string, val any, expiration time.Duration) error {
buf, err := encoding.Marshal(c.encoding, val) buf, err := encoding.Marshal(c.encoding, val)
if err != nil { if err != nil {
return xerror.Errorf("encoding.Marshal error: %v, key=%s, val=%+v ", err, key, val) return xerror.Errorf("encoding.Marshal error: %v, key=%s, val=%+v ", err, key, val)
...@@ -73,7 +73,7 @@ func (c *redisCache) Set(ctx context.Context, key string, val interface{}, expir ...@@ -73,7 +73,7 @@ func (c *redisCache) Set(ctx context.Context, key string, val interface{}, expir
} }
// Get one value // Get one value
func (c *redisCache) Get(ctx context.Context, key string, val interface{}) error { func (c *redisCache) Get(ctx context.Context, key string, val any) error {
cacheKey, err := BuildCacheKey(c.KeyPrefix, key) cacheKey, err := BuildCacheKey(c.KeyPrefix, key)
if err != nil { if err != nil {
return xerror.Errorf("BuildCacheKey error: %v, key=%s", err, key) return xerror.Errorf("BuildCacheKey error: %v, key=%s", err, key)
...@@ -99,7 +99,7 @@ func (c *redisCache) Get(ctx context.Context, key string, val interface{}) error ...@@ -99,7 +99,7 @@ func (c *redisCache) Get(ctx context.Context, key string, val interface{}) error
} }
// MultiSet set multiple values // MultiSet set multiple values
func (c *redisCache) MultiSet(ctx context.Context, valueMap map[string]interface{}, expiration time.Duration) error { func (c *redisCache) MultiSet(ctx context.Context, valueMap map[string]any, expiration time.Duration) error {
if len(valueMap) == 0 { if len(valueMap) == 0 {
return nil return nil
} }
...@@ -108,7 +108,7 @@ func (c *redisCache) MultiSet(ctx context.Context, valueMap map[string]interface ...@@ -108,7 +108,7 @@ func (c *redisCache) MultiSet(ctx context.Context, valueMap map[string]interface
//} //}
// the key-value is paired and has twice the capacity of a map // the key-value is paired and has twice the capacity of a map
paris := make([]interface{}, 0, 2*len(valueMap)) paris := make([]any, 0, 2*len(valueMap))
for key, value := range valueMap { for key, value := range valueMap {
buf, err := encoding.Marshal(c.encoding, value) buf, err := encoding.Marshal(c.encoding, value)
if err != nil { if err != nil {
...@@ -144,7 +144,7 @@ func (c *redisCache) MultiSet(ctx context.Context, valueMap map[string]interface ...@@ -144,7 +144,7 @@ func (c *redisCache) MultiSet(ctx context.Context, valueMap map[string]interface
} }
// MultiGet get multiple values // MultiGet get multiple values
func (c *redisCache) MultiGet(ctx context.Context, keys []string, value interface{}) error { func (c *redisCache) MultiGet(ctx context.Context, keys []string, value any) error {
if len(keys) == 0 { if len(keys) == 0 {
return nil return nil
} }
...@@ -251,11 +251,11 @@ type redisClusterCache struct { ...@@ -251,11 +251,11 @@ type redisClusterCache struct {
KeyPrefix string KeyPrefix string
encoding encoding.Encoding encoding encoding.Encoding
DefaultExpireTime time.Duration DefaultExpireTime time.Duration
newObject func() interface{} newObject func() any
} }
// NewRedisClusterCache new a cache // NewRedisClusterCache new a cache
func NewRedisClusterCache(client *redis.ClusterClient, keyPrefix string, encode encoding.Encoding, newObject func() interface{}) Cache { func NewRedisClusterCache(client *redis.ClusterClient, keyPrefix string, encode encoding.Encoding, newObject func() any) Cache {
return &redisClusterCache{ return &redisClusterCache{
client: client, client: client,
KeyPrefix: keyPrefix, KeyPrefix: keyPrefix,
...@@ -265,7 +265,7 @@ func NewRedisClusterCache(client *redis.ClusterClient, keyPrefix string, encode ...@@ -265,7 +265,7 @@ func NewRedisClusterCache(client *redis.ClusterClient, keyPrefix string, encode
} }
// Set one value // Set one value
func (c *redisClusterCache) Set(ctx context.Context, key string, val interface{}, expiration time.Duration) error { func (c *redisClusterCache) Set(ctx context.Context, key string, val any, expiration time.Duration) error {
buf, err := encoding.Marshal(c.encoding, val) buf, err := encoding.Marshal(c.encoding, val)
if err != nil { if err != nil {
return xerror.Errorf("encoding.Marshal error: %v, key=%s, val=%+v ", err, key, val) return xerror.Errorf("encoding.Marshal error: %v, key=%s, val=%+v ", err, key, val)
...@@ -301,7 +301,7 @@ func (c *redisClusterCache) IncrBy(ctx context.Context, key string, val int64) ( ...@@ -301,7 +301,7 @@ func (c *redisClusterCache) IncrBy(ctx context.Context, key string, val int64) (
} }
// Get one value // Get one value
func (c *redisClusterCache) Get(ctx context.Context, key string, val interface{}) error { func (c *redisClusterCache) Get(ctx context.Context, key string, val any) error {
cacheKey, err := BuildCacheKey(c.KeyPrefix, key) cacheKey, err := BuildCacheKey(c.KeyPrefix, key)
if err != nil { if err != nil {
return xerror.Errorf("BuildCacheKey error: %v, key=%s", err, key) return xerror.Errorf("BuildCacheKey error: %v, key=%s", err, key)
...@@ -327,12 +327,12 @@ func (c *redisClusterCache) Get(ctx context.Context, key string, val interface{} ...@@ -327,12 +327,12 @@ func (c *redisClusterCache) Get(ctx context.Context, key string, val interface{}
} }
// MultiSet set multiple values // MultiSet set multiple values
func (c *redisClusterCache) MultiSet(ctx context.Context, valueMap map[string]interface{}, expiration time.Duration) error { func (c *redisClusterCache) MultiSet(ctx context.Context, valueMap map[string]any, expiration time.Duration) error {
if len(valueMap) == 0 { if len(valueMap) == 0 {
return nil return nil
} }
// the key-value is paired and has twice the capacity of a map // the key-value is paired and has twice the capacity of a map
paris := make([]interface{}, 0, 2*len(valueMap)) paris := make([]any, 0, 2*len(valueMap))
for key, value := range valueMap { for key, value := range valueMap {
buf, err := encoding.Marshal(c.encoding, value) buf, err := encoding.Marshal(c.encoding, value)
if err != nil { if err != nil {
...@@ -368,7 +368,7 @@ func (c *redisClusterCache) MultiSet(ctx context.Context, valueMap map[string]in ...@@ -368,7 +368,7 @@ func (c *redisClusterCache) MultiSet(ctx context.Context, valueMap map[string]in
} }
// MultiGet get multiple values // MultiGet get multiple values
func (c *redisClusterCache) MultiGet(ctx context.Context, keys []string, value interface{}) error { func (c *redisClusterCache) MultiGet(ctx context.Context, keys []string, value any) error {
if len(keys) == 0 { if len(keys) == 0 {
return nil return nil
} }
......
...@@ -16,7 +16,7 @@ type redisUser struct { ...@@ -16,7 +16,7 @@ type redisUser struct {
Name string Name string
} }
func newTestData() map[string]interface{} { func newTestData() map[string]any {
record1 := &redisUser{ record1 := &redisUser{
ID: 1, ID: 1,
Name: "foo", Name: "foo",
...@@ -26,7 +26,7 @@ func newTestData() map[string]interface{} { ...@@ -26,7 +26,7 @@ func newTestData() map[string]interface{} {
Name: "bar", Name: "bar",
} }
return map[string]interface{}{ return map[string]any{
utils.Uint64ToStr(record1.ID): record1, utils.Uint64ToStr(record1.ID): record1,
utils.Uint64ToStr(record2.ID): record2, utils.Uint64ToStr(record2.ID): record2,
} }
...@@ -36,7 +36,7 @@ func newRedisCache() *gotest.Cache { ...@@ -36,7 +36,7 @@ func newRedisCache() *gotest.Cache {
testData := newTestData() testData := newTestData()
c := gotest.NewCache(testData) c := gotest.NewCache(testData)
cachePrefix := "" cachePrefix := ""
c.ICache = NewRedisCache(c.RedisClient, cachePrefix, encoding.JSONEncoding{}, func() interface{} { c.ICache = NewRedisCache(c.RedisClient, cachePrefix, encoding.JSONEncoding{}, func() any {
return &redisUser{} return &redisUser{}
}) })
...@@ -47,7 +47,7 @@ func newRedisClusterCache() *gotest.RCCache { ...@@ -47,7 +47,7 @@ func newRedisClusterCache() *gotest.RCCache {
testData := newTestData() testData := newTestData()
c := gotest.NewRCCache(testData) c := gotest.NewRCCache(testData)
cachePrefix := "" cachePrefix := ""
c.ICache = NewRedisClusterCache(c.RedisClient, cachePrefix, encoding.JSONEncoding{}, func() interface{} { c.ICache = NewRedisClusterCache(c.RedisClient, cachePrefix, encoding.JSONEncoding{}, func() any {
return &redisUser{} return &redisUser{}
}) })
......
...@@ -11,7 +11,7 @@ func (c *Counter) Incr() { ...@@ -11,7 +11,7 @@ func (c *Counter) Incr() {
} }
func ExampleGroup_Get() { func ExampleGroup_Get() {
group := NewGroup(func() interface{} { group := NewGroup(func() any {
fmt.Println("Only Once") fmt.Println("Only Once")
return &Counter{} return &Counter{}
}) })
...@@ -26,12 +26,12 @@ func ExampleGroup_Get() { ...@@ -26,12 +26,12 @@ func ExampleGroup_Get() {
} }
func ExampleGroup_Reset() { func ExampleGroup_Reset() {
group := NewGroup(func() interface{} { group := NewGroup(func() any {
return &Counter{} return &Counter{}
}) })
// Reset the new function and clear all created objects. // Reset the new function and clear all created objects.
group.Reset(func() interface{} { group.Reset(func() any {
fmt.Println("reset") fmt.Println("reset")
return &Counter{} return &Counter{}
}) })
......
...@@ -7,24 +7,24 @@ import "sync" ...@@ -7,24 +7,24 @@ import "sync"
// Group is a lazy load container. // Group is a lazy load container.
type Group struct { type Group struct {
new func() interface{} new func() any
vals map[string]interface{} vals map[string]any
sync.RWMutex sync.RWMutex
} }
// NewGroup news a group container. // NewGroup news a group container.
func NewGroup(fn func() interface{}) *Group { func NewGroup(fn func() any) *Group {
if fn == nil { if fn == nil {
panic("container.group: can't assign a nil to the new function") panic("container.group: can't assign a nil to the new function")
} }
return &Group{ return &Group{
new: fn, new: fn,
vals: make(map[string]interface{}), vals: make(map[string]any),
} }
} }
// Get gets the object by the given key. // Get gets the object by the given key.
func (g *Group) Get(key string) interface{} { func (g *Group) Get(key string) any {
g.RLock() g.RLock()
v, ok := g.vals[key] v, ok := g.vals[key]
if ok { if ok {
...@@ -46,7 +46,7 @@ func (g *Group) Get(key string) interface{} { ...@@ -46,7 +46,7 @@ func (g *Group) Get(key string) interface{} {
} }
// Reset resets the new function and deletes all existing objects. // Reset resets the new function and deletes all existing objects.
func (g *Group) Reset(fn func() interface{}) { func (g *Group) Reset(fn func() any) {
if fn == nil { if fn == nil {
panic("container.group: can't assign a nil to the new function") panic("container.group: can't assign a nil to the new function")
} }
...@@ -59,6 +59,6 @@ func (g *Group) Reset(fn func() interface{}) { ...@@ -59,6 +59,6 @@ func (g *Group) Reset(fn func() interface{}) {
// Clear deletes all objects. // Clear deletes all objects.
func (g *Group) Clear() { func (g *Group) Clear() {
g.Lock() g.Lock()
g.vals = make(map[string]interface{}) g.vals = make(map[string]any)
g.Unlock() g.Unlock()
} }
...@@ -7,7 +7,7 @@ import ( ...@@ -7,7 +7,7 @@ import (
func TestGroupGet(t *testing.T) { func TestGroupGet(t *testing.T) {
count := 0 count := 0
g := NewGroup(func() interface{} { g := NewGroup(func() any {
count++ count++
return count return count
}) })
...@@ -31,12 +31,12 @@ func TestGroupGet(t *testing.T) { ...@@ -31,12 +31,12 @@ func TestGroupGet(t *testing.T) {
} }
func TestGroupReset(t *testing.T) { func TestGroupReset(t *testing.T) {
g := NewGroup(func() interface{} { g := NewGroup(func() any {
return 1 return 1
}) })
g.Get("key") g.Get("key")
call := false call := false
g.Reset(func() interface{} { g.Reset(func() any {
call = true call = true
return 1 return 1
}) })
...@@ -56,7 +56,7 @@ func TestGroupReset(t *testing.T) { ...@@ -56,7 +56,7 @@ func TestGroupReset(t *testing.T) {
} }
func TestGroupClear(t *testing.T) { func TestGroupClear(t *testing.T) {
g := NewGroup(func() interface{} { g := NewGroup(func() any {
return 1 return 1
}) })
g.Get("key") g.Get("key")
......
...@@ -18,9 +18,9 @@ var ( ...@@ -18,9 +18,9 @@ var (
// methods can be called from concurrent goroutines. // methods can be called from concurrent goroutines.
type Codec interface { type Codec interface {
// Marshal returns the wire format of v. // 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 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 // 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 // will be used as part of content type in transmission. The result must be
// static; the result cannot change between calls. // static; the result cannot change between calls.
...@@ -64,12 +64,12 @@ func GetCodec(contentSubtype string) Codec { ...@@ -64,12 +64,12 @@ func GetCodec(contentSubtype string) Codec {
// Encoding definition of coding interfaces // Encoding definition of coding interfaces
type Encoding interface { type Encoding interface {
Marshal(v interface{}) ([]byte, error) Marshal(v any) ([]byte, error)
Unmarshal(data []byte, v interface{}) error Unmarshal(data []byte, v any) error
} }
// Marshal encode data // Marshal encode data
func Marshal(e Encoding, v interface{}) (data []byte, err error) { func Marshal(e Encoding, v any) (data []byte, err error) {
if isPointer(v) { if isPointer(v) {
bm, ok := v.(encoding.BinaryMarshaler) bm, ok := v.(encoding.BinaryMarshaler)
if ok { if ok {
...@@ -80,7 +80,7 @@ func Marshal(e Encoding, v interface{}) (data []byte, err error) { ...@@ -80,7 +80,7 @@ func Marshal(e Encoding, v interface{}) (data []byte, err error) {
} }
// Unmarshal decode data // Unmarshal decode data
func Unmarshal(e Encoding, data []byte, v interface{}) (err error) { func Unmarshal(e Encoding, data []byte, v any) (err error) {
if isPointer(v) { if isPointer(v) {
bm, ok := v.(encoding.BinaryUnmarshaler) bm, ok := v.(encoding.BinaryUnmarshaler)
if ok { if ok {
...@@ -90,7 +90,7 @@ func Unmarshal(e Encoding, data []byte, v interface{}) (err error) { ...@@ -90,7 +90,7 @@ func Unmarshal(e Encoding, data []byte, v interface{}) (err error) {
return e.Unmarshal(data, v) return e.Unmarshal(data, v)
} }
func isPointer(data interface{}) bool { func isPointer(data any) bool {
switch reflect.ValueOf(data).Kind() { switch reflect.ValueOf(data).Kind() {
case reflect.Ptr, reflect.Interface: case reflect.Ptr, reflect.Interface:
return true return true
......
...@@ -87,11 +87,11 @@ func TestEncodingError(t *testing.T) { ...@@ -87,11 +87,11 @@ func TestEncodingError(t *testing.T) {
type codec struct{} type codec struct{}
func (c codec) Marshal(v interface{}) ([]byte, error) { func (c codec) Marshal(v any) ([]byte, error) {
return []byte{}, nil return []byte{}, nil
} }
func (c codec) Unmarshal(data []byte, v interface{}) error { func (c codec) Unmarshal(data []byte, v any) error {
return nil return nil
} }
...@@ -121,11 +121,11 @@ func TestRegisterCodec2(t *testing.T) { ...@@ -121,11 +121,11 @@ func TestRegisterCodec2(t *testing.T) {
type encoder struct{} type encoder struct{}
func (e encoder) Marshal(v interface{}) ([]byte, error) { func (e encoder) Marshal(v any) ([]byte, error) {
return nil, errors.New("mock Marshal error") return nil, errors.New("mock Marshal error")
} }
func (e encoder) Unmarshal(data []byte, v interface{}) error { func (e encoder) Unmarshal(data []byte, v any) error {
return errors.New("mock Unmarshal error") return errors.New("mock Unmarshal error")
} }
......
...@@ -9,7 +9,7 @@ import ( ...@@ -9,7 +9,7 @@ import (
type GobEncoding struct{} type GobEncoding struct{}
// Marshal gob encode // Marshal gob encode
func (g GobEncoding) Marshal(v interface{}) ([]byte, error) { func (g GobEncoding) Marshal(v any) ([]byte, error) {
var ( var (
buffer bytes.Buffer buffer bytes.Buffer
) )
...@@ -19,7 +19,7 @@ func (g GobEncoding) Marshal(v interface{}) ([]byte, error) { ...@@ -19,7 +19,7 @@ func (g GobEncoding) Marshal(v interface{}) ([]byte, error) {
} }
// Unmarshal gob encode // Unmarshal gob encode
func (g GobEncoding) Unmarshal(data []byte, value interface{}) error { func (g GobEncoding) Unmarshal(data []byte, value any) error {
err := gob.NewDecoder(bytes.NewReader(data)).Decode(value) err := gob.NewDecoder(bytes.NewReader(data)).Decode(value)
if err != nil { if err != nil {
return err return err
......
...@@ -33,7 +33,7 @@ func init() { ...@@ -33,7 +33,7 @@ func init() {
type codec struct{} type codec struct{}
// Marshal object to data // Marshal object to data
func (codec) Marshal(v interface{}) ([]byte, error) { func (codec) Marshal(v any) ([]byte, error) {
switch m := v.(type) { switch m := v.(type) {
case json.Marshaler: case json.Marshaler:
return m.MarshalJSON() return m.MarshalJSON()
...@@ -45,7 +45,7 @@ func (codec) Marshal(v interface{}) ([]byte, error) { ...@@ -45,7 +45,7 @@ func (codec) Marshal(v interface{}) ([]byte, error) {
} }
// Unmarshal data to bytes // Unmarshal data to bytes
func (codec) Unmarshal(data []byte, v interface{}) error { func (codec) Unmarshal(data []byte, v any) error {
switch m := v.(type) { switch m := v.(type) {
case json.Unmarshaler: case json.Unmarshaler:
return m.UnmarshalJSON(data) return m.UnmarshalJSON(data)
......
...@@ -14,13 +14,13 @@ import ( ...@@ -14,13 +14,13 @@ import (
type JSONEncoding struct{} type JSONEncoding struct{}
// Marshal json encode // Marshal json encode
func (j JSONEncoding) Marshal(v interface{}) ([]byte, error) { func (j JSONEncoding) Marshal(v any) ([]byte, error) {
buf, err := json.Marshal(v) buf, err := json.Marshal(v)
return buf, err return buf, err
} }
// Unmarshal json decode // Unmarshal json decode
func (j JSONEncoding) Unmarshal(data []byte, value interface{}) error { func (j JSONEncoding) Unmarshal(data []byte, value any) error {
err := json.Unmarshal(data, value) err := json.Unmarshal(data, value)
if err != nil { if err != nil {
return err return err
...@@ -32,7 +32,7 @@ func (j JSONEncoding) Unmarshal(data []byte, value interface{}) error { ...@@ -32,7 +32,7 @@ func (j JSONEncoding) Unmarshal(data []byte, value interface{}) error {
type JSONGzipEncoding struct{} type JSONGzipEncoding struct{}
// Marshal json encode and gzip // Marshal json encode and gzip
func (jz JSONGzipEncoding) Marshal(v interface{}) ([]byte, error) { func (jz JSONGzipEncoding) Marshal(v any) ([]byte, error) {
buf, err := json.Marshal(v) buf, err := json.Marshal(v)
if err != nil { if err != nil {
return nil, err return nil, err
...@@ -45,7 +45,7 @@ func (jz JSONGzipEncoding) Marshal(v interface{}) ([]byte, error) { ...@@ -45,7 +45,7 @@ func (jz JSONGzipEncoding) Marshal(v interface{}) ([]byte, error) {
} }
// Unmarshal json encode and gzip // Unmarshal json encode and gzip
func (jz JSONGzipEncoding) Unmarshal(data []byte, value interface{}) error { func (jz JSONGzipEncoding) Unmarshal(data []byte, value any) error {
jsonData, err := GzipDecode(data) jsonData, err := GzipDecode(data)
if err != nil { if err != nil {
return err return err
...@@ -107,7 +107,7 @@ func GzipDecode(in []byte) ([]byte, error) { ...@@ -107,7 +107,7 @@ func GzipDecode(in []byte) ([]byte, error) {
type JSONSnappyEncoding struct{} type JSONSnappyEncoding struct{}
// Marshal serialization // Marshal serialization
func (s JSONSnappyEncoding) Marshal(v interface{}) (data []byte, err error) { func (s JSONSnappyEncoding) Marshal(v any) (data []byte, err error) {
b, err := json.Marshal(v) b, err := json.Marshal(v)
if err != nil { if err != nil {
return nil, err return nil, err
...@@ -117,7 +117,7 @@ func (s JSONSnappyEncoding) Marshal(v interface{}) (data []byte, err error) { ...@@ -117,7 +117,7 @@ func (s JSONSnappyEncoding) Marshal(v interface{}) (data []byte, err error) {
} }
// Unmarshal deserialization // Unmarshal deserialization
func (s JSONSnappyEncoding) Unmarshal(data []byte, value interface{}) error { func (s JSONSnappyEncoding) Unmarshal(data []byte, value any) error {
b, err := snappy.Decode(nil, data) b, err := snappy.Decode(nil, data)
if err != nil { if err != nil {
return err return err
......
...@@ -6,13 +6,13 @@ import "github.com/vmihailenco/msgpack" ...@@ -6,13 +6,13 @@ import "github.com/vmihailenco/msgpack"
type MsgPackEncoding struct{} type MsgPackEncoding struct{}
// Marshal msgpack encode // Marshal msgpack encode
func (mp MsgPackEncoding) Marshal(v interface{}) ([]byte, error) { func (mp MsgPackEncoding) Marshal(v any) ([]byte, error) {
buf, err := msgpack.Marshal(v) buf, err := msgpack.Marshal(v)
return buf, err return buf, err
} }
// Unmarshal msgpack decode // Unmarshal msgpack decode
func (mp MsgPackEncoding) Unmarshal(data []byte, value interface{}) error { func (mp MsgPackEncoding) Unmarshal(data []byte, value any) error {
err := msgpack.Unmarshal(data, value) err := msgpack.Unmarshal(data, value)
if err != nil { if err != nil {
return err return err
......
...@@ -19,7 +19,7 @@ func init() { ...@@ -19,7 +19,7 @@ func init() {
// codec is a Codec implementation with protobuf. It is the default codec for gRPC. // codec is a Codec implementation with protobuf. It is the default codec for gRPC.
type codec struct{} type codec struct{}
func (codec) Marshal(v interface{}) ([]byte, error) { func (codec) Marshal(v any) ([]byte, error) {
vv, ok := v.(proto.Message) vv, ok := v.(proto.Message)
if !ok { if !ok {
return nil, fmt.Errorf("failed to marshal, message is %T, want proto.Message", v) return nil, fmt.Errorf("failed to marshal, message is %T, want proto.Message", v)
...@@ -27,7 +27,7 @@ func (codec) Marshal(v interface{}) ([]byte, error) { ...@@ -27,7 +27,7 @@ func (codec) Marshal(v interface{}) ([]byte, error) {
return proto.Marshal(vv) return proto.Marshal(vv)
} }
func (codec) Unmarshal(data []byte, v interface{}) error { func (codec) Unmarshal(data []byte, v any) error {
vv, ok := v.(proto.Message) vv, ok := v.(proto.Message)
if !ok { if !ok {
return fmt.Errorf("failed to unmarshal, message is %T, want proto.Message", v) return fmt.Errorf("failed to unmarshal, message is %T, want proto.Message", v)
......
...@@ -16,7 +16,7 @@ var SkipResponse = errors.New("skip response") //nolint ...@@ -16,7 +16,7 @@ var SkipResponse = errors.New("skip response") //nolint
// Responser response interface // Responser response interface
type Responser interface { type Responser interface {
Success(ctx *gin.Context, data interface{}) Success(ctx *gin.Context, data any)
ParamError(ctx *gin.Context, err error) ParamError(ctx *gin.Context, err error)
Error(ctx *gin.Context, err error) bool Error(ctx *gin.Context, err error) bool
} }
...@@ -53,8 +53,8 @@ type defaultResponse struct { ...@@ -53,8 +53,8 @@ type defaultResponse struct {
rpcStatus map[int]*RPCStatus rpcStatus map[int]*RPCStatus
} }
func (resp *defaultResponse) response(c *gin.Context, respStatus, code int, msg string, data interface{}) { func (resp *defaultResponse) response(c *gin.Context, respStatus, code int, msg string, data any) {
c.JSON(respStatus, map[string]interface{}{ c.JSON(respStatus, map[string]any{
"code": code, "code": code,
"msg": msg, "msg": msg,
"data": data, "data": data,
...@@ -62,7 +62,7 @@ func (resp *defaultResponse) response(c *gin.Context, respStatus, code int, msg ...@@ -62,7 +62,7 @@ func (resp *defaultResponse) response(c *gin.Context, respStatus, code int, msg
} }
// Success response success information // Success response success information
func (resp *defaultResponse) Success(c *gin.Context, data interface{}) { func (resp *defaultResponse) Success(c *gin.Context, data any) {
resp.response(c, http.StatusOK, 0, "ok", data) resp.response(c, http.StatusOK, 0, "ok", data)
} }
......
...@@ -39,7 +39,7 @@ msg2 = %s ...@@ -39,7 +39,7 @@ msg2 = %s
// Detail error details // Detail error details
type Detail struct { type Detail struct {
key string key string
val interface{} val any
} }
// String detail key-value // String detail key-value
...@@ -48,7 +48,7 @@ func (d *Detail) String() string { ...@@ -48,7 +48,7 @@ func (d *Detail) String() string {
} }
// Any type key value // Any type key value
func Any(key string, val interface{}) Detail { func Any(key string, val any) Detail {
return Detail{ return Detail{
key: key, key: key,
val: val, val: val,
......
...@@ -8,15 +8,15 @@ import ( ...@@ -8,15 +8,15 @@ import (
) )
type BusSubscriber interface { type BusSubscriber interface {
Subscribe(topic string, fn interface{}) error Subscribe(topic string, fn any) error
SubscribeAsync(topic string, fn interface{}, transactional bool) error SubscribeAsync(topic string, fn any, transactional bool) error
SubscribeOnce(topic string, fn interface{}) error SubscribeOnce(topic string, fn any) error
SubscribeOnceAsync(topic string, fn interface{}) error SubscribeOnceAsync(topic string, fn any) error
Unsubscribe(topic string, handler interface{}) error Unsubscribe(topic string, handler any) error
} }
type BusPublisher interface { type BusPublisher interface {
Publish(ctx context.Context, topic string, args ...interface{}) Publish(ctx context.Context, topic string, args ...any)
} }
type BusController interface { type BusController interface {
...@@ -53,7 +53,7 @@ func New() Bus { ...@@ -53,7 +53,7 @@ func New() Bus {
return Bus(b) return Bus(b)
} }
func (bus *EventBus) doSubscribe(topic string, fn interface{}, handler *eventHandler) error { func (bus *EventBus) doSubscribe(topic string, fn any, handler *eventHandler) error {
bus.lock.Lock() bus.lock.Lock()
defer bus.lock.Unlock() defer bus.lock.Unlock()
if !(reflect.TypeOf(fn).Kind() == reflect.Func) { if !(reflect.TypeOf(fn).Kind() == reflect.Func) {
...@@ -63,25 +63,25 @@ func (bus *EventBus) doSubscribe(topic string, fn interface{}, handler *eventHan ...@@ -63,25 +63,25 @@ func (bus *EventBus) doSubscribe(topic string, fn interface{}, handler *eventHan
return nil return nil
} }
func (bus *EventBus) Subscribe(topic string, fn interface{}) error { func (bus *EventBus) Subscribe(topic string, fn any) error {
return bus.doSubscribe(topic, fn, &eventHandler{ return bus.doSubscribe(topic, fn, &eventHandler{
reflect.ValueOf(fn), false, false, false, sync.Mutex{}, reflect.ValueOf(fn), false, false, false, sync.Mutex{},
}) })
} }
func (bus *EventBus) SubscribeAsync(topic string, fn interface{}, transactional bool) error { func (bus *EventBus) SubscribeAsync(topic string, fn any, transactional bool) error {
return bus.doSubscribe(topic, fn, &eventHandler{ return bus.doSubscribe(topic, fn, &eventHandler{
reflect.ValueOf(fn), false, true, transactional, sync.Mutex{}, reflect.ValueOf(fn), false, true, transactional, sync.Mutex{},
}) })
} }
func (bus *EventBus) SubscribeOnce(topic string, fn interface{}) error { func (bus *EventBus) SubscribeOnce(topic string, fn any) error {
return bus.doSubscribe(topic, fn, &eventHandler{ return bus.doSubscribe(topic, fn, &eventHandler{
reflect.ValueOf(fn), true, false, false, sync.Mutex{}, reflect.ValueOf(fn), true, false, false, sync.Mutex{},
}) })
} }
func (bus *EventBus) SubscribeOnceAsync(topic string, fn interface{}) error { func (bus *EventBus) SubscribeOnceAsync(topic string, fn any) error {
return bus.doSubscribe(topic, fn, &eventHandler{ return bus.doSubscribe(topic, fn, &eventHandler{
reflect.ValueOf(fn), true, true, false, sync.Mutex{}, reflect.ValueOf(fn), true, true, false, sync.Mutex{},
}) })
...@@ -97,7 +97,7 @@ func (bus *EventBus) HasCallback(topic string) bool { ...@@ -97,7 +97,7 @@ func (bus *EventBus) HasCallback(topic string) bool {
return false return false
} }
func (bus *EventBus) Unsubscribe(topic string, handler interface{}) error { func (bus *EventBus) Unsubscribe(topic string, handler any) error {
bus.lock.Lock() bus.lock.Lock()
defer bus.lock.Unlock() defer bus.lock.Unlock()
if _, ok := bus.handlers[topic]; ok && len(bus.handlers[topic]) > 0 { if _, ok := bus.handlers[topic]; ok && len(bus.handlers[topic]) > 0 {
...@@ -107,7 +107,7 @@ func (bus *EventBus) Unsubscribe(topic string, handler interface{}) error { ...@@ -107,7 +107,7 @@ func (bus *EventBus) Unsubscribe(topic string, handler interface{}) error {
return fmt.Errorf("topic %s doesn't exist", topic) return fmt.Errorf("topic %s doesn't exist", topic)
} }
func (bus *EventBus) Publish(ctx context.Context, topic string, args ...interface{}) { func (bus *EventBus) Publish(ctx context.Context, topic string, args ...any) {
bus.lock.Lock() bus.lock.Lock()
defer bus.lock.Unlock() defer bus.lock.Unlock()
if handlers, ok := bus.handlers[topic]; ok && 0 < len(handlers) { if handlers, ok := bus.handlers[topic]; ok && 0 < len(handlers) {
...@@ -134,7 +134,7 @@ func (bus *EventBus) Publish(ctx context.Context, topic string, args ...interfac ...@@ -134,7 +134,7 @@ func (bus *EventBus) Publish(ctx context.Context, topic string, args ...interfac
} }
} }
func (bus *EventBus) doPublish(ctx context.Context, handler *eventHandler, args ...interface{}) { func (bus *EventBus) doPublish(ctx context.Context, handler *eventHandler, args ...any) {
allArgs := make([]any, 0, len(args)+1) allArgs := make([]any, 0, len(args)+1)
allArgs = append(allArgs, ctx) allArgs = append(allArgs, ctx)
allArgs = append(allArgs, args...) allArgs = append(allArgs, args...)
...@@ -142,7 +142,7 @@ func (bus *EventBus) doPublish(ctx context.Context, handler *eventHandler, args ...@@ -142,7 +142,7 @@ func (bus *EventBus) doPublish(ctx context.Context, handler *eventHandler, args
handler.callBack.Call(passedArguments) handler.callBack.Call(passedArguments)
} }
func (bus *EventBus) doPublishAsync(ctx context.Context, handler *eventHandler, args ...interface{}) { func (bus *EventBus) doPublishAsync(ctx context.Context, handler *eventHandler, args ...any) {
defer bus.wg.Done() defer bus.wg.Done()
if handler.transactional { if handler.transactional {
defer handler.Unlock() defer handler.Unlock()
...@@ -177,7 +177,7 @@ func (bus *EventBus) findHandlerIdx(topic string, callback reflect.Value) int { ...@@ -177,7 +177,7 @@ func (bus *EventBus) findHandlerIdx(topic string, callback reflect.Value) int {
return -1 return -1
} }
func (bus *EventBus) setUpPublish(callback *eventHandler, args ...interface{}) []reflect.Value { func (bus *EventBus) setUpPublish(callback *eventHandler, args ...any) []reflect.Value {
funcType := callback.callBack.Type() funcType := callback.callBack.Type()
passedArguments := make([]reflect.Value, len(args)) passedArguments := make([]reflect.Value, len(args))
for i, v := range args { for i, v := range args {
......
...@@ -114,7 +114,7 @@ func IsRunningTask(name string) bool { ...@@ -114,7 +114,7 @@ func IsRunningTask(name string) bool {
// GetRunningTaskNames gets a list of running task names // GetRunningTaskNames gets a list of running task names
func GetRunningTaskNames() []string { func GetRunningTaskNames() []string {
var names []string var names []string
nameID.Range(func(key, value interface{}) bool { nameID.Range(func(key, value any) bool {
names = append(names, key.(string)) names = append(names, key.(string))
return true return true
}) })
...@@ -124,7 +124,7 @@ func GetRunningTaskNames() []string { ...@@ -124,7 +124,7 @@ func GetRunningTaskNames() []string {
// GetRunningTasks gets a list of running task names // GetRunningTasks gets a list of running task names
func GetRunningTasks() []*Task { func GetRunningTasks() []*Task {
var ts []*Task var ts []*Task
taskMap.Range(func(key, value interface{}) bool { taskMap.Range(func(key, value any) bool {
ts = append(ts, value.(*Task)) ts = append(ts, value.(*Task))
return true return true
}) })
......
...@@ -65,7 +65,7 @@ type zapLog struct { ...@@ -65,7 +65,7 @@ type zapLog struct {
} }
// Info print info // Info print info
func (l *zapLog) Info(msg string, keysAndValues ...interface{}) { func (l *zapLog) Info(msg string, keysAndValues ...any) {
if l.zapLog == nil || l.isOnlyPrintError { if l.zapLog == nil || l.isOnlyPrintError {
return return
} }
...@@ -78,7 +78,7 @@ func (l *zapLog) Info(msg string, keysAndValues ...interface{}) { ...@@ -78,7 +78,7 @@ func (l *zapLog) Info(msg string, keysAndValues ...interface{}) {
} }
// Error print error // Error print error
func (l *zapLog) Error(err error, msg string, keysAndValues ...interface{}) { func (l *zapLog) Error(err error, msg string, keysAndValues ...any) {
if l.zapLog == nil { if l.zapLog == nil {
return return
} }
...@@ -88,10 +88,10 @@ func (l *zapLog) Error(err error, msg string, keysAndValues ...interface{}) { ...@@ -88,10 +88,10 @@ func (l *zapLog) Error(err error, msg string, keysAndValues ...interface{}) {
l.zapLog.Error(msg, fields...) l.zapLog.Error(msg, fields...)
} }
func parseKVs(kvs interface{}) []zap.Field { func parseKVs(kvs any) []zap.Field {
var fields []zap.Field var fields []zap.Field
infos, ok := kvs.([]interface{}) infos, ok := kvs.([]any)
if !ok { if !ok {
return fields return fields
} }
......
...@@ -12,16 +12,16 @@ import ( ...@@ -12,16 +12,16 @@ import (
// Cache redis cache // Cache redis cache
type Cache struct { type Cache struct {
Ctx context.Context Ctx context.Context
TestDataSlice []interface{} TestDataSlice []any
TestDataMap map[string]interface{} TestDataMap map[string]any
RedisClient *redis.Client RedisClient *redis.Client
redisServer *miniredis.Miniredis redisServer *miniredis.Miniredis
ICache interface{} ICache any
} }
// NewCache instantiated redis cache // NewCache instantiated redis cache
func NewCache(testDataMap map[string]interface{}) *Cache { func NewCache(testDataMap map[string]any) *Cache {
var tds []interface{} var tds []any
for _, data := range testDataMap { for _, data := range testDataMap {
tds = append(tds, data) tds = append(tds, data)
} }
...@@ -64,7 +64,7 @@ func (c *Cache) GetFields() []string { ...@@ -64,7 +64,7 @@ func (c *Cache) GetFields() []string {
} }
// GetTestData get test data // GetTestData get test data
func (c *Cache) GetTestData() map[string]interface{} { func (c *Cache) GetTestData() map[string]any {
return c.TestDataMap return c.TestDataMap
} }
...@@ -73,16 +73,16 @@ func (c *Cache) GetTestData() map[string]interface{} { ...@@ -73,16 +73,16 @@ func (c *Cache) GetTestData() map[string]interface{} {
// RCCache redis cluster cache // RCCache redis cluster cache
type RCCache struct { type RCCache struct {
Ctx context.Context Ctx context.Context
TestDataSlice []interface{} TestDataSlice []any
TestDataMap map[string]interface{} TestDataMap map[string]any
RedisClient *redis.ClusterClient RedisClient *redis.ClusterClient
redisServer *miniredis.Miniredis redisServer *miniredis.Miniredis
ICache interface{} ICache any
} }
// NewRCCache instantiated redis cluster cache // NewRCCache instantiated redis cluster cache
func NewRCCache(testDataMap map[string]interface{}) *RCCache { func NewRCCache(testDataMap map[string]any) *RCCache {
var tds []interface{} var tds []any
for _, data := range testDataMap { for _, data := range testDataMap {
tds = append(tds, data) tds = append(tds, data)
} }
...@@ -116,6 +116,6 @@ func (c *RCCache) GetIDs() []uint64 { ...@@ -116,6 +116,6 @@ func (c *RCCache) GetIDs() []uint64 {
} }
// GetTestData get test data // GetTestData get test data
func (c *RCCache) GetTestData() map[string]interface{} { func (c *RCCache) GetTestData() map[string]any {
return c.TestDataMap return c.TestDataMap
} }
...@@ -4,8 +4,8 @@ import ( ...@@ -4,8 +4,8 @@ import (
"testing" "testing"
) )
func getTestData() map[string]interface{} { func getTestData() map[string]any {
return map[string]interface{}{ return map[string]any{
"1": "foo", "1": "foo",
"2": "bar", "2": "bar",
} }
......
...@@ -15,17 +15,17 @@ import ( ...@@ -15,17 +15,17 @@ import (
// Dao dao info // Dao dao info
type Dao struct { type Dao struct {
Ctx context.Context Ctx context.Context
TestData interface{} TestData any
SQLMock sqlmock.Sqlmock SQLMock sqlmock.Sqlmock
Cache *Cache Cache *Cache
DB *gorm.DB DB *gorm.DB
IDao interface{} IDao any
AnyTime *anyTime AnyTime *anyTime
closeFns []func() closeFns []func()
} }
// NewDao instantiated dao // NewDao instantiated dao
func NewDao(c *Cache, testData interface{}) *Dao { func NewDao(c *Cache, testData any) *Dao {
var closeFns []func() var closeFns []func()
if c != nil { if c != nil {
...@@ -74,7 +74,7 @@ func (d *Dao) Close() { ...@@ -74,7 +74,7 @@ func (d *Dao) Close() {
} }
// GetAnyArgs Dynamic generation of parameter types based on structures // GetAnyArgs Dynamic generation of parameter types based on structures
func (d *Dao) GetAnyArgs(obj interface{}) []driver.Value { func (d *Dao) GetAnyArgs(obj any) []driver.Value {
to := reflect.TypeOf(obj) to := reflect.TypeOf(obj)
vo := reflect.ValueOf(obj) vo := reflect.ValueOf(obj)
......
...@@ -89,7 +89,7 @@ func (d *userDao) UpdateByID(ctx context.Context, table *User) error { ...@@ -89,7 +89,7 @@ func (d *userDao) UpdateByID(ctx context.Context, table *User) error {
return errors.New("id cannot be 0") return errors.New("id cannot be 0")
} }
update := map[string]interface{}{} update := map[string]any{}
if table.Name != "" { if table.Name != "" {
update["name"] = table.Name update["name"] = table.Name
} }
...@@ -147,7 +147,7 @@ func newTestUserDao() *Dao { ...@@ -147,7 +147,7 @@ func newTestUserDao() *Dao {
} }
// init mock cache, to test mysql, disable caching // init mock cache, to test mysql, disable caching
c := NewCache(map[string]interface{}{"no cache": testData}) c := NewCache(map[string]any{"no cache": testData})
// init mock dao // init mock dao
d := NewDao(c, testData) d := NewDao(c, testData)
......
...@@ -14,9 +14,9 @@ import ( ...@@ -14,9 +14,9 @@ import (
// Handler info // Handler info
type Handler struct { type Handler struct {
TestData interface{} TestData any
MockDao *Dao MockDao *Dao
IHandler interface{} IHandler any
Engine *gin.Engine Engine *gin.Engine
HTTPServer *http.Server HTTPServer *http.Server
...@@ -34,7 +34,7 @@ type RouterInfo struct { ...@@ -34,7 +34,7 @@ type RouterInfo struct {
} }
// NewHandler instantiated handler // NewHandler instantiated handler
func NewHandler(dao *Dao, testData interface{}) *Handler { func NewHandler(dao *Dao, testData any) *Handler {
serverAddr, requestAddr := utils.GetLocalHTTPAddrPairs() serverAddr, requestAddr := utils.GetLocalHTTPAddrPairs()
return &Handler{ return &Handler{
...@@ -85,7 +85,7 @@ func (h *Handler) GoRunHTTPServer(fns []RouterInfo) { ...@@ -85,7 +85,7 @@ func (h *Handler) GoRunHTTPServer(fns []RouterInfo) {
} }
// GetRequestURL get request url from name // GetRequestURL get request url from name
func (h *Handler) GetRequestURL(funcName string, pathVal ...interface{}) string { func (h *Handler) GetRequestURL(funcName string, pathVal ...any) string {
fn, ok := h.routers[strings.ToLower(funcName)] fn, ok := h.routers[strings.ToLower(funcName)]
if !ok { if !ok {
return "" return ""
......
...@@ -10,13 +10,13 @@ import ( ...@@ -10,13 +10,13 @@ import (
) )
func newHandler() *Handler { func newHandler() *Handler {
var testData = map[string]interface{}{ var testData = map[string]any{
"1": "foo", "1": "foo",
"2": "bar", "2": "bar",
} }
// init mock cache // init mock cache
c := NewCache(map[string]interface{}{"no cache": testData}) c := NewCache(map[string]any{"no cache": testData})
c.ICache = struct{}{} // instantiated cache interface c.ICache = struct{}{} // instantiated cache interface
// init mock dao // init mock dao
......
...@@ -15,7 +15,7 @@ import ( ...@@ -15,7 +15,7 @@ import (
// Service info // Service info
type Service struct { type Service struct {
Ctx context.Context Ctx context.Context
TestData interface{} TestData any
MockDao *Dao MockDao *Dao
Server *grpc.Server Server *grpc.Server
...@@ -23,11 +23,11 @@ type Service struct { ...@@ -23,11 +23,11 @@ type Service struct {
clientAddr string clientAddr string
clientConn *grpc.ClientConn clientConn *grpc.ClientConn
IServiceClient interface{} IServiceClient any
} }
// NewService instantiated service // NewService instantiated service
func NewService(dao *Dao, testData interface{}) *Service { func NewService(dao *Dao, testData any) *Service {
port, _ := utils.GetAvailablePort() port, _ := utils.GetAvailablePort()
clientAddr := fmt.Sprintf("127.0.0.1:%d", port) clientAddr := fmt.Sprintf("127.0.0.1:%d", port)
......
...@@ -9,13 +9,13 @@ import ( ...@@ -9,13 +9,13 @@ import (
) )
func newService() *Service { func newService() *Service {
var testData = map[string]interface{}{ var testData = map[string]any{
"1": "foo", "1": "foo",
"2": "bar", "2": "bar",
} }
// init mock cache // init mock cache
c := NewCache(map[string]interface{}{"no cache": testData}) c := NewCache(map[string]any{"no cache": testData})
c.ICache = struct{}{} // instantiated cache interface c.ICache = struct{}{} // instantiated cache interface
// init mock dao // init mock dao
...@@ -56,7 +56,7 @@ func TestService_GoGrpcServer(t *testing.T) { ...@@ -56,7 +56,7 @@ func TestService_GoGrpcServer(t *testing.T) {
} }
func TestServiceError(t *testing.T) { func TestServiceError(t *testing.T) {
var testData = map[string]interface{}{ var testData = map[string]any{
"1": "foo", "1": "foo",
"2": "bar", "2": "bar",
} }
......
...@@ -29,9 +29,9 @@ type Request struct { ...@@ -29,9 +29,9 @@ type Request struct {
url string url string
method string method string
headers map[string]string headers map[string]string
params map[string]interface{} // parameters after URL params map[string]any // parameters after URL
reqBody []byte // Body data reqBody []byte // Body data
reqBodyJSON interface{} // 传入对象,会自动json marshal reqBodyJSON any // 传入对象,会自动json marshal
timeout time.Duration // Client timeout timeout time.Duration // Client timeout
retryCount int retryCount int
...@@ -106,7 +106,7 @@ func (x *Request) SetURL(path string) *Request { ...@@ -106,7 +106,7 @@ func (x *Request) SetURL(path string) *Request {
} }
// SetParams parameters after setting the URL // SetParams parameters after setting the URL
func (x *Request) SetParams(params map[string]interface{}) *Request { func (x *Request) SetParams(params map[string]any) *Request {
if x.params == nil { if x.params == nil {
x.params = params x.params = params
} else { } else {
...@@ -118,16 +118,16 @@ func (x *Request) SetParams(params map[string]interface{}) *Request { ...@@ -118,16 +118,16 @@ func (x *Request) SetParams(params map[string]interface{}) *Request {
} }
// SetParam parameters after setting the URL // SetParam parameters after setting the URL
func (x *Request) SetParam(k string, v interface{}) *Request { func (x *Request) SetParam(k string, v any) *Request {
if x.params == nil { if x.params == nil {
x.params = make(map[string]interface{}) x.params = make(map[string]any)
} }
x.params[k] = v x.params[k] = v
return x return x
} }
// SetBody set body data, support string and []byte, if it is not string, it will be json marshal. // SetBody set body data, support string and []byte, if it is not string, it will be json marshal.
func (x *Request) SetBody(body interface{}) *Request { func (x *Request) SetBody(body any) *Request {
switch v := body.(type) { switch v := body.(type) {
case string: case string:
x.reqBody = []byte(v) x.reqBody = []byte(v)
...@@ -233,15 +233,15 @@ func (x *Request) PATCH(ctx context.Context) *Request { ...@@ -233,15 +233,15 @@ func (x *Request) PATCH(ctx context.Context) *Request {
} }
// Do a request // Do a request
func (x *Request) Do(ctx context.Context, method string, data interface{}) *Request { func (x *Request) Do(ctx context.Context, method string, data any) *Request {
x.method = method x.method = method
switch method { switch method {
case http.MethodGet: case http.MethodGet:
if data != nil { if data != nil {
if params, ok := data.(map[string]interface{}); ok { //nolint if params, ok := data.(map[string]any); ok { //nolint
x.SetParams(params) x.SetParams(params)
} else { } else {
x.err = errors.New("params is not a map[string]interface{}") x.err = errors.New("params is not a map[string]any")
return x return x
} }
} }
...@@ -454,7 +454,7 @@ func (x *Request) ReadRspBody() ([]byte, error) { ...@@ -454,7 +454,7 @@ func (x *Request) ReadRspBody() ([]byte, error) {
} }
// BindJSON parses the response's body as JSON // BindJSON parses the response's body as JSON
func (x *Request) BindJSON(v interface{}) *Request { func (x *Request) BindJSON(v any) *Request {
if v == nil { if v == nil {
return x return x
} }
...@@ -473,7 +473,7 @@ func (x *Request) BindJSON(v interface{}) *Request { ...@@ -473,7 +473,7 @@ func (x *Request) BindJSON(v interface{}) *Request {
type Option func(*options) type Option func(*options)
type options struct { type options struct {
params map[string]interface{} params map[string]any
headers map[string]string headers map[string]string
timeout time.Duration timeout time.Duration
} }
...@@ -489,7 +489,7 @@ func defaultOptions() *options { ...@@ -489,7 +489,7 @@ func defaultOptions() *options {
} }
// WithParams set params // WithParams set params
func WithParams(params map[string]interface{}) Option { func WithParams(params map[string]any) Option {
return func(o *options) { return func(o *options) {
o.params = params o.params = params
} }
...@@ -513,15 +513,15 @@ func WithTimeout(t time.Duration) Option { ...@@ -513,15 +513,15 @@ func WithTimeout(t time.Duration) Option {
type StdResult struct { type StdResult struct {
Code int `json:"code"` Code int `json:"code"`
Msg string `json:"msg"` Msg string `json:"msg"`
Data interface{} `json:"data,omitempty"` Data any `json:"data,omitempty"`
} }
// StdResult standard return data // StdResult standard return data
type StdResult2 struct { type StdResult2 struct {
Code int `json:"code"` Code int `json:"code"`
Msg string `json:"message"` Msg string `json:"message"`
Data interface{} `json:"data,omitempty"` Data any `json:"data,omitempty"`
} }
// KV string:interface{} // KV string:any
type KV = map[string]interface{} type KV = map[string]any
...@@ -57,7 +57,7 @@ func ParseToken(tokenString string) (*Claims, error) { ...@@ -57,7 +57,7 @@ func ParseToken(tokenString string) (*Claims, error) {
return nil, errInit return nil, errInit
} }
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) { token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (any, error) {
return opt.signingKey, nil return opt.signingKey, nil
}) })
if err != nil { if err != nil {
...@@ -86,7 +86,7 @@ func RefreshToken(tokenString string) (string, error) { ...@@ -86,7 +86,7 @@ func RefreshToken(tokenString string) (string, error) {
// ------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------
// KV map type // KV map type
type KV = map[string]interface{} type KV = map[string]any
// CustomClaims custom fields claims // CustomClaims custom fields claims
type CustomClaims struct { type CustomClaims struct {
...@@ -95,7 +95,7 @@ type CustomClaims struct { ...@@ -95,7 +95,7 @@ type CustomClaims struct {
} }
// Get custom field value by key, if not found, return false // Get custom field value by key, if not found, return false
func (c *CustomClaims) Get(key string) (val interface{}, isExist bool) { func (c *CustomClaims) Get(key string) (val any, isExist bool) {
if c.Fields == nil { if c.Fields == nil {
return nil, false return nil, false
} }
...@@ -142,7 +142,7 @@ func (c *CustomClaims) GetUint64(key string) (uint64, bool) { ...@@ -142,7 +142,7 @@ func (c *CustomClaims) GetUint64(key string) (uint64, bool) {
} }
// GenerateCustomToken generate token by custom fields, use CustomClaims // GenerateCustomToken generate token by custom fields, use CustomClaims
func GenerateCustomToken(kv map[string]interface{}) (string, error) { func GenerateCustomToken(kv map[string]any) (string, error) {
if opt == nil { if opt == nil {
return "", errInit return "", errInit
} }
...@@ -167,7 +167,7 @@ func ParseCustomToken(tokenString string) (*CustomClaims, error) { ...@@ -167,7 +167,7 @@ func ParseCustomToken(tokenString string) (*CustomClaims, error) {
} }
cc := &CustomClaims{} cc := &CustomClaims{}
token, err := jwt.ParseWithClaims(tokenString, cc, func(token *jwt.Token) (interface{}, error) { token, err := jwt.ParseWithClaims(tokenString, cc, func(token *jwt.Token) (any, error) {
return opt.signingKey, nil return opt.signingKey, nil
}) })
if err != nil { if err != nil {
......
...@@ -22,51 +22,51 @@ func ReplaceGRPCLoggerV2(l *zap.Logger) { ...@@ -22,51 +22,51 @@ func ReplaceGRPCLoggerV2(l *zap.Logger) {
grpclog.SetLoggerV2(zzl) grpclog.SetLoggerV2(zzl)
} }
func (l *grpcLogger) Info(args ...interface{}) { func (l *grpcLogger) Info(args ...any) {
l.zLog.Info(fmt.Sprint(args...)) l.zLog.Info(fmt.Sprint(args...))
} }
func (l *grpcLogger) Infoln(args ...interface{}) { func (l *grpcLogger) Infoln(args ...any) {
l.zLog.Info(fmt.Sprint(args...)) l.zLog.Info(fmt.Sprint(args...))
} }
func (l *grpcLogger) Infof(format string, args ...interface{}) { func (l *grpcLogger) Infof(format string, args ...any) {
l.zLog.Info(fmt.Sprintf(format, args...)) l.zLog.Info(fmt.Sprintf(format, args...))
} }
func (l *grpcLogger) Warning(args ...interface{}) { func (l *grpcLogger) Warning(args ...any) {
l.zLog.Warn(fmt.Sprint(args...)) l.zLog.Warn(fmt.Sprint(args...))
} }
func (l *grpcLogger) Warningln(args ...interface{}) { func (l *grpcLogger) Warningln(args ...any) {
l.zLog.Warn(fmt.Sprint(args...)) l.zLog.Warn(fmt.Sprint(args...))
} }
func (l *grpcLogger) Warningf(format string, args ...interface{}) { func (l *grpcLogger) Warningf(format string, args ...any) {
l.zLog.Warn(fmt.Sprintf(format, args...)) l.zLog.Warn(fmt.Sprintf(format, args...))
} }
func (l *grpcLogger) Error(args ...interface{}) { func (l *grpcLogger) Error(args ...any) {
l.zLog.Error(fmt.Sprint(args...)) l.zLog.Error(fmt.Sprint(args...))
} }
func (l *grpcLogger) Errorln(args ...interface{}) { func (l *grpcLogger) Errorln(args ...any) {
l.zLog.Error(fmt.Sprint(args...)) l.zLog.Error(fmt.Sprint(args...))
} }
func (l *grpcLogger) Errorf(format string, args ...interface{}) { func (l *grpcLogger) Errorf(format string, args ...any) {
l.zLog.Error(fmt.Sprintf(format, args...)) l.zLog.Error(fmt.Sprintf(format, args...))
} }
func (l *grpcLogger) Fatal(args ...interface{}) { func (l *grpcLogger) Fatal(args ...any) {
l.zLog.Fatal(fmt.Sprint(args...)) l.zLog.Fatal(fmt.Sprint(args...))
} }
func (l *grpcLogger) Fatalln(args ...interface{}) { func (l *grpcLogger) Fatalln(args ...any) {
l.zLog.Fatal(fmt.Sprint(args...)) l.zLog.Fatal(fmt.Sprint(args...))
} }
func (l *grpcLogger) Fatalf(format string, args ...interface{}) { func (l *grpcLogger) Fatalf(format string, args ...any) {
l.zLog.Fatal(fmt.Sprintf(format, args...)) l.zLog.Fatal(fmt.Sprintf(format, args...))
} }
......
...@@ -37,27 +37,27 @@ func Fatal(msg string, fields ...Field) { ...@@ -37,27 +37,27 @@ func Fatal(msg string, fields ...Field) {
} }
// Debugf format level information // Debugf format level information
func Debugf(format string, a ...interface{}) { func Debugf(format string, a ...any) {
getSugaredLogger().Debugf(format, a...) getSugaredLogger().Debugf(format, a...)
} }
// Infof format level information // Infof format level information
func Infof(format string, a ...interface{}) { func Infof(format string, a ...any) {
getSugaredLogger().Infof(format, a...) getSugaredLogger().Infof(format, a...)
} }
// Warnf format level information // Warnf format level information
func Warnf(format string, a ...interface{}) { func Warnf(format string, a ...any) {
getSugaredLogger().Warnf(format, a...) getSugaredLogger().Warnf(format, a...)
} }
// Errorf format level information // Errorf format level information
func Errorf(format string, a ...interface{}) { func Errorf(format string, a ...any) {
getSugaredLogger().Errorf(format, a...) getSugaredLogger().Errorf(format, a...)
} }
// Fatalf format level information // Fatalf format level information
func Fatalf(format string, a ...interface{}) { func Fatalf(format string, a ...any) {
getSugaredLogger().Fatalf(format, a...) getSugaredLogger().Fatalf(format, a...)
} }
......
...@@ -87,6 +87,6 @@ func Err(err error) Field { ...@@ -87,6 +87,6 @@ func Err(err error) Field {
} }
// Any type, if it is a composite type such as object, slice, map, etc., use Any // Any type, if it is a composite type such as object, slice, map, etc., use Any
func Any(key string, val interface{}) Field { func Any(key string, val any) Field {
return zap.Any(key, val) return zap.Any(key, val)
} }
...@@ -43,10 +43,10 @@ type Model2 struct { ...@@ -43,10 +43,10 @@ type Model2 struct {
} }
// KV map type // KV map type
type KV = map[string]interface{} type KV = map[string]any
// GetTableName get table name // GetTableName get table name
func GetTableName(object interface{}) string { func GetTableName(object any) string {
tableName := "" tableName := ""
typeof := reflect.TypeOf(object) typeof := reflect.TypeOf(object)
......
...@@ -51,7 +51,7 @@ func (l *gormLogger) LogMode(level logger.LogLevel) logger.Interface { ...@@ -51,7 +51,7 @@ func (l *gormLogger) LogMode(level logger.LogLevel) logger.Interface {
} }
// Info print info // Info print info
func (l *gormLogger) Info(ctx context.Context, msg string, data ...interface{}) { func (l *gormLogger) Info(ctx context.Context, msg string, data ...any) {
if l.logLevel >= logger.Info { if l.logLevel >= logger.Info {
msg = strings.ReplaceAll(msg, "%v", "") msg = strings.ReplaceAll(msg, "%v", "")
l.gLog.Info(msg, zap.Any("data", data), zap.String("line", FileWithLineNum()), requestIDField(ctx, l.requestIDKey)) l.gLog.Info(msg, zap.Any("data", data), zap.String("line", FileWithLineNum()), requestIDField(ctx, l.requestIDKey))
...@@ -59,7 +59,7 @@ func (l *gormLogger) Info(ctx context.Context, msg string, data ...interface{}) ...@@ -59,7 +59,7 @@ func (l *gormLogger) Info(ctx context.Context, msg string, data ...interface{})
} }
// Warn print warn messages // Warn print warn messages
func (l *gormLogger) Warn(ctx context.Context, msg string, data ...interface{}) { func (l *gormLogger) Warn(ctx context.Context, msg string, data ...any) {
if l.logLevel >= logger.Warn { if l.logLevel >= logger.Warn {
msg = strings.ReplaceAll(msg, "%v", "") msg = strings.ReplaceAll(msg, "%v", "")
l.gLog.Warn(msg, zap.Any("data", data), zap.String("line", FileWithLineNum()), requestIDField(ctx, l.requestIDKey)) l.gLog.Warn(msg, zap.Any("data", data), zap.String("line", FileWithLineNum()), requestIDField(ctx, l.requestIDKey))
...@@ -67,7 +67,7 @@ func (l *gormLogger) Warn(ctx context.Context, msg string, data ...interface{}) ...@@ -67,7 +67,7 @@ func (l *gormLogger) Warn(ctx context.Context, msg string, data ...interface{})
} }
// Error print error messages // Error print error messages
func (l *gormLogger) Error(ctx context.Context, msg string, data ...interface{}) { func (l *gormLogger) Error(ctx context.Context, msg string, data ...any) {
if l.logLevel >= logger.Error { if l.logLevel >= logger.Error {
msg = strings.ReplaceAll(msg, "%v", "") msg = strings.ReplaceAll(msg, "%v", "")
l.gLog.Warn(msg, zap.Any("data", data), zap.String("line", FileWithLineNum()), requestIDField(ctx, l.requestIDKey)) l.gLog.Warn(msg, zap.Any("data", data), zap.String("line", FileWithLineNum()), requestIDField(ctx, l.requestIDKey))
......
...@@ -130,7 +130,7 @@ type Params struct { ...@@ -130,7 +130,7 @@ type Params struct {
type Column struct { type Column struct {
Name string `json:"name" form:"name" validate:"required" example:"id"` // column name eg id Name string `json:"name" form:"name" validate:"required" example:"id"` // column name eg id
Exp string `json:"exp" form:"exp" validate:"required" example:"="` // expressions, default value is "=", support =, !=, >, >=, <, <=, like, in Exp string `json:"exp" form:"exp" validate:"required" example:"="` // expressions, default value is "=", support =, !=, >, >=, <, <=, like, in
Value interface{} `json:"value" form:"value" validate:"required"` // column value eg 102 Value any `json:"value" form:"value" validate:"required"` // column value eg 102
Logic string `json:"logic" form:"logic" example:"and"` // logical type, defaults to and when the value is null, with &(and), ||(or) Logic string `json:"logic" form:"logic" example:"and"` // logical type, defaults to and when the value is null, with &(and), ||(or)
} }
...@@ -159,7 +159,7 @@ func (c *Column) convert() error { ...@@ -159,7 +159,7 @@ func (c *Column) convert() error {
if !ok { if !ok {
return xerror.Newf("invalid value type '%s'", c.Value) return xerror.Newf("invalid value type '%s'", c.Value)
} }
iVal := []interface{}{} iVal := []any{}
ss := strings.Split(val, ",") ss := strings.Split(val, ",")
for _, s := range ss { for _, s := range ss {
iVal = append(iVal, s) iVal = append(iVal, s)
...@@ -193,9 +193,9 @@ func (p *Params) ConvertToPage() (order string, limit int, offset int) { //nolin ...@@ -193,9 +193,9 @@ func (p *Params) ConvertToPage() (order string, limit int, offset int) { //nolin
// ConvertToGormConditions conversion to gorm-compliant parameters based on the Columns parameter // ConvertToGormConditions conversion to gorm-compliant parameters based on the Columns parameter
// ignore the logical type of the last column, whether it is a one-column or multi-column query // ignore the logical type of the last column, whether it is a one-column or multi-column query
func (p *Params) ConvertToGormConditions() (string, []interface{}, error) { func (p *Params) ConvertToGormConditions() (string, []any, error) {
str := "" str := ""
args := []interface{}{} args := []any{}
l := len(p.Columns) l := len(p.Columns)
if l == 0 { if l == 0 {
return "", nil, nil return "", nil, nil
...@@ -242,7 +242,7 @@ func (p *Params) ConvertToGormConditions() (string, []interface{}, error) { ...@@ -242,7 +242,7 @@ func (p *Params) ConvertToGormConditions() (string, []interface{}, error) {
if isUseIN { if isUseIN {
str = field + " IN (?)" str = field + " IN (?)"
args = []interface{}{args} args = []any{args}
} }
return str, args, nil return str, args, nil
...@@ -281,7 +281,7 @@ func (c *Conditions) CheckValid() error { ...@@ -281,7 +281,7 @@ func (c *Conditions) CheckValid() error {
// ConvertToGorm conversion to gorm-compliant parameters based on the Columns parameter // ConvertToGorm conversion to gorm-compliant parameters based on the Columns parameter
// ignore the logical type of the last column, whether it is a one-column or multi-column query // ignore the logical type of the last column, whether it is a one-column or multi-column query
func (c *Conditions) ConvertToGorm() (string, []interface{}, error) { func (c *Conditions) ConvertToGorm() (string, []any, error) {
p := &Params{Columns: c.Columns} p := &Params{Columns: c.Columns}
return p.ConvertToGormConditions() return p.ConvertToGormConditions()
} }
...@@ -37,7 +37,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) { ...@@ -37,7 +37,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) {
name string name string
args args args args
want string want string
want1 []interface{} want1 []any
wantErr bool wantErr bool
}{ }{
// --------------------------- only 1 column query ------------------------------ // --------------------------- only 1 column query ------------------------------
...@@ -52,7 +52,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) { ...@@ -52,7 +52,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) {
}, },
}, },
want: "name = ?", want: "name = ?",
want1: []interface{}{"ZhangSan"}, want1: []any{"ZhangSan"},
wantErr: false, wantErr: false,
}, },
{ {
...@@ -68,7 +68,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) { ...@@ -68,7 +68,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) {
}, },
}, },
want: "name <> ?", want: "name <> ?",
want1: []interface{}{"ZhangSan"}, want1: []any{"ZhangSan"},
wantErr: false, wantErr: false,
}, },
{ {
...@@ -84,7 +84,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) { ...@@ -84,7 +84,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) {
}, },
}, },
want: "age > ?", want: "age > ?",
want1: []interface{}{20}, want1: []any{20},
wantErr: false, wantErr: false,
}, },
{ {
...@@ -100,7 +100,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) { ...@@ -100,7 +100,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) {
}, },
}, },
want: "age >= ?", want: "age >= ?",
want1: []interface{}{20}, want1: []any{20},
wantErr: false, wantErr: false,
}, },
{ {
...@@ -116,7 +116,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) { ...@@ -116,7 +116,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) {
}, },
}, },
want: "age < ?", want: "age < ?",
want1: []interface{}{20}, want1: []any{20},
wantErr: false, wantErr: false,
}, },
{ {
...@@ -132,7 +132,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) { ...@@ -132,7 +132,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) {
}, },
}, },
want: "age <= ?", want: "age <= ?",
want1: []interface{}{20}, want1: []any{20},
wantErr: false, wantErr: false,
}, },
{ {
...@@ -147,7 +147,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) { ...@@ -147,7 +147,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) {
}, },
}, },
want: "name LIKE ?", want: "name LIKE ?",
want1: []interface{}{"%Li%"}, want1: []any{"%Li%"},
wantErr: false, wantErr: false,
}, },
{ {
...@@ -162,7 +162,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) { ...@@ -162,7 +162,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) {
}, },
}, },
want: "name IN (?)", want: "name IN (?)",
want1: []interface{}{[]interface{}{"ab", "cd", "ef"}}, want1: []any{[]any{"ab", "cd", "ef"}},
wantErr: false, wantErr: false,
}, },
...@@ -182,7 +182,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) { ...@@ -182,7 +182,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) {
}, },
}, },
want: "name = ? AND gender = ?", want: "name = ? AND gender = ?",
want1: []interface{}{"ZhangSan", "male"}, want1: []any{"ZhangSan", "male"},
wantErr: false, wantErr: false,
}, },
{ {
...@@ -204,7 +204,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) { ...@@ -204,7 +204,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) {
}, },
}, },
want: "name <> ? AND name <> ?", want: "name <> ? AND name <> ?",
want1: []interface{}{"ZhangSan", "LiSi"}, want1: []any{"ZhangSan", "LiSi"},
wantErr: false, wantErr: false,
}, },
{ {
...@@ -224,7 +224,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) { ...@@ -224,7 +224,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) {
}, },
}, },
want: "gender = ? AND age > ?", want: "gender = ? AND age > ?",
want1: []interface{}{"male", 20}, want1: []any{"male", 20},
wantErr: false, wantErr: false,
}, },
{ {
...@@ -244,7 +244,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) { ...@@ -244,7 +244,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) {
}, },
}, },
want: "gender = ? AND age >= ?", want: "gender = ? AND age >= ?",
want1: []interface{}{"male", 20}, want1: []any{"male", 20},
wantErr: false, wantErr: false,
}, },
{ {
...@@ -264,7 +264,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) { ...@@ -264,7 +264,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) {
}, },
}, },
want: "gender = ? AND age < ?", want: "gender = ? AND age < ?",
want1: []interface{}{"female", 20}, want1: []any{"female", 20},
wantErr: false, wantErr: false,
}, },
{ {
...@@ -284,7 +284,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) { ...@@ -284,7 +284,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) {
}, },
}, },
want: "gender = ? AND age <= ?", want: "gender = ? AND age <= ?",
want1: []interface{}{"female", 20}, want1: []any{"female", 20},
wantErr: false, wantErr: false,
}, },
{ {
...@@ -306,7 +306,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) { ...@@ -306,7 +306,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) {
}, },
}, },
want: "age >= ? AND age <= ?", want: "age >= ? AND age <= ?",
want1: []interface{}{10, 20}, want1: []any{10, 20},
wantErr: false, wantErr: false,
}, },
{ {
...@@ -326,7 +326,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) { ...@@ -326,7 +326,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) {
}, },
}, },
want: "name = ? OR gender = ?", want: "name = ? OR gender = ?",
want1: []interface{}{"LiSi", "female"}, want1: []any{"LiSi", "female"},
wantErr: false, wantErr: false,
}, },
{ {
...@@ -348,7 +348,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) { ...@@ -348,7 +348,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) {
}, },
}, },
want: "name = ? OR gender <> ?", want: "name = ? OR gender <> ?",
want1: []interface{}{"LiSi", "male"}, want1: []any{"LiSi", "male"},
wantErr: false, wantErr: false,
}, },
{ {
...@@ -368,7 +368,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) { ...@@ -368,7 +368,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) {
}, },
}, },
want: "gender = ? AND name IN (?)", want: "gender = ? AND name IN (?)",
want1: []interface{}{"male", []interface{}{"LiSi", "ZhangSan", "WangWu"}}, want1: []any{"male", []any{"LiSi", "ZhangSan", "WangWu"}},
wantErr: false, wantErr: false,
}, },
...@@ -392,7 +392,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) { ...@@ -392,7 +392,7 @@ func TestParams_ConvertToGormConditions(t *testing.T) {
}, },
}, },
want: "name IN (?)", want: "name IN (?)",
want1: []interface{}{[]interface{}{"LiSi", "ZhangSan", "WangWu"}}, want1: []any{[]any{"LiSi", "ZhangSan", "WangWu"}},
wantErr: false, wantErr: false,
}, },
......
...@@ -52,7 +52,7 @@ func UnaryServerCircuitBreaker(opts ...CircuitBreakerOption) grpc.UnaryServerInt ...@@ -52,7 +52,7 @@ func UnaryServerCircuitBreaker(opts ...CircuitBreakerOption) grpc.UnaryServerInt
o := defaultCircuitBreakerOptions() o := defaultCircuitBreakerOptions()
o.apply(opts...) o.apply(opts...)
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) {
breaker := o.group.Get(info.FullMethod).(circuitbreaker.CircuitBreaker) breaker := o.group.Get(info.FullMethod).(circuitbreaker.CircuitBreaker)
if err := breaker.Allow(); err != nil { if err := breaker.Allow(); err != nil {
// NOTE: when client reject request locally, keep adding let the drop ratio higher. // NOTE: when client reject request locally, keep adding let the drop ratio higher.
......
...@@ -19,7 +19,7 @@ func SetTraceName(name string) { ...@@ -19,7 +19,7 @@ func SetTraceName(name string) {
} }
// NewSpan create a span, to end a span you must call span.End() // NewSpan create a span, to end a span you must call span.End()
func NewSpan(ctx context.Context, spanName string, tags map[string]interface{}) (context.Context, trace.Span) { func NewSpan(ctx context.Context, spanName string, tags map[string]any) (context.Context, trace.Span) {
var opts []trace.SpanStartOption var opts []trace.SpanStartOption
//nolint //nolint
......
...@@ -10,7 +10,7 @@ import ( ...@@ -10,7 +10,7 @@ import (
func TestNewSpan(t *testing.T) { func TestNewSpan(t *testing.T) {
SetTraceName("foo") SetTraceName("foo")
tags := map[string]interface{}{ tags := map[string]any{
"foo1": nil, "foo1": nil,
"foo2": true, "foo2": true,
"foo3": "bar", "foo3": "bar",
......
...@@ -33,7 +33,7 @@ func NewController() *Controller { ...@@ -33,7 +33,7 @@ func NewController() *Controller {
return &Controller{} return &Controller{}
} }
func (e *Controller) Bind(c *gin.Context, req interface{}) error { func (e *Controller) Bind(c *gin.Context, req any) error {
switch c.Request.Method { switch c.Request.Method {
case http.MethodGet: case http.MethodGet:
if err := c.ShouldBindQuery(req); err != nil { if err := c.ShouldBindQuery(req); err != nil {
......
...@@ -45,13 +45,13 @@ func NewCache[T IID](cacheType string, prefix string, d time.Duration) *OCache[T ...@@ -45,13 +45,13 @@ func NewCache[T IID](cacheType string, prefix string, d time.Duration) *OCache[T
} }
switch cType { switch cType {
case cache.CacheType_Redis: case cache.CacheType_Redis:
c := cache.NewRedisCache(database.GetRedisCli(), cachePrefix, JsonEncoding, func() interface{} { c := cache.NewRedisCache(database.GetRedisCli(), cachePrefix, JsonEncoding, func() any {
var t T var t T
return &t return &t
}) })
return &OCache[T]{Cache: c, KeyPrefix: prefix, ExpireTime: d} return &OCache[T]{Cache: c, KeyPrefix: prefix, ExpireTime: d}
case cache.CacheType_Memory: case cache.CacheType_Memory:
c := cache.NewMemoryCache(database.GetMemoryCache(), cachePrefix, JsonEncoding, func() interface{} { c := cache.NewMemoryCache(database.GetMemoryCache(), cachePrefix, JsonEncoding, func() any {
var t T var t T
return &t return &t
}) })
...@@ -90,7 +90,7 @@ func (x *OCache[T]) MultiSet(ctx context.Context, data []*T, duration time.Durat ...@@ -90,7 +90,7 @@ func (x *OCache[T]) MultiSet(ctx context.Context, data []*T, duration time.Durat
if x.Cache == nil { if x.Cache == nil {
return nil return nil
} }
valMap := make(map[string]interface{}) valMap := make(map[string]any)
for _, v := range data { for _, v := range data {
cacheKey := getCacheKey(x.KeyPrefix, (*v).GetID().Int64()) cacheKey := getCacheKey(x.KeyPrefix, (*v).GetID().Int64())
valMap[cacheKey] = v valMap[cacheKey] = v
......
...@@ -3,8 +3,8 @@ package odao ...@@ -3,8 +3,8 @@ package odao
import "strings" import "strings"
type Condition interface { type Condition interface {
SetWhere(k string, v []interface{}) SetWhere(k string, v []any)
SetOr(k string, v []interface{}) SetOr(k string, v []any)
SetOrder(k string) SetOrder(k string)
SetJoinOn(t, on string) Condition SetJoinOn(t, on string) Condition
} }
...@@ -15,9 +15,9 @@ type GormCondition struct { ...@@ -15,9 +15,9 @@ type GormCondition struct {
} }
type GormPublic struct { type GormPublic struct {
Where map[string][]interface{} Where map[string][]any
Order []string Order []string
Or map[string][]interface{} Or map[string][]any
} }
type GormJoin struct { type GormJoin struct {
...@@ -30,16 +30,16 @@ func (e *GormJoin) SetJoinOn(t, on string) Condition { ...@@ -30,16 +30,16 @@ func (e *GormJoin) SetJoinOn(t, on string) Condition {
return nil return nil
} }
func (e *GormPublic) SetWhere(k string, v []interface{}) { func (e *GormPublic) SetWhere(k string, v []any) {
if e.Where == nil { if e.Where == nil {
e.Where = make(map[string][]interface{}) e.Where = make(map[string][]any)
} }
e.Where[k] = v e.Where[k] = v
} }
func (e *GormPublic) SetOr(k string, v []interface{}) { func (e *GormPublic) SetOr(k string, v []any) {
if e.Or == nil { if e.Or == nil {
e.Or = make(map[string][]interface{}) e.Or = make(map[string][]any)
} }
e.Or[k] = v e.Or[k] = v
} }
......
...@@ -6,7 +6,7 @@ import ( ...@@ -6,7 +6,7 @@ import (
"strings" "strings"
) )
func GetGormTags(obj interface{}) []string { func GetGormTags(obj any) []string {
var tags []string var tags []string
val := reflect.ValueOf(obj) val := reflect.ValueOf(obj)
......
...@@ -209,7 +209,7 @@ func (x *ODao[T]) UpdateByIDTx(ctx context.Context, tx *gorm.DB, id xsf.ID, tb a ...@@ -209,7 +209,7 @@ func (x *ODao[T]) UpdateByIDTx(ctx context.Context, tx *gorm.DB, id xsf.ID, tb a
// updByIDTx // updByIDTx
// id 必传 // id 必传
// upd 可以是struct、map // upd 可以是struct、map
// Updates 方法支持 struct 和 map[string]interface{} 参数。当使用 struct 更新时,默认情况下GORM 只会更新非零值的字段 // Updates 方法支持 struct 和 map[string]any 参数。当使用 struct 更新时,默认情况下GORM 只会更新非零值的字段
func (x *ODao[T]) updByIDTx(ctx context.Context, tx *gorm.DB, id xsf.ID, upd any) error { func (x *ODao[T]) updByIDTx(ctx context.Context, tx *gorm.DB, id xsf.ID, upd any) error {
if id <= 0 { if id <= 0 {
return nil return nil
...@@ -229,7 +229,7 @@ func (x *ODao[T]) UpdateByIDsTx(ctx context.Context, tx *gorm.DB, ids []xsf.ID, ...@@ -229,7 +229,7 @@ func (x *ODao[T]) UpdateByIDsTx(ctx context.Context, tx *gorm.DB, ids []xsf.ID,
// updByIDsTx // updByIDsTx
// ids 必传 // ids 必传
// upd 可以是struct、map // upd 可以是struct、map
// Updates 方法支持 struct 和 map[string]interface{} 参数。当使用 struct 更新时,默认情况下GORM 只会更新非零值的字段 // Updates 方法支持 struct 和 map[string]any 参数。当使用 struct 更新时,默认情况下GORM 只会更新非零值的字段
// 1. 零值问题的解决方案 // 1. 零值问题的解决方案
// 如果需要用 Updates更新零值字段,可以使用: // 如果需要用 Updates更新零值字段,可以使用:
// // 方法1:使用Select指定字段 // // 方法1:使用Select指定字段
...@@ -241,7 +241,7 @@ func (x *ODao[T]) UpdateByIDsTx(ctx context.Context, tx *gorm.DB, ids []xsf.ID, ...@@ -241,7 +241,7 @@ func (x *ODao[T]) UpdateByIDsTx(ctx context.Context, tx *gorm.DB, ids []xsf.ID,
// //
// // 方法2:使用map和指针 // // 方法2:使用map和指针
// //
// db.Model(&user).Updates(map[string]interface{}{ // db.Model(&user).Updates(map[string]any{
// "name": "张三", // "name": "张三",
// "email": "", // 使用map可以更新零值 // "email": "", // 使用map可以更新零值
// }) // })
...@@ -465,7 +465,7 @@ func (x *ODao[T]) GetByID(ctx context.Context, id xsf.ID) (record *T, err error) ...@@ -465,7 +465,7 @@ func (x *ODao[T]) GetByID(ctx context.Context, id xsf.ID) (record *T, err error)
} }
if xerror.Is(err, ErrCacheNotFound) { if xerror.Is(err, ErrCacheNotFound) {
val, err, _ := x.Sf.Do(utils.Int64ToStr(id.Int64()), func() (interface{}, error) { val, err, _ := x.Sf.Do(utils.Int64ToStr(id.Int64()), func() (any, error) {
if err = x.DB().WithContext(ctx).Where("id = ?", id).First(&record).Error; err != nil { if err = x.DB().WithContext(ctx).Where("id = ?", id).First(&record).Error; err != nil {
if xerror.Is(err, ErrRecordNotFound) { if xerror.Is(err, ErrRecordNotFound) {
if err = x.Cache.SetPlaceholder(ctx, id); err != nil { if err = x.Cache.SetPlaceholder(ctx, id); err != nil {
......
...@@ -139,55 +139,55 @@ const ( ...@@ -139,55 +139,55 @@ const (
func pgSql(driver string, t *resolveSearchTag, condition Condition, qValue reflect.Value, i int, tname string) { func pgSql(driver string, t *resolveSearchTag, condition Condition, qValue reflect.Value, i int, tname string) {
if t.Type == "" { if t.Type == "" {
condition.SetWhere(fmt.Sprintf("%s.%s = ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()}) condition.SetWhere(fmt.Sprintf("%s.%s = ?", t.Table, t.Column), []any{qValue.Field(i).Interface()})
return return
} }
qtag := QueryTag(t.Type) qtag := QueryTag(t.Type)
switch qtag { switch qtag {
case EQ: case EQ:
condition.SetWhere(fmt.Sprintf("%s.%s = ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()}) condition.SetWhere(fmt.Sprintf("%s.%s = ?", t.Table, t.Column), []any{qValue.Field(i).Interface()})
return return
case ILIKE: case ILIKE:
condition.SetWhere(fmt.Sprintf("%s.%s ilike ?", t.Table, t.Column), []interface{}{"%" + qValue.Field(i).String() + "%"}) condition.SetWhere(fmt.Sprintf("%s.%s ilike ?", t.Table, t.Column), []any{"%" + qValue.Field(i).String() + "%"})
return return
case LIKE: case LIKE:
condition.SetWhere(fmt.Sprintf("%s.%s like ?", t.Table, t.Column), []interface{}{"%" + qValue.Field(i).String() + "%"}) condition.SetWhere(fmt.Sprintf("%s.%s like ?", t.Table, t.Column), []any{"%" + qValue.Field(i).String() + "%"})
return return
case GT: case GT:
condition.SetWhere(fmt.Sprintf("%s.%s > ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()}) condition.SetWhere(fmt.Sprintf("%s.%s > ?", t.Table, t.Column), []any{qValue.Field(i).Interface()})
return return
case GTE: case GTE:
condition.SetWhere(fmt.Sprintf("%s.%s >= ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()}) condition.SetWhere(fmt.Sprintf("%s.%s >= ?", t.Table, t.Column), []any{qValue.Field(i).Interface()})
return return
case LT: case LT:
condition.SetWhere(fmt.Sprintf("%s.%s < ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()}) condition.SetWhere(fmt.Sprintf("%s.%s < ?", t.Table, t.Column), []any{qValue.Field(i).Interface()})
return return
case LTE: case LTE:
condition.SetWhere(fmt.Sprintf("%s.%s <= ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()}) condition.SetWhere(fmt.Sprintf("%s.%s <= ?", t.Table, t.Column), []any{qValue.Field(i).Interface()})
return return
case ILEFT: case ILEFT:
condition.SetWhere(fmt.Sprintf("%s.%s ilike ?", t.Table, t.Column), []interface{}{qValue.Field(i).String() + "%"}) condition.SetWhere(fmt.Sprintf("%s.%s ilike ?", t.Table, t.Column), []any{qValue.Field(i).String() + "%"})
return return
case LEFT: case LEFT:
condition.SetWhere(fmt.Sprintf("%s.%s like ?", t.Table, t.Column), []interface{}{qValue.Field(i).String() + "%"}) condition.SetWhere(fmt.Sprintf("%s.%s like ?", t.Table, t.Column), []any{qValue.Field(i).String() + "%"})
return return
case IRIGHT: case IRIGHT:
condition.SetWhere(fmt.Sprintf("%s.%s ilike ?", t.Table, t.Column), []interface{}{"%" + qValue.Field(i).String()}) condition.SetWhere(fmt.Sprintf("%s.%s ilike ?", t.Table, t.Column), []any{"%" + qValue.Field(i).String()})
return return
case RIGHT: case RIGHT:
condition.SetWhere(fmt.Sprintf("%s.%s like ?", t.Table, t.Column), []interface{}{"%" + qValue.Field(i).String()}) condition.SetWhere(fmt.Sprintf("%s.%s like ?", t.Table, t.Column), []any{"%" + qValue.Field(i).String()})
return return
case IN: case IN:
condition.SetWhere(fmt.Sprintf("%s.%s in (?)", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()}) condition.SetWhere(fmt.Sprintf("%s.%s in (?)", t.Table, t.Column), []any{qValue.Field(i).Interface()})
return return
case ISNULL: case ISNULL:
if !(qValue.Field(i).IsZero() && qValue.Field(i).IsNil()) { if !(qValue.Field(i).IsZero() && qValue.Field(i).IsNil()) {
condition.SetWhere(fmt.Sprintf("%s.%s is null", t.Table, t.Column), make([]interface{}, 0)) condition.SetWhere(fmt.Sprintf("%s.%s is null", t.Table, t.Column), make([]any, 0))
} }
return return
case ISNOTNULL: case ISNOTNULL:
if !(qValue.Field(i).IsZero() && qValue.Field(i).IsNil()) { if !(qValue.Field(i).IsZero() && qValue.Field(i).IsNil()) {
condition.SetWhere(fmt.Sprintf("%s.%s is not null", t.Table, t.Column), make([]interface{}, 0)) condition.SetWhere(fmt.Sprintf("%s.%s is not null", t.Table, t.Column), make([]any, 0))
} }
return return
case ORDER: case ORDER:
...@@ -208,52 +208,52 @@ func pgSql(driver string, t *resolveSearchTag, condition Condition, qValue refle ...@@ -208,52 +208,52 @@ func pgSql(driver string, t *resolveSearchTag, condition Condition, qValue refle
ResolveSearchQuery(driver, qValue.Field(i).Interface(), join, tname) ResolveSearchQuery(driver, qValue.Field(i).Interface(), join, tname)
return return
default: default:
condition.SetWhere(fmt.Sprintf("%s.%s = ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()}) condition.SetWhere(fmt.Sprintf("%s.%s = ?", t.Table, t.Column), []any{qValue.Field(i).Interface()})
} }
} }
func otherSql(driver string, t *resolveSearchTag, condition Condition, qValue reflect.Value, i int, tname string) { func otherSql(driver string, t *resolveSearchTag, condition Condition, qValue reflect.Value, i int, tname string) {
if t.Type == "" { if t.Type == "" {
condition.SetWhere(fmt.Sprintf("`%s`.`%s` = ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()}) condition.SetWhere(fmt.Sprintf("`%s`.`%s` = ?", t.Table, t.Column), []any{qValue.Field(i).Interface()})
return return
} }
qtag := QueryTag(t.Type) qtag := QueryTag(t.Type)
switch qtag { switch qtag {
case EQ: case EQ:
condition.SetWhere(fmt.Sprintf("`%s`.`%s` = ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()}) condition.SetWhere(fmt.Sprintf("`%s`.`%s` = ?", t.Table, t.Column), []any{qValue.Field(i).Interface()})
return return
case GT: case GT:
condition.SetWhere(fmt.Sprintf("`%s`.`%s` > ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()}) condition.SetWhere(fmt.Sprintf("`%s`.`%s` > ?", t.Table, t.Column), []any{qValue.Field(i).Interface()})
return return
case GTE: case GTE:
condition.SetWhere(fmt.Sprintf("`%s`.`%s` >= ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()}) condition.SetWhere(fmt.Sprintf("`%s`.`%s` >= ?", t.Table, t.Column), []any{qValue.Field(i).Interface()})
return return
case LT: case LT:
condition.SetWhere(fmt.Sprintf("`%s`.`%s` < ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()}) condition.SetWhere(fmt.Sprintf("`%s`.`%s` < ?", t.Table, t.Column), []any{qValue.Field(i).Interface()})
return return
case LTE: case LTE:
condition.SetWhere(fmt.Sprintf("`%s`.`%s` <= ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()}) condition.SetWhere(fmt.Sprintf("`%s`.`%s` <= ?", t.Table, t.Column), []any{qValue.Field(i).Interface()})
return return
case LEFT: case LEFT:
condition.SetWhere(fmt.Sprintf("`%s`.`%s` like ?", t.Table, t.Column), []interface{}{qValue.Field(i).String() + "%"}) condition.SetWhere(fmt.Sprintf("`%s`.`%s` like ?", t.Table, t.Column), []any{qValue.Field(i).String() + "%"})
return return
case LIKE: case LIKE:
condition.SetWhere(fmt.Sprintf("`%s`.`%s` like ?", t.Table, t.Column), []interface{}{"%" + qValue.Field(i).String() + "%"}) condition.SetWhere(fmt.Sprintf("`%s`.`%s` like ?", t.Table, t.Column), []any{"%" + qValue.Field(i).String() + "%"})
return return
case RIGHT: case RIGHT:
condition.SetWhere(fmt.Sprintf("`%s`.`%s` like ?", t.Table, t.Column), []interface{}{"%" + qValue.Field(i).String()}) condition.SetWhere(fmt.Sprintf("`%s`.`%s` like ?", t.Table, t.Column), []any{"%" + qValue.Field(i).String()})
return return
case IN: case IN:
condition.SetWhere(fmt.Sprintf("`%s`.`%s` in (?)", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()}) condition.SetWhere(fmt.Sprintf("`%s`.`%s` in (?)", t.Table, t.Column), []any{qValue.Field(i).Interface()})
return return
case ISNULL: case ISNULL:
if !(qValue.Field(i).IsZero() && qValue.Field(i).IsNil()) { if !(qValue.Field(i).IsZero() && qValue.Field(i).IsNil()) {
condition.SetWhere(fmt.Sprintf("`%s`.`%s` is null", t.Table, t.Column), make([]interface{}, 0)) condition.SetWhere(fmt.Sprintf("`%s`.`%s` is null", t.Table, t.Column), make([]any, 0))
} }
return return
case ISNOTNULL: case ISNOTNULL:
if !(qValue.Field(i).IsZero() && qValue.Field(i).IsNil()) { if !(qValue.Field(i).IsZero() && qValue.Field(i).IsNil()) {
condition.SetWhere(fmt.Sprintf("%s.%s is not null", t.Table, t.Column), make([]interface{}, 0)) condition.SetWhere(fmt.Sprintf("%s.%s is not null", t.Table, t.Column), make([]any, 0))
} }
return return
case ORDER: case ORDER:
...@@ -294,7 +294,7 @@ func otherSql(driver string, t *resolveSearchTag, condition Condition, qValue re ...@@ -294,7 +294,7 @@ func otherSql(driver string, t *resolveSearchTag, condition Condition, qValue re
ResolveSearchQuery(driver, qValue.Field(i).Interface(), join, tname) ResolveSearchQuery(driver, qValue.Field(i).Interface(), join, tname)
return return
default: default:
condition.SetWhere(fmt.Sprintf("`%s`.`%s` = ?", t.Table, t.Column), []interface{}{qValue.Field(i).Interface()}) condition.SetWhere(fmt.Sprintf("`%s`.`%s` = ?", t.Table, t.Column), []any{qValue.Field(i).Interface()})
} }
} }
......
...@@ -117,11 +117,11 @@ func xxlJob(r *gin.Engine) { ...@@ -117,11 +117,11 @@ func xxlJob(r *gin.Engine) {
type log struct{} type log struct{}
func (l *log) Info(format string, a ...interface{}) { func (l *log) Info(format string, a ...any) {
logger.Infof("[xxl-executor]%s", fmt.Sprintf(format, a...)) logger.Infof("[xxl-executor]%s", fmt.Sprintf(format, a...))
} }
func (l *log) Error(format string, a ...interface{}) { func (l *log) Error(format string, a ...any) {
logger.Errorf("[xxl-executor]%s", fmt.Sprintf(format, a...)) logger.Errorf("[xxl-executor]%s", fmt.Sprintf(format, a...))
} }
......
...@@ -84,7 +84,7 @@ func (id *IDCard) UnmarshalCSV(csv string) error { ...@@ -84,7 +84,7 @@ func (id *IDCard) UnmarshalCSV(csv string) error {
} }
// Scan 数据库读取接口 // Scan 数据库读取接口
func (id *IDCard) Scan(value interface{}) error { func (id *IDCard) Scan(value any) error {
if value == nil { if value == nil {
*id = "" *id = ""
return nil return nil
......
...@@ -98,7 +98,7 @@ func MaskPhone(phone string) string { ...@@ -98,7 +98,7 @@ func MaskPhone(phone string) string {
} }
// Scan 数据库读取接口 // Scan 数据库读取接口
func (id *Mobile) Scan(value interface{}) error { func (id *Mobile) Scan(value any) error {
if value == nil { if value == nil {
*id = "" *id = ""
return nil return nil
......
...@@ -81,7 +81,7 @@ func (d *Password) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) error ...@@ -81,7 +81,7 @@ func (d *Password) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) error
} }
// Scan 数据库读取接口 // Scan 数据库读取接口
func (id *Password) Scan(value interface{}) error { func (id *Password) Scan(value any) error {
if value == nil { if value == nil {
*id = "" *id = ""
return nil return nil
......
...@@ -363,7 +363,7 @@ func GetGinRsp(c *gin.Context) []byte { ...@@ -363,7 +363,7 @@ func GetGinRsp(c *gin.Context) []byte {
return nil return nil
} }
func SetVal(ctx context.Context, key string, val interface{}) context.Context { func SetVal(ctx context.Context, key string, val any) context.Context {
if ginCtx, err := GetGinCtx(ctx); err == nil && ginCtx != nil { if ginCtx, err := GetGinCtx(ctx); err == nil && ginCtx != nil {
ginCtx.Set(key, val) ginCtx.Set(key, val)
} }
......
...@@ -50,7 +50,7 @@ func (x *Excel) WriteSheet(sheetName string, data any, dataType any) *Excel { ...@@ -50,7 +50,7 @@ func (x *Excel) WriteSheet(sheetName string, data any, dataType any) *Excel {
} }
t := reflect.TypeOf(dataType) t := reflect.TypeOf(dataType)
headers := make([]interface{}, 0, t.NumField()) headers := make([]any, 0, t.NumField())
for j := 0; j < t.NumField(); j++ { for j := 0; j < t.NumField(); j++ {
name := t.Field(j).Tag.Get("xls") name := t.Field(j).Tag.Get("xls")
if name == "" { if name == "" {
...@@ -65,7 +65,7 @@ func (x *Excel) WriteSheet(sheetName string, data any, dataType any) *Excel { ...@@ -65,7 +65,7 @@ func (x *Excel) WriteSheet(sheetName string, data any, dataType any) *Excel {
} }
for i := 0; i < v.Len(); i++ { for i := 0; i < v.Len(); i++ {
item := make([]interface{}, 0, t.NumField()) item := make([]any, 0, t.NumField())
for j := 0; j < t.NumField(); j++ { for j := 0; j < t.NumField(); j++ {
item = append(item, v.Index(i).Field(j).Interface()) item = append(item, v.Index(i).Field(j).Interface())
} }
......
...@@ -15,7 +15,7 @@ func Unmarshal(data []byte, v any) error { ...@@ -15,7 +15,7 @@ func Unmarshal(data []byte, v any) error {
return nil return nil
} }
func MarshalEscapeHTML(data interface{}) ([]byte, error) { func MarshalEscapeHTML(data any) ([]byte, error) {
bf := bytes.NewBuffer([]byte{}) bf := bytes.NewBuffer([]byte{})
jsonEncoder := json.NewEncoder(bf) jsonEncoder := json.NewEncoder(bf)
jsonEncoder.SetEscapeHTML(false) jsonEncoder.SetEscapeHTML(false)
...@@ -25,7 +25,7 @@ func MarshalEscapeHTML(data interface{}) ([]byte, error) { ...@@ -25,7 +25,7 @@ func MarshalEscapeHTML(data interface{}) ([]byte, error) {
return bf.Bytes(), nil return bf.Bytes(), nil
} }
func MarshalEscapeHTMLSilent(data interface{}) []byte { func MarshalEscapeHTMLSilent(data any) []byte {
d, _ := MarshalEscapeHTML(data) d, _ := MarshalEscapeHTML(data)
return d return d
} }
...@@ -59,11 +59,11 @@ func ToJSONBytes(v any) []byte { ...@@ -59,11 +59,11 @@ func ToJSONBytes(v any) []byte {
return bytes return bytes
} }
func ToJSONString(v interface{}) string { func ToJSONString(v any) string {
return string(ToJSONBytes(v)) return string(ToJSONBytes(v))
} }
func ToJSONStringPtr(d interface{}) *string { func ToJSONStringPtr(d any) *string {
v := ToJSONString(d) v := ToJSONString(d)
return &v return &v
} }
...@@ -9,7 +9,7 @@ import ( ...@@ -9,7 +9,7 @@ import (
"github.com/spf13/cast" "github.com/spf13/cast"
) )
func MapToStruct(m map[string]interface{}, s interface{}) error { func MapToStruct(m map[string]any, s any) error {
data, err := json.Marshal(m) data, err := json.Marshal(m)
if err != nil { if err != nil {
return fmt.Errorf("marshal error: %v", err) return fmt.Errorf("marshal error: %v", err)
...@@ -21,7 +21,7 @@ func MapToStruct(m map[string]interface{}, s interface{}) error { ...@@ -21,7 +21,7 @@ func MapToStruct(m map[string]interface{}, s interface{}) error {
return nil return nil
} }
func MapToStructByReflect(m map[string]interface{}, s interface{}) error { func MapToStructByReflect(m map[string]any, s any) error {
rv := reflect.ValueOf(s) rv := reflect.ValueOf(s)
if rv.Kind() != reflect.Ptr || rv.IsNil() { if rv.Kind() != reflect.Ptr || rv.IsNil() {
return fmt.Errorf("target must be non-nil pointer") return fmt.Errorf("target must be non-nil pointer")
...@@ -45,12 +45,12 @@ func MapToStructByReflect(m map[string]interface{}, s interface{}) error { ...@@ -45,12 +45,12 @@ func MapToStructByReflect(m map[string]interface{}, s interface{}) error {
return nil return nil
} }
func StructToMapWithJsonTag(obj interface{}) map[string]interface{} { func StructToMapWithJsonTag(obj any) map[string]any {
v := reflect.ValueOf(obj) v := reflect.ValueOf(obj)
if v.Kind() == reflect.Ptr { if v.Kind() == reflect.Ptr {
v = v.Elem() v = v.Elem()
} }
result := make(map[string]interface{}) result := make(map[string]any)
t := v.Type() t := v.Type()
for i := 0; i < v.NumField(); i++ { for i := 0; i < v.NumField(); i++ {
field := t.Field(i) field := t.Field(i)
......
...@@ -10,7 +10,7 @@ func URLValuePairsToMap(query string) (map[string]any, error) { ...@@ -10,7 +10,7 @@ func URLValuePairsToMap(query string) (map[string]any, error) {
return nil, err return nil, err
} }
data := make(map[string]interface{}) data := make(map[string]any)
for key, val := range values { for key, val := range values {
if len(val) == 1 { if len(val) == 1 {
data[key] = val[0] data[key] = val[0]
......
...@@ -19,7 +19,7 @@ const ( ...@@ -19,7 +19,7 @@ const (
) )
// Scan 改进:增强健壮性,统一解析路径,优化错误信息 // Scan 改进:增强健壮性,统一解析路径,优化错误信息
func (d *Date) Scan(value interface{}) error { func (d *Date) Scan(value any) error {
if value == nil { if value == nil {
*d = Date(time.Time{}) // 明确处理数据库NULL值 *d = Date(time.Time{}) // 明确处理数据库NULL值
return nil return nil
...@@ -92,7 +92,7 @@ func (d *Date) UnmarshalJSON(data []byte) error { ...@@ -92,7 +92,7 @@ func (d *Date) UnmarshalJSON(data []byte) error {
} }
// MarshalYAML 改进:符合yaml.v3接口标准 // MarshalYAML 改进:符合yaml.v3接口标准
func (d Date) MarshalYAML() (interface{}, error) { func (d Date) MarshalYAML() (any, error) {
t := time.Time(d) t := time.Time(d)
if t.IsZero() { if t.IsZero() {
return nil, nil return nil, nil
......
...@@ -12,7 +12,7 @@ import ( ...@@ -12,7 +12,7 @@ import (
func TestDate_Scan(t *testing.T) { func TestDate_Scan(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
input interface{} input any
want string want string
wantErr bool wantErr bool
}{ }{
...@@ -76,7 +76,7 @@ func TestDate_Value(t *testing.T) { ...@@ -76,7 +76,7 @@ func TestDate_Value(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
input Date input Date
want interface{} want any
wantErr bool wantErr bool
}{ }{
{ {
......
...@@ -71,7 +71,7 @@ func (dt *DateTime) UnmarshalJSON(data []byte) error { ...@@ -71,7 +71,7 @@ func (dt *DateTime) UnmarshalJSON(data []byte) error {
} }
// MarshalYAML 自定义YAML序列化 // MarshalYAML 自定义YAML序列化
func (dt DateTime) MarshalYAML() (interface{}, error) { func (dt DateTime) MarshalYAML() (any, error) {
t := time.Time(dt) t := time.Time(dt)
if t.IsZero() { if t.IsZero() {
return nil, nil return nil, nil
...@@ -166,7 +166,7 @@ func (dt DateTime) Value() (driver.Value, error) { ...@@ -166,7 +166,7 @@ func (dt DateTime) Value() (driver.Value, error) {
} }
// Scan 实现 sql.Scanner 接口,用于从数据库读取 // Scan 实现 sql.Scanner 接口,用于从数据库读取
func (dt *DateTime) Scan(value interface{}) error { func (dt *DateTime) Scan(value any) error {
if value == nil { if value == nil {
*dt = DateTime(time.Time{}) *dt = DateTime(time.Time{})
return nil return nil
......
...@@ -12,7 +12,7 @@ import ( ...@@ -12,7 +12,7 @@ import (
func TestDateTime_Scan(t *testing.T) { func TestDateTime_Scan(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
input interface{} input any
want string want string
wantErr bool wantErr bool
}{ }{
...@@ -82,7 +82,7 @@ func TestDateTime_Value(t *testing.T) { ...@@ -82,7 +82,7 @@ func TestDateTime_Value(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
input DateTime input DateTime
want interface{} want any
wantErr bool wantErr bool
}{ }{
{ {
......
...@@ -15,7 +15,7 @@ type Time time.Time ...@@ -15,7 +15,7 @@ type Time time.Time
const timeFormat = "15:04:05" const timeFormat = "15:04:05"
// Scan 改进:增强空值处理和错误信息 // Scan 改进:增强空值处理和错误信息
func (t *Time) Scan(value interface{}) error { func (t *Time) Scan(value any) error {
if value == nil { if value == nil {
*t = Time(time.Time{}) // 明确处理数据库NULL值 *t = Time(time.Time{}) // 明确处理数据库NULL值
return nil return nil
...@@ -83,7 +83,7 @@ func (t *Time) UnmarshalJSON(data []byte) error { ...@@ -83,7 +83,7 @@ func (t *Time) UnmarshalJSON(data []byte) error {
} }
// MarshalYAML 改进:符合yaml.v3接口 // MarshalYAML 改进:符合yaml.v3接口
func (t Time) MarshalYAML() (interface{}, error) { func (t Time) MarshalYAML() (any, error) {
if t.IsZero() { if t.IsZero() {
return nil, nil return nil, nil
} }
......
...@@ -12,7 +12,7 @@ import ( ...@@ -12,7 +12,7 @@ import (
func TestTime_Scan(t *testing.T) { func TestTime_Scan(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
input interface{} input any
want string want string
wantErr bool wantErr bool
}{ }{
...@@ -82,7 +82,7 @@ func TestTime_Value(t *testing.T) { ...@@ -82,7 +82,7 @@ func TestTime_Value(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
input Time input Time
want interface{} want any
wantErr bool wantErr bool
}{ }{
{ {
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论