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

update

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