From 61e8d6f4e18d01c81e7cb7281454cbef6dc74521 Mon Sep 17 00:00:00 2001 From: zakir <80246097+zakir-code@users.noreply.github.com> Date: Wed, 20 Nov 2024 14:32:34 +0800 Subject: [PATCH 1/2] chore: format code --- .golangci.yml | 77 ++++++++++++++++++++++++++----------- dao/base.go | 4 +- dao/base_test.go | 4 +- db/config.go | 4 +- db/config_test.go | 2 +- db/db.go | 52 ++++++++++++------------- db/db_test.go | 63 +++++++++++++++--------------- db/driver_test.go | 2 +- db/mysql.go | 6 +-- db/sqlite.go | 12 +++--- db/sqlite_test.go | 12 +++--- eth/config_test.go | 4 +- eth/keys.go | 2 +- eth/rpc.go | 2 +- log/log.go | 30 +++++++-------- log/logger.go | 16 ++++---- log/noplog.go | 22 +++++------ log/zaplog.go | 22 +++++------ log/zerolog.go | 30 +++++++-------- log/zerolog_test.go | 9 +++-- migration/config.go | 4 +- migration/migration.go | 4 +- modules/big_int.go | 4 +- pprof/config.go | 2 +- pprof/server.go | 8 ++-- pprof/server_test.go | 11 +++--- rand/random.go | 11 +++--- rand/random_test.go | 8 ++-- scheduler/scheduler.go | 2 +- scheduler/scheduler_test.go | 4 +- server/interface.go | 2 +- telemetry/config.go | 2 +- telemetry/metrics.go | 2 +- telemetry/server.go | 4 +- telemetry/server_test.go | 4 +- tool/file.go | 2 +- tool/json.go | 16 ++++---- tool/mapstructure.go | 6 +-- 38 files changed, 250 insertions(+), 221 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 1998be8..0850cf0 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -2,49 +2,48 @@ run: timeout: 5m tests: true go: '1.22' + allow-parallel-runners: true linters: disable-all: true enable: - - dogsled - - errcheck + - gofumpt + - unconvert + - unparam + - stylecheck + - gocyclo - errorlint - - copyloopvar - - gci - - goconst + - prealloc - gocritic - - gofumpt + - gci + - dogsled - gosec + - errcheck + - goconst - gosimple - govet - ineffassign - misspell - nakedret - nolintlint - - revive - staticcheck - - stylecheck - - thelper + - revive - typecheck - - unconvert - unused + - thelper + - copyloopvar + - wastedassign + - testifylint linters-settings: + staticcheck: + checks: [ "all", "-SA1019" ] stylecheck: checks: [ "all", "-ST1003" ] gocyclo: min-complexity: 15 - govet: - disable: - - loopclosure - gosec: - excludes: [ "G108", "G115" ] - exclude-generated: true - confidence: medium - revive: - rules: - - name: redefines-builtin-id - disabled: true + gocritic: + disabled-checks: [ "assignOp", "ifElseChain", "appendAssign" ] misspell: locale: US gofumpt: @@ -57,8 +56,8 @@ linters-settings: require-specific: false gosimple: checks: [ "all" ] - staticcheck: - checks: [ "all", "-SA1019" ] + gosec: + excludes: [ "G115" ] gci: custom-order: true sections: @@ -68,3 +67,35 @@ linters-settings: errcheck: check-type-assertions: false check-blank: false + unused: + field-writes-are-uses: false + exported-fields-are-used: false + local-variables-are-used: false + revive: + # https://golangci-lint.run/usage/linters/#revive + enable-all-rules: true + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md + rules: + - name: line-length-limit + disabled: true + - name: add-constant + disabled: true + - name: cognitive-complexity + disabled: false + exclude: + - "**_test.go" + - name: function-length + disabled: true + - name: var-naming + arguments: + - [ "ID", "IDS", "URL", "JSON", "RPC" ] # AllowList + - [ "" ] # DenyList + - - upperCaseConst: true + - name: unhandled-error + arguments: + - "fmt.Print" + - "fmt.Println" + - name: import-shadowing + disabled: true + - name: cognitive-complexity + disabled: true \ No newline at end of file diff --git a/dao/base.go b/dao/base.go index e9f1a1b..df8af8b 100644 --- a/dao/base.go +++ b/dao/base.go @@ -80,7 +80,7 @@ func (d *BaseDao) BeginTx(ctx context.Context) context.Context { return context.WithValue(ctx, keyTx, d.db.Begin()) } -func (d *BaseDao) CommitTx(ctx context.Context) error { +func (*BaseDao) CommitTx(ctx context.Context) error { tx, canOperator := hasOperatorTx(ctx) if !canOperator { return nil @@ -88,7 +88,7 @@ func (d *BaseDao) CommitTx(ctx context.Context) error { return tx.Commit() } -func (d *BaseDao) RollbackTx(ctx context.Context) error { +func (*BaseDao) RollbackTx(ctx context.Context) error { tx, canOperator := hasOperatorTx(ctx) if !canOperator { return nil diff --git a/dao/base_test.go b/dao/base_test.go index a43b25f..694b7ee 100644 --- a/dao/base_test.go +++ b/dao/base_test.go @@ -20,7 +20,7 @@ type TestModel struct { Number uint64 `gorm:"column:number; type:bigint(20);not null;comment:block number"` } -func (v *TestModel) TableName() string { +func (*TestModel) TableName() string { return "test_model" } @@ -99,7 +99,7 @@ func (s *DaoTestSuite) TestNoTransaction() { data := NewTestModel("test", 100) var txErr error defer func() { - s.Require().NotNil(txErr) + s.Require().Error(txErr) s.Require().EqualError(txErr, "db create error: UNIQUE constraint failed: test_model.name") }() if txErr = s.baseDao.Insert(data); txErr != nil { diff --git a/db/config.go b/db/config.go index ef2c219..2f5e9ca 100644 --- a/db/config.go +++ b/db/config.go @@ -55,7 +55,7 @@ func (c Config) String() string { return string(out) } -func (c Config) MarshalYAML() (interface{}, error) { +func (c Config) MarshalYAML() (any, error) { type marshalConfig Config temp := marshalConfig(c) temp.Source = SourceDesensitization(temp.Source) @@ -68,7 +68,7 @@ func (c Config) MarshalJSON() ([]byte, error) { return json.Marshal(temp) } -func (c Config) Check() error { +func (c Config) Check() error { //nolint:revive // cyclomatic if c.Driver == "" { return errors.New("check: driver is empty") } diff --git a/db/config_test.go b/db/config_test.go index eb4dba0..0d68ad7 100644 --- a/db/config_test.go +++ b/db/config_test.go @@ -29,7 +29,7 @@ refresh_metric_interval: 15s func (suite *ConfigTestSuite) TestCheck() { config := db.NewDefConfig() - suite.NoError(config.Check()) + suite.Require().NoError(config.Check()) config.Driver = "" suite.EqualError(config.Check(), "check: driver is empty") diff --git a/db/db.go b/db/db.go index 509cbe4..91bf0e2 100644 --- a/db/db.go +++ b/db/db.go @@ -18,27 +18,27 @@ import ( ) type DB interface { - Model(value interface{}) DB - Where(query interface{}, args ...interface{}) DB + Model(value any) DB + Where(query any, args ...any) DB Limit(limit int) DB Scopes(funcs ...func(DB) DB) DB Offset(offset int) DB - Order(value interface{}) DB + Order(value any) DB Count(count *int64) DB Group(query string) DB RowsAffected(number int64) DB - Select(query interface{}, args ...interface{}) DB - Distinct(args ...interface{}) DB - Find(dest interface{}, conds ...interface{}) (err error) - First(dest interface{}, conds ...interface{}) (found bool, err error) - MustFirst(dest interface{}, conds ...interface{}) (err error) + Select(query any, args ...any) DB + Distinct(args ...any) DB + Find(dest any, conds ...any) (err error) + First(dest any, conds ...any) (found bool, err error) + MustFirst(dest any, conds ...any) (err error) - Exec(sql string, values ...interface{}) error + Exec(sql string, values ...any) error - Create(value interface{}) error - Update(column string, value interface{}) error - Updates(values interface{}) error + Create(value any) error + Update(column string, value any) error + Updates(values any) error Transaction(fn func(tx DB) error) error @@ -46,7 +46,7 @@ type DB interface { Commit() error Rollback() error - AutoMigrate(dst ...interface{}) error + AutoMigrate(dst ...any) error GetSource() string GetDriver() Driver @@ -193,11 +193,11 @@ func (g *gDB) WithContext(ctx context.Context) DB { return g.copy(g.db.WithContext(ctx)) } -func (g *gDB) Model(value interface{}) DB { +func (g *gDB) Model(value any) DB { return g.copy(g.db.Model(value)) } -func (g *gDB) Where(query interface{}, args ...interface{}) DB { +func (g *gDB) Where(query any, args ...any) DB { return g.copy(g.db.Where(query, args...)) } @@ -218,7 +218,7 @@ func (g *gDB) Offset(offset int) DB { return g.copy(g.db.Offset(offset)) } -func (g *gDB) Order(value interface{}) DB { +func (g *gDB) Order(value any) DB { return g.copy(g.db.Order(value)) } @@ -230,15 +230,15 @@ func (g *gDB) Group(query string) DB { return g.copy(g.db.Group(query)) } -func (g *gDB) Distinct(args ...interface{}) DB { +func (g *gDB) Distinct(args ...any) DB { return g.copy(g.db.Distinct(args...)) } -func (g *gDB) Select(query interface{}, args ...interface{}) DB { +func (g *gDB) Select(query any, args ...any) DB { return g.copy(g.db.Select(query, args...)) } -func (g *gDB) Find(dest interface{}, conds ...interface{}) error { +func (g *gDB) Find(dest any, conds ...any) error { err := g.db.Find(dest, conds...).Error if err != nil { g.logger.Error("db find error", "dest", dest, "conds", conds, "error", err) @@ -247,7 +247,7 @@ func (g *gDB) Find(dest interface{}, conds ...interface{}) error { return nil } -func (g *gDB) First(dest interface{}, conds ...interface{}) (bool, error) { +func (g *gDB) First(dest any, conds ...any) (bool, error) { err := g.db.First(dest, conds...).Error if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { @@ -259,7 +259,7 @@ func (g *gDB) First(dest interface{}, conds ...interface{}) (bool, error) { return true, nil } -func (g *gDB) MustFirst(dest interface{}, conds ...interface{}) error { +func (g *gDB) MustFirst(dest any, conds ...any) error { return errors.Wrap(g.db.First(dest, conds...).Error, "db must first error") } @@ -281,7 +281,7 @@ func (g *gDB) Rollback() error { return g.db.Rollback().Error } -func (g *gDB) Create(value interface{}) error { +func (g *gDB) Create(value any) error { tx := g.db.Create(value) if err := tx.Error; err != nil { g.logger.Error("db create error", "value", value, "error", err) @@ -294,7 +294,7 @@ func (g *gDB) Create(value interface{}) error { return nil } -func (g *gDB) Update(column string, value interface{}) error { +func (g *gDB) Update(column string, value any) error { tx := g.db.Update(column, value) if err := tx.Error; err != nil { g.logger.Error("db update error", "column", column, "value", value, "error", err) @@ -307,7 +307,7 @@ func (g *gDB) Update(column string, value interface{}) error { return nil } -func (g *gDB) Updates(values interface{}) error { +func (g *gDB) Updates(values any) error { tx := g.db.Updates(values) if err := tx.Error; err != nil { g.logger.Error("db updates error", "values", values, "error", err) @@ -320,7 +320,7 @@ func (g *gDB) Updates(values interface{}) error { return nil } -func (g *gDB) Exec(sql string, values ...interface{}) error { +func (g *gDB) Exec(sql string, values ...any) error { if err := g.db.Exec(sql, values...).Error; err != nil { g.logger.Error("db exec error", "sql", sql, "values", values, "error", err) return errors.Wrap(err, "db exec error") @@ -328,7 +328,7 @@ func (g *gDB) Exec(sql string, values ...interface{}) error { return nil } -func (g *gDB) AutoMigrate(dst ...interface{}) error { +func (g *gDB) AutoMigrate(dst ...any) error { return g.db.Transaction(func(tx *gorm.DB) error { for key, value := range g.driver.MigrateOptions() { tx = tx.Set(key, value) diff --git a/db/db_test.go b/db/db_test.go index e2eed31..9669301 100644 --- a/db/db_test.go +++ b/db/db_test.go @@ -5,7 +5,6 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" "gorm.io/gorm" @@ -24,36 +23,36 @@ func (suite *DBTestSuite) SetupTest() { } func (suite *DBTestSuite) TestExec() { - assert.Error(suite.T(), suite.db.Exec("123")) + suite.Require().Error(suite.db.Exec("123")) } func (suite *DBTestSuite) TestFirst() { module := &gorm.Model{} found, err := suite.db.First(module) - assert.NoError(suite.T(), err) - assert.False(suite.T(), found) - assert.NotNil(suite.T(), module) + suite.Require().NoError(err) + suite.False(found) + suite.NotNil(module) } func (suite *DBTestSuite) TestFirstWhere() { found, err := suite.db.Where("id", 1).First(&gorm.Model{}) - assert.NoError(suite.T(), err) - assert.False(suite.T(), found) + suite.Require().NoError(err) + suite.False(found) } func (suite *DBTestSuite) TestForWhere() { for i := 0; i < 10; i++ { found, err := suite.db.Where("id", 1).First(&gorm.Model{}) - assert.NoError(suite.T(), err) - assert.False(suite.T(), found) + suite.Require().NoError(err) + suite.False(found) } } func (suite *DBTestSuite) TestFind() { modules := make([]gorm.Model, 0) err := suite.db.Find(&modules) - assert.NoError(suite.T(), err) - assert.Len(suite.T(), modules, 0) + suite.Require().NoError(err) + suite.Empty(modules) } func TestDBTestSuite(t *testing.T) { @@ -70,13 +69,13 @@ func (suite *DBTestSuite) TestTransaction() { name: "SUCCESS", malloc: func(tx db.DB) error { err := tx.Create(&gorm.Model{ID: 1}) - assert.NoError(suite.T(), err) + suite.Require().NoError(err) err = tx.Create(&gorm.Model{ID: 2}) - assert.NoError(suite.T(), err) + suite.Require().NoError(err) err = tx.Create(&gorm.Model{ID: 3}) - assert.NoError(suite.T(), err) + suite.Require().NoError(err) return nil }, @@ -86,13 +85,13 @@ func (suite *DBTestSuite) TestTransaction() { name: "rollback", malloc: func(tx db.DB) error { err := tx.Create(&gorm.Model{ID: 4}) - assert.NoError(suite.T(), err) + suite.Require().NoError(err) err = tx.Create(&gorm.Model{ID: 5}) - assert.NoError(suite.T(), err) + suite.Require().NoError(err) err = tx.Create(&gorm.Model{ID: 6}) - assert.NoError(suite.T(), err) + suite.Require().NoError(err) return errors.New("rollback") }, err: errors.New("rollback"), @@ -100,32 +99,32 @@ func (suite *DBTestSuite) TestTransaction() { } for _, tt := range testCases { - suite.T().Run(tt.name, func(t *testing.T) { + suite.Run(tt.name, func() { malloc := tt.malloc err := suite.db.Transaction(malloc) var found bool if err == nil && tt.err == nil { - assert.NoError(suite.T(), err) + suite.Require().NoError(err) found, err = suite.db.Where("id", 1).First(&gorm.Model{}) - assert.NoError(suite.T(), err) - assert.True(suite.T(), found) + suite.Require().NoError(err) + suite.True(found) found, err = suite.db.Where("id", 2).First(&gorm.Model{}) - assert.NoError(suite.T(), err) - assert.True(suite.T(), found) + suite.Require().NoError(err) + suite.True(found) found, err = suite.db.Where("id", 3).First(&gorm.Model{}) - assert.NoError(suite.T(), err) - assert.True(suite.T(), found) + suite.Require().NoError(err) + suite.True(found) } else { - assert.Error(suite.T(), err) + suite.Require().Error(err) found, err = suite.db.Where("id", 4).First(&gorm.Model{}) - assert.NoError(suite.T(), err) - assert.False(suite.T(), found) + suite.Require().NoError(err) + suite.False(found) found, err = suite.db.Where("id", 5).First(&gorm.Model{}) - assert.NoError(suite.T(), err) - assert.False(suite.T(), found) + suite.Require().NoError(err) + suite.False(found) found, err = suite.db.Where("id", 6).First(&gorm.Model{}) - assert.NoError(suite.T(), err) - assert.False(suite.T(), found) + suite.Require().NoError(err) + suite.False(found) } }) } diff --git a/db/driver_test.go b/db/driver_test.go index b2e7f93..6e1d1b5 100644 --- a/db/driver_test.go +++ b/db/driver_test.go @@ -8,7 +8,7 @@ import ( ) func TestRegisterDriver(t *testing.T) { - assert.Equal(t, 2, len(drivers)) + assert.Len(t, drivers, 2) } func TestGetDriver(t *testing.T) { diff --git a/db/mysql.go b/db/mysql.go index 1d1791b..4b4d33d 100644 --- a/db/mysql.go +++ b/db/mysql.go @@ -39,7 +39,7 @@ func (m *Mysql) ToMigrateDriver(source string) (string, database.Driver, error) return m.GetDatabaseName(source), driver, nil } -func (m *Mysql) Open(source string) gorm.Dialector { +func (*Mysql) Open(source string) gorm.Dialector { return mysql.Open(source) } @@ -122,11 +122,11 @@ func (m *Mysql) DropDB(logger log.Logger, config Config) error { return nil } -func (m *Mysql) GetMigrationsDriver() (source.Driver, error) { +func (*Mysql) GetMigrationsDriver() (source.Driver, error) { return GetMigrationsDriver(MysqlDriver) } -func (m *Mysql) MigrateOptions() map[string]string { +func (*Mysql) MigrateOptions() map[string]string { return map[string]string{ "gorm:table_options": "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", } diff --git a/db/sqlite.go b/db/sqlite.go index 5232689..b551c23 100644 --- a/db/sqlite.go +++ b/db/sqlite.go @@ -29,7 +29,7 @@ type Sqlite struct { name string } -func (s *Sqlite) Open(source string) gorm.Dialector { +func (*Sqlite) Open(source string) gorm.Dialector { if err := os.MkdirAll(filepath.Dir(source), os.ModePerm); err != nil { panic(err) } @@ -60,7 +60,7 @@ func (s *Sqlite) GetDatabaseName(source string) string { return s.name } -func (s *Sqlite) CreateDB(logger log.Logger, config Config) error { +func (*Sqlite) CreateDB(logger log.Logger, config Config) error { if err := os.MkdirAll(config.Source, os.ModePerm); err != nil { return errors.Wrap(err, "sqlite: create db error") } @@ -68,7 +68,7 @@ func (s *Sqlite) CreateDB(logger log.Logger, config Config) error { return nil } -func (s *Sqlite) DropDB(logger log.Logger, config Config) error { +func (*Sqlite) DropDB(logger log.Logger, config Config) error { if err := os.RemoveAll(config.Source); err != nil { return errors.Wrap(err, "sqlite: drop db error") } @@ -76,15 +76,15 @@ func (s *Sqlite) DropDB(logger log.Logger, config Config) error { return nil } -func (s *Sqlite) MigrateOptions() map[string]string { +func (*Sqlite) MigrateOptions() map[string]string { return map[string]string{} } -func (s *Sqlite) GetMigrationsDriver() (source.Driver, error) { +func (*Sqlite) GetMigrationsDriver() (source.Driver, error) { return GetMigrationsDriver(SqliteDriver) } -func (s *Sqlite) ToMigrateDriver(source string) (string, database.Driver, error) { +func (*Sqlite) ToMigrateDriver(source string) (string, database.Driver, error) { db, err := sql.Open("sqlite3", source) if err != nil { return "", nil, errors.Wrap(err, "sqlite: open error") diff --git a/db/sqlite_test.go b/db/sqlite_test.go index 89122cb..0562a54 100644 --- a/db/sqlite_test.go +++ b/db/sqlite_test.go @@ -57,28 +57,28 @@ func (suite *SqliteTestSuite) SetupTest() { } func (suite *SqliteTestSuite) TestOpen() { - assert.NotNil(suite.T(), suite.driver.Open("coastdao.db")) + suite.NotNil(suite.driver.Open("coastdao.db")) } func (suite *SqliteTestSuite) TestOpen2() { source := "${HOME}/.coastdao-keeper/coastdao-keeper.db" suite.T().Log(os.ExpandEnv(source)) - assert.NotNil(suite.T(), suite.driver.Open(os.ExpandEnv(source))) + suite.NotNil(suite.driver.Open(os.ExpandEnv(source))) } func (suite *SqliteTestSuite) TestGetDatabaseName() { source := "coastdao.db" - assert.Equal(suite.T(), "coastdao", suite.driver.GetDatabaseName(source)) + suite.Equal("coastdao", suite.driver.GetDatabaseName(source)) source = suite.T().TempDir() + "/coastdao.db" - assert.Equal(suite.T(), "coastdao", suite.driver.GetDatabaseName(source)) + suite.Equal("coastdao", suite.driver.GetDatabaseName(source)) } func (suite *SqliteTestSuite) TestCreateDB() { source := suite.T().TempDir() + "/coastdao.db" - assert.NoError(suite.T(), suite.driver.CreateDB(log.NewNopLogger(), db.Config{Source: source})) + suite.Require().NoError(suite.driver.CreateDB(log.NewNopLogger(), db.Config{Source: source})) defer func() { - assert.NoError(suite.T(), suite.driver.DropDB(log.NewNopLogger(), db.Config{Source: source})) + suite.Require().NoError(suite.driver.DropDB(log.NewNopLogger(), db.Config{Source: source})) }() stat, err := os.Stat(source) suite.Require().NoError(err) diff --git a/eth/config_test.go b/eth/config_test.go index aa13f87..b2b4eaa 100644 --- a/eth/config_test.go +++ b/eth/config_test.go @@ -21,11 +21,11 @@ func (suite *ConfigTestSuite) TestNewDefConfig() { func (suite *ConfigTestSuite) TestCheck() { config := eth.NewDefConfig() - suite.EqualError(config.Check(), "check: chain_id is empty") + suite.Require().EqualError(config.Check(), "check: chain_id is empty") config.ChainId = big.NewInt(1) config.RpcUrl = "" - suite.EqualError(config.Check(), "check: rpc_url is empty") + suite.Require().EqualError(config.Check(), "check: rpc_url is empty") } func TestConfigTestSuite(t *testing.T) { diff --git a/eth/keys.go b/eth/keys.go index ae7050e..90bc960 100644 --- a/eth/keys.go +++ b/eth/keys.go @@ -11,7 +11,7 @@ import ( "github.com/pkg/errors" ) -func NewPrivKeyFromKeyStore(keystoreFile, passwordFile string, needPass bool) (*ecdsa.PrivateKey, error) { +func NewPrivKeyFromKeyStore(keystoreFile, passwordFile string, needPass bool) (*ecdsa.PrivateKey, error) { //nolint:revive // flag-parameter keyJson, err := os.ReadFile(keystoreFile) if err != nil { return nil, errors.Wrap(err, fmt.Sprintf("failed to read the keyfile at %s", keystoreFile)) diff --git a/eth/rpc.go b/eth/rpc.go index 8474290..33d9b7a 100644 --- a/eth/rpc.go +++ b/eth/rpc.go @@ -58,7 +58,7 @@ func NewRPCClient(ctx context.Context, logger log.Logger, config Config) (RPCCli type client struct { *ethclient.Client - logger log.Logger + logger log.Logger //nolint:unused // for debug config Config } diff --git a/log/log.go b/log/log.go index 0d015ff..4bdb33d 100644 --- a/log/log.go +++ b/log/log.go @@ -21,26 +21,24 @@ const ( ) var ( - NewLoggerFunc newLogger = NewZeroLogger + NewLoggerFunc = NewZeroLogger DefaultWriter io.Writer = os.Stdout ) -type newLogger func(format, logLevel string) (Logger, error) - type Logger interface { - With(k, v interface{}) Logger - - Debug(msg string, args ...interface{}) - Info(msg string, args ...interface{}) - Warn(msg string, args ...interface{}) - Error(msg string, args ...interface{}) - Panic(msg string, args ...interface{}) - - Debugf(format string, args ...interface{}) - Infof(format string, args ...interface{}) - Warnf(format string, args ...interface{}) - Errorf(format string, args ...interface{}) - Panicf(format string, args ...interface{}) + With(k, v any) Logger + + Debug(msg string, args ...any) + Info(msg string, args ...any) + Warn(msg string, args ...any) + Error(msg string, args ...any) + Panic(msg string, args ...any) + + Debugf(format string, args ...any) + Infof(format string, args ...any) + Warnf(format string, args ...any) + Errorf(format string, args ...any) + Panicf(format string, args ...any) } func NewLogger(format, logLevel string) (Logger, error) { diff --git a/log/logger.go b/log/logger.go index 65fcce9..d664c8b 100644 --- a/log/logger.go +++ b/log/logger.go @@ -17,34 +17,34 @@ func GetLogger() Logger { return l } -func Debug(msg string, args ...interface{}) { +func Debug(msg string, args ...any) { l.Debug(msg, args...) } -func Debugf(template string, args ...interface{}) { +func Debugf(template string, args ...any) { l.Debugf(template, args...) } -func Info(msg string, args ...interface{}) { +func Info(msg string, args ...any) { l.Info(msg, args...) } -func Infof(template string, args ...interface{}) { +func Infof(template string, args ...any) { l.Infof(template, args...) } -func Warn(msg string, args ...interface{}) { +func Warn(msg string, args ...any) { l.Warn(msg, args...) } -func Warnf(template string, args ...interface{}) { +func Warnf(template string, args ...any) { l.Warnf(template, args...) } -func Error(msg string, args ...interface{}) { +func Error(msg string, args ...any) { l.Error(msg, args...) } -func Errorf(template string, args ...interface{}) { +func Errorf(template string, args ...any) { l.Errorf(template, args...) } diff --git a/log/noplog.go b/log/noplog.go index d975e6c..54c6be8 100644 --- a/log/noplog.go +++ b/log/noplog.go @@ -8,26 +8,26 @@ func NewNopLogger() Logger { type nopLogger struct{} -func (n *nopLogger) With(_, _ interface{}) Logger { +func (n *nopLogger) With(_, _ any) Logger { return n } -func (n *nopLogger) Debug(_ string, _ ...interface{}) {} +func (*nopLogger) Debug(_ string, _ ...any) {} -func (n *nopLogger) Info(_ string, _ ...interface{}) {} +func (*nopLogger) Info(_ string, _ ...any) {} -func (n *nopLogger) Warn(_ string, _ ...interface{}) {} +func (*nopLogger) Warn(_ string, _ ...any) {} -func (n *nopLogger) Error(_ string, _ ...interface{}) {} +func (*nopLogger) Error(_ string, _ ...any) {} -func (n *nopLogger) Panic(_ string, _ ...interface{}) {} +func (*nopLogger) Panic(_ string, _ ...any) {} -func (n *nopLogger) Debugf(_ string, _ ...interface{}) {} +func (*nopLogger) Debugf(_ string, _ ...any) {} -func (n *nopLogger) Infof(_ string, _ ...interface{}) {} +func (*nopLogger) Infof(_ string, _ ...any) {} -func (n *nopLogger) Warnf(_ string, _ ...interface{}) {} +func (*nopLogger) Warnf(_ string, _ ...any) {} -func (n *nopLogger) Errorf(_ string, _ ...interface{}) {} +func (*nopLogger) Errorf(_ string, _ ...any) {} -func (n *nopLogger) Panicf(_ string, _ ...interface{}) {} +func (*nopLogger) Panicf(_ string, _ ...any) {} diff --git a/log/zaplog.go b/log/zaplog.go index 2e245c7..086b4f0 100644 --- a/log/zaplog.go +++ b/log/zaplog.go @@ -31,47 +31,47 @@ func NewZapLogger(format string, logLevel string) (Logger, error) { return &ZapLogger{logger: logger.Sugar()}, nil } -func (l *ZapLogger) With(k, v interface{}) Logger { +func (l *ZapLogger) With(k, v any) Logger { return &ZapLogger{logger: l.logger.With(k, v)} } -func (l *ZapLogger) Debug(msg string, args ...interface{}) { +func (l *ZapLogger) Debug(msg string, args ...any) { l.logger.Debug(msg, args) } -func (l *ZapLogger) Info(msg string, args ...interface{}) { +func (l *ZapLogger) Info(msg string, args ...any) { l.logger.Info(msg, args) } -func (l *ZapLogger) Warn(msg string, args ...interface{}) { +func (l *ZapLogger) Warn(msg string, args ...any) { l.logger.Warn(msg, args) } -func (l *ZapLogger) Error(msg string, args ...interface{}) { +func (l *ZapLogger) Error(msg string, args ...any) { l.logger.Error(msg, args) } -func (l *ZapLogger) Panic(msg string, args ...interface{}) { +func (l *ZapLogger) Panic(msg string, args ...any) { l.logger.Panic(msg, args) } -func (l *ZapLogger) Debugf(format string, args ...interface{}) { +func (l *ZapLogger) Debugf(format string, args ...any) { l.logger.Debugf(format, args...) } -func (l *ZapLogger) Infof(format string, args ...interface{}) { +func (l *ZapLogger) Infof(format string, args ...any) { l.logger.Infof(format, args...) } -func (l *ZapLogger) Warnf(format string, args ...interface{}) { +func (l *ZapLogger) Warnf(format string, args ...any) { l.logger.Warnf(format, args...) } -func (l *ZapLogger) Errorf(format string, args ...interface{}) { +func (l *ZapLogger) Errorf(format string, args ...any) { l.logger.Errorf(format, args...) } -func (l *ZapLogger) Panicf(format string, args ...interface{}) { +func (l *ZapLogger) Panicf(format string, args ...any) { l.logger.Panicf(format, args...) } diff --git a/log/zerolog.go b/log/zerolog.go index a5824cf..29ad2c3 100644 --- a/log/zerolog.go +++ b/log/zerolog.go @@ -15,7 +15,7 @@ func init() { zerolog.TimeFieldFormat = TimeFieldFormat zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack zerolog.CallerSkipFrameCount = 3 - zerolog.CallerMarshalFunc = func(pc uintptr, file string, line int) string { + zerolog.CallerMarshalFunc = func(_ uintptr, file string, line int) string { if parts := strings.Split(file, "/"); len(parts) > 2 && parts[0] == "github.com" { return strings.Join(parts[3:], "/") + ":" + strconv.Itoa(line) } @@ -30,59 +30,59 @@ type ZeroLogger struct { } func NewZeroLogger(format, logLevel string) (Logger, error) { - logger, err := newZeroLogger(format, logLevel) + logger, err := newZeroLog(format, logLevel) if err != nil { return nil, errors.Wrapf(err, "new zero logger failed, format: %s, log level: %s", format, logLevel) } return &ZeroLogger{logger: logger}, nil } -func (l *ZeroLogger) With(k, v interface{}) Logger { - logger := l.logger.With().Fields([]interface{}{k, v}).Logger() +func (l *ZeroLogger) With(k, v any) Logger { + logger := l.logger.With().Fields([]any{k, v}).Logger() return &ZeroLogger{logger: &logger} } -func (l *ZeroLogger) Debug(msg string, args ...interface{}) { +func (l *ZeroLogger) Debug(msg string, args ...any) { l.logger.Debug().Fields(args).Msg(msg) } -func (l *ZeroLogger) Info(msg string, args ...interface{}) { +func (l *ZeroLogger) Info(msg string, args ...any) { l.logger.Info().Fields(args).Msg(msg) } -func (l *ZeroLogger) Warn(msg string, args ...interface{}) { +func (l *ZeroLogger) Warn(msg string, args ...any) { l.logger.Warn().Fields(args).Msg(msg) } -func (l *ZeroLogger) Error(msg string, args ...interface{}) { +func (l *ZeroLogger) Error(msg string, args ...any) { l.logger.Error().Fields(args).Msg(msg) } -func (l *ZeroLogger) Panic(msg string, args ...interface{}) { +func (l *ZeroLogger) Panic(msg string, args ...any) { l.logger.Panic().Fields(args).Msg(msg) } -func (l *ZeroLogger) Debugf(format string, args ...interface{}) { +func (l *ZeroLogger) Debugf(format string, args ...any) { l.logger.Debug().Msgf(format, args...) } -func (l *ZeroLogger) Infof(format string, args ...interface{}) { +func (l *ZeroLogger) Infof(format string, args ...any) { l.logger.Info().Msgf(format, args...) } -func (l *ZeroLogger) Warnf(format string, args ...interface{}) { +func (l *ZeroLogger) Warnf(format string, args ...any) { l.logger.Warn().Msgf(format, args...) } -func (l *ZeroLogger) Errorf(format string, args ...interface{}) { +func (l *ZeroLogger) Errorf(format string, args ...any) { l.logger.Error().Msgf(format, args...) } -func (l *ZeroLogger) Panicf(format string, args ...interface{}) { +func (l *ZeroLogger) Panicf(format string, args ...any) { l.logger.Panic().Msgf(format, args...) } -func newZeroLogger(format, logLevel string) (*zerolog.Logger, error) { +func newZeroLog(format, logLevel string) (*zerolog.Logger, error) { level, err := zerolog.ParseLevel(logLevel) if err != nil { return nil, err diff --git a/log/zerolog_test.go b/log/zerolog_test.go index 14ff0f6..c48adcd 100644 --- a/log/zerolog_test.go +++ b/log/zerolog_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/pundiai/go-sdk/log" ) @@ -14,7 +15,7 @@ func TestZeroLogger_Console(t *testing.T) { log.DefaultWriter = output logger, err := log.NewZeroLogger(log.FormatConsole, log.LevelInfo) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, logger) logger.Info("test") assert.Contains(t, output.String(), "test") @@ -26,7 +27,7 @@ func TestZeroLogger_JSON(t *testing.T) { log.DefaultWriter = output logger, err := log.NewZeroLogger(log.FormatJSON, log.LevelInfo) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, logger) logger.Info("test") assert.Contains(t, output.String(), "test") @@ -35,7 +36,7 @@ func TestZeroLogger_JSON(t *testing.T) { func TestZeroLogger_Nil(t *testing.T) { logger, err := log.NewZeroLogger(log.FormatConsole, log.LevelInfo) - assert.NoError(t, err) + require.NoError(t, err) logger.Info("test", "error", nil) } @@ -44,7 +45,7 @@ func TestZeroLogger_With(t *testing.T) { log.DefaultWriter = output logger, err := log.NewZeroLogger(log.FormatConsole, log.LevelInfo) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, logger) logger = logger.With("key", "value") logger.Info("test") diff --git a/migration/config.go b/migration/config.go index 0c0f4e9..21c5c3f 100644 --- a/migration/config.go +++ b/migration/config.go @@ -26,10 +26,10 @@ func (c Config) IsEnabled() bool { return c.Enabled } -func (c Config) Check() error { +func (Config) Check() error { return nil } -func (c Config) Name() string { +func (Config) Name() string { return "migration" } diff --git a/migration/migration.go b/migration/migration.go index bad8bc8..7766b86 100644 --- a/migration/migration.go +++ b/migration/migration.go @@ -29,7 +29,7 @@ func NewMigration(logger log.Logger, config Config, db db.DB) *Server { } } -func (s *Server) Start(_ *errgroup.Group, _ context.Context) error { +func (s *Server) Start(context.Context, *errgroup.Group) error { if !s.config.Enabled { return nil } @@ -61,6 +61,6 @@ func (s *Server) Start(_ *errgroup.Group, _ context.Context) error { return nil } -func (s *Server) Close() error { +func (*Server) Close() error { return nil } diff --git a/modules/big_int.go b/modules/big_int.go index f4d236c..954241e 100644 --- a/modules/big_int.go +++ b/modules/big_int.go @@ -10,7 +10,7 @@ var _ CustomType = (*BigInt)(nil) type BigInt big.Int -func (b *BigInt) Scan(value interface{}) error { +func (b *BigInt) Scan(value any) error { str, err := unquoteIfQuoted(value) if err != nil { return err @@ -40,7 +40,7 @@ func NewBigInt(value *big.Int) *BigInt { return (*BigInt)(value) } -func unquoteIfQuoted(value interface{}) (string, error) { +func unquoteIfQuoted(value any) (string, error) { var bytes []byte switch v := value.(type) { case string: diff --git a/pprof/config.go b/pprof/config.go index 1fdc971..23c50b0 100644 --- a/pprof/config.go +++ b/pprof/config.go @@ -37,6 +37,6 @@ func (c Config) Check() error { return nil } -func (c Config) Name() string { +func (Config) Name() string { return "pprof" } diff --git a/pprof/server.go b/pprof/server.go index f374793..e7f7773 100644 --- a/pprof/server.go +++ b/pprof/server.go @@ -5,7 +5,7 @@ import ( "fmt" "net" "net/http" - _ "net/http/pprof" + _ "net/http/pprof" //nolint:gosec // for debug "github.com/pkg/errors" "golang.org/x/sync/errgroup" @@ -30,7 +30,7 @@ func NewServer(logger log.Logger, config Config) *Server { } } -func (s *Server) Start(group *errgroup.Group, ctx context.Context) error { +func (s *Server) Start(ctx context.Context, group *errgroup.Group) error { if !s.config.Enabled { return nil } @@ -43,13 +43,13 @@ func (s *Server) Start(group *errgroup.Group, ctx context.Context) error { s.pprof = &http.Server{ Addr: s.config.ListenAddr, ReadHeaderTimeout: s.config.ReadTimeout, - BaseContext: func(listener net.Listener) context.Context { + BaseContext: func(net.Listener) context.Context { return ctx }, } s.logger.Info("starting pprof server", "addr", fmt.Sprintf("http://%s", s.pprof.Addr)) - s.pprof.BaseContext = func(listener net.Listener) context.Context { + s.pprof.BaseContext = func(net.Listener) context.Context { return ctx } group.Go(func() error { diff --git a/pprof/server_test.go b/pprof/server_test.go index 4f36da2..13937d7 100644 --- a/pprof/server_test.go +++ b/pprof/server_test.go @@ -7,6 +7,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "golang.org/x/sync/errgroup" "github.com/pundiai/go-sdk/log" @@ -21,14 +22,14 @@ func TestNewServer(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Millisecond) defer cancel() group, ctx := errgroup.WithContext(ctx) - err := server.Start(group, ctx) - assert.NoError(t, err) + err := server.Start(ctx, group) + require.NoError(t, err) resp, err := http.Get("http://" + config.ListenAddr + "/debug/pprof/") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) <-ctx.Done() - assert.NoError(t, server.Close()) - assert.NoError(t, group.Wait()) + require.NoError(t, server.Close()) + require.NoError(t, group.Wait()) } diff --git a/rand/random.go b/rand/random.go index 0f5321c..d823a37 100644 --- a/rand/random.go +++ b/rand/random.go @@ -162,13 +162,12 @@ loop: if v >= 62 { // only 62 characters in strChars val >>= 6 continue - } else { - chars = append(chars, strChars[v]) - if len(chars) == length { - break loop - } - val >>= 6 } + chars = append(chars, strChars[v]) + if len(chars) == length { + break loop + } + val >>= 6 } } diff --git a/rand/random_test.go b/rand/random_test.go index 9cbda0f..5cadb16 100644 --- a/rand/random_test.go +++ b/rand/random_test.go @@ -14,20 +14,20 @@ import ( func TestRandStr(t *testing.T) { l := 243 s := Str(l) - assert.Equal(t, l, len(s)) + assert.Len(t, s, l) } func TestRandBytes(t *testing.T) { l := 243 b := Bytes(l) - assert.Equal(t, l, len(b)) + assert.Len(t, b, l) } func TestRandIntn(t *testing.T) { n := 243 for i := 0; i < 100; i++ { x := Intn(n) - assert.True(t, x < n) + assert.Less(t, x, n) } } @@ -68,7 +68,7 @@ func testThemAll() string { return out.String() } -func TestRngConcurrencySafety(t *testing.T) { +func TestRngConcurrencySafety(*testing.T) { var wg sync.WaitGroup for i := 0; i < 100; i++ { wg.Add(1) diff --git a/scheduler/scheduler.go b/scheduler/scheduler.go index b4119d4..31343f7 100644 --- a/scheduler/scheduler.go +++ b/scheduler/scheduler.go @@ -39,8 +39,8 @@ func (t *scheduler) Run(ctx context.Context) error { } t.logger.Infof("start %s service", t.config.Name) errCount := uint16(0) + var sleepTime time.Duration normalSleepTime := t.config.Interval - sleepTime := normalSleepTime timer := time.NewTimer(normalSleepTime) defer timer.Stop() for { diff --git a/scheduler/scheduler_test.go b/scheduler/scheduler_test.go index f629598..0fbfd37 100644 --- a/scheduler/scheduler_test.go +++ b/scheduler/scheduler_test.go @@ -33,7 +33,7 @@ func Test_scheduler_Run(t1 *testing.T) { Interval: 100 * time.Millisecond, MaxErrCount: 1, }, - exec: func(ctx context.Context) error { + exec: func(context.Context) error { return nil }, }, @@ -52,7 +52,7 @@ func Test_scheduler_Run(t1 *testing.T) { Interval: 50 * time.Millisecond, MaxErrCount: 2, }, - exec: func(ctx context.Context) error { + exec: func(context.Context) error { return assert.AnError }, }, diff --git a/server/interface.go b/server/interface.go index 6a2dacf..2609d4f 100644 --- a/server/interface.go +++ b/server/interface.go @@ -8,7 +8,7 @@ import ( type Server interface { // Start service and keep the goroutine of the blocked - Start(group *errgroup.Group, ctx context.Context) error + Start(ctx context.Context, group *errgroup.Group) error // Close service and release resources(e.g. http connect) Close() error } diff --git a/telemetry/config.go b/telemetry/config.go index 9cec445..ccc84b2 100644 --- a/telemetry/config.go +++ b/telemetry/config.go @@ -72,6 +72,6 @@ func (c Config) Check() error { return nil } -func (c Config) Name() string { +func (Config) Name() string { return "telemetry" } diff --git a/telemetry/metrics.go b/telemetry/metrics.go index dd432bd..519b1e2 100644 --- a/telemetry/metrics.go +++ b/telemetry/metrics.go @@ -60,7 +60,7 @@ func (s *Server) Gather(format string) (GatherResponse, error) { } } -func (s *Server) gatherPrometheus() (GatherResponse, error) { +func (*Server) gatherPrometheus() (GatherResponse, error) { metricsFamilies, err := prometheus.DefaultGatherer.Gather() if err != nil { return GatherResponse{}, fmt.Errorf("failed to gather prometheus metrics: %w", err) diff --git a/telemetry/server.go b/telemetry/server.go index 33a04d0..34b2f64 100644 --- a/telemetry/server.go +++ b/telemetry/server.go @@ -44,7 +44,7 @@ func NewServer(logger log.Logger, config Config) *Server { } } -func (s *Server) Start(group *errgroup.Group, ctx context.Context) error { +func (s *Server) Start(ctx context.Context, group *errgroup.Group) error { //nolint:revive // cyclomatic if !s.config.Enabled { return nil } @@ -87,7 +87,7 @@ func (s *Server) Start(group *errgroup.Group, ctx context.Context) error { promhttp.HandlerOpts{MaxRequestsInFlight: s.config.MaxOpenConnections}, ), ), - BaseContext: func(listener net.Listener) context.Context { + BaseContext: func(net.Listener) context.Context { return ctx }, } diff --git a/telemetry/server_test.go b/telemetry/server_test.go index e19e2cd..2143837 100644 --- a/telemetry/server_test.go +++ b/telemetry/server_test.go @@ -24,8 +24,8 @@ func TestNewServer(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Millisecond) defer cancel() group, ctx := errgroup.WithContext(ctx) - err := server.Start(group, ctx) - assert.NoError(t, err) + err := server.Start(ctx, group) + require.NoError(t, err) emitMetrics() diff --git a/tool/file.go b/tool/file.go index 8c94095..257c3f3 100644 --- a/tool/file.go +++ b/tool/file.go @@ -7,7 +7,7 @@ import ( "github.com/pkg/errors" ) -func LoadJSONFile(path string, data interface{}) error { +func LoadJSONFile(path string, data any) error { filePtr, err := os.Open(path) if err != nil { return err diff --git a/tool/json.go b/tool/json.go index 48a872c..534b185 100644 --- a/tool/json.go +++ b/tool/json.go @@ -2,18 +2,18 @@ package tool import "encoding/json" -func MustItfToJsonStr(v interface{}) string { - if bts, err := json.Marshal(v); err != nil { +func MustItfToJSONStr(v any) string { + bts, err := json.Marshal(v) + if err != nil { panic(err) - } else { - return string(bts) } + return string(bts) } -func MustItfToJsonStrIndex(v interface{}) string { - if bts, err := json.MarshalIndent(v, "", " "); err != nil { +func MustItfToJSONStrIndex(v any) string { + bts, err := json.MarshalIndent(v, "", " ") + if err != nil { panic(err) - } else { - return string(bts) } + return string(bts) } diff --git a/tool/mapstructure.go b/tool/mapstructure.go index c1fed9f..42bbe27 100644 --- a/tool/mapstructure.go +++ b/tool/mapstructure.go @@ -22,7 +22,7 @@ func ComposeDecodeHookFunc(fs ...mapstructure.DecodeHookFunc) mapstructure.Decod } func StringToBigIntHookFunc() mapstructure.DecodeHookFunc { - return func(f, t reflect.Type, data interface{}) (interface{}, error) { + return func(f, t reflect.Type, data any) (any, error) { if f.Kind() != reflect.String { return data, nil } @@ -38,7 +38,7 @@ func StringToBigIntHookFunc() mapstructure.DecodeHookFunc { } func StringToAddressHookFunc() mapstructure.DecodeHookFunc { - return func(f, t reflect.Type, data interface{}) (interface{}, error) { + return func(f, t reflect.Type, data any) (any, error) { if f.Kind() != reflect.String { return data, nil } @@ -50,7 +50,7 @@ func StringToAddressHookFunc() mapstructure.DecodeHookFunc { } func StringToDecimalHookFunc() mapstructure.DecodeHookFunc { - return func(f, t reflect.Type, data interface{}) (interface{}, error) { + return func(f, t reflect.Type, data any) (any, error) { if t != reflect.TypeOf(decimal.Decimal{}) { return data, nil } From e3eda839162284f66bf96a9229efbba03b4067b8 Mon Sep 17 00:00:00 2001 From: zakir <80246097+zakir-code@users.noreply.github.com> Date: Wed, 20 Nov 2024 15:05:00 +0800 Subject: [PATCH 2/2] format --- .golangci.yml | 6 +----- db/config.go | 2 +- db/config_test.go | 20 ++++++++++---------- db/mysql_test.go | 4 ++-- db/sqlite_test.go | 22 +++++++++++----------- pprof/server.go | 3 --- 6 files changed, 25 insertions(+), 32 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 0850cf0..2e3b390 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -81,9 +81,7 @@ linters-settings: - name: add-constant disabled: true - name: cognitive-complexity - disabled: false - exclude: - - "**_test.go" + disabled: true - name: function-length disabled: true - name: var-naming @@ -97,5 +95,3 @@ linters-settings: - "fmt.Println" - name: import-shadowing disabled: true - - name: cognitive-complexity - disabled: true \ No newline at end of file diff --git a/db/config.go b/db/config.go index 2f5e9ca..dd39e0e 100644 --- a/db/config.go +++ b/db/config.go @@ -35,7 +35,7 @@ type Config struct { func NewDefConfig() Config { return Config{ Driver: SqliteDriver, - Source: os.ExpandEnv("$HOME/.coastdao/coastdao.db"), + Source: os.ExpandEnv("$HOME/.my/my.db"), ConnMaxIdleTime: time.Hour, ConnMaxLifeTime: time.Hour, MaxIdleConn: 10, diff --git a/db/config_test.go b/db/config_test.go index 0d68ad7..42d32c0 100644 --- a/db/config_test.go +++ b/db/config_test.go @@ -14,9 +14,9 @@ type ConfigTestSuite struct { func (suite *ConfigTestSuite) TestNewDefConfig() { config := db.NewDefConfig() - config.Source = "root:root@tcp(127.0.0.1:3306)/coastdao?charset=utf8mb4&parseTime=True&loc=Local" + config.Source = "root:root@tcp(127.0.0.1:3306)/my?charset=utf8mb4&parseTime=True&loc=Local" suite.Equal(`driver: sqlite -source: '****:****@tcp(127.0.0.1:3306)/coastdao?charset=utf8mb4&parseTime=True&loc=Local' +source: '****:****@tcp(127.0.0.1:3306)/my?charset=utf8mb4&parseTime=True&loc=Local' conn_max_idle_time: 1h0m0s conn_max_life_time: 1h0m0s max_idle_conn: 10 @@ -47,23 +47,23 @@ func TestSourceDesensitization(t *testing.T) { }{ { name: "test1", - source: "coastdao.db", - want: "coastdao.db", + source: "my.db", + want: "my.db", }, { name: "test2", - source: "root:root@tcp(127.0.0.1:3306)/coastdao?charset=utf8mb4&parseTime=True&loc=Local", - want: "****:****@tcp(127.0.0.1:3306)/coastdao?charset=utf8mb4&parseTime=True&loc=Local", + source: "root:root@tcp(127.0.0.1:3306)/my?charset=utf8mb4&parseTime=True&loc=Local", + want: "****:****@tcp(127.0.0.1:3306)/my?charset=utf8mb4&parseTime=True&loc=Local", }, { name: "test3", - source: "root@tcp(127.0.0.1:3306)/coastdao?charset=utf8mb4&parseTime=True&loc=Local", - want: "*:*@tcp(127.0.0.1:3306)/coastdao?charset=utf8mb4&parseTime=True&loc=Local", + source: "root@tcp(127.0.0.1:3306)/my?charset=utf8mb4&parseTime=True&loc=Local", + want: "*:*@tcp(127.0.0.1:3306)/my?charset=utf8mb4&parseTime=True&loc=Local", }, { name: "test4", - source: "tcp(127.0.0.1:3306)/coastdao?charset=utf8mb4&parseTime=True&loc=Local", - want: "tcp(127.0.0.1:3306)/coastdao?charset=utf8mb4&parseTime=True&loc=Local", + source: "tcp(127.0.0.1:3306)/my?charset=utf8mb4&parseTime=True&loc=Local", + want: "tcp(127.0.0.1:3306)/my?charset=utf8mb4&parseTime=True&loc=Local", }, } for _, tt := range tests { diff --git a/db/mysql_test.go b/db/mysql_test.go index e08b818..7344feb 100644 --- a/db/mysql_test.go +++ b/db/mysql_test.go @@ -15,7 +15,7 @@ func TestMysql_CheckSource(t *testing.T) { }{ { name: "test1", - source: "root:root@tcp(127.0.0.1:3306)/coastdao?charset=utf8mb4&parseTime=True&loc=Local", + source: "root:root@tcp(127.0.0.1:3306)/my?charset=utf8mb4&parseTime=True&loc=Local", wantErr: assert.NoError, }, { @@ -25,7 +25,7 @@ func TestMysql_CheckSource(t *testing.T) { }, { name: "test3", - source: "coastdao", + source: "my", wantErr: assert.Error, }, } diff --git a/db/sqlite_test.go b/db/sqlite_test.go index 0562a54..ad1f0dc 100644 --- a/db/sqlite_test.go +++ b/db/sqlite_test.go @@ -20,7 +20,7 @@ func TestSqlite_CheckSource(t *testing.T) { }{ { name: "test1", - source: "coastdao.db", + source: "my.db", wantErr: assert.NoError, }, { @@ -30,12 +30,12 @@ func TestSqlite_CheckSource(t *testing.T) { }, { name: "test3", - source: "coastdao", + source: "my", wantErr: assert.Error, }, { name: "test4", - source: "file:coastdao.db?mode=memory", + source: "file:my.db?mode=memory", wantErr: assert.NoError, }, } @@ -57,25 +57,25 @@ func (suite *SqliteTestSuite) SetupTest() { } func (suite *SqliteTestSuite) TestOpen() { - suite.NotNil(suite.driver.Open("coastdao.db")) + suite.NotNil(suite.driver.Open("my.db")) } func (suite *SqliteTestSuite) TestOpen2() { - source := "${HOME}/.coastdao-keeper/coastdao-keeper.db" + source := "${HOME}/.my/my.db" suite.T().Log(os.ExpandEnv(source)) suite.NotNil(suite.driver.Open(os.ExpandEnv(source))) } func (suite *SqliteTestSuite) TestGetDatabaseName() { - source := "coastdao.db" - suite.Equal("coastdao", suite.driver.GetDatabaseName(source)) + source := "my.db" + suite.Equal("my", suite.driver.GetDatabaseName(source)) - source = suite.T().TempDir() + "/coastdao.db" - suite.Equal("coastdao", suite.driver.GetDatabaseName(source)) + source = suite.T().TempDir() + "/my.db" + suite.Equal("my", suite.driver.GetDatabaseName(source)) } func (suite *SqliteTestSuite) TestCreateDB() { - source := suite.T().TempDir() + "/coastdao.db" + source := suite.T().TempDir() + "/my.db" suite.Require().NoError(suite.driver.CreateDB(log.NewNopLogger(), db.Config{Source: source})) defer func() { suite.Require().NoError(suite.driver.DropDB(log.NewNopLogger(), db.Config{Source: source})) @@ -84,7 +84,7 @@ func (suite *SqliteTestSuite) TestCreateDB() { suite.Require().NoError(err) suite.Require().NotNil(stat) suite.True(stat.IsDir()) - suite.Equal("coastdao.db", stat.Name()) + suite.Equal("my.db", stat.Name()) } func TestSqliteTestSuite(t *testing.T) { diff --git a/pprof/server.go b/pprof/server.go index e7f7773..1811ee3 100644 --- a/pprof/server.go +++ b/pprof/server.go @@ -49,9 +49,6 @@ func (s *Server) Start(ctx context.Context, group *errgroup.Group) error { } s.logger.Info("starting pprof server", "addr", fmt.Sprintf("http://%s", s.pprof.Addr)) - s.pprof.BaseContext = func(net.Listener) context.Context { - return ctx - } group.Go(func() error { if err := s.pprof.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) { s.logger.Error("pprof HTTP server listen", "error", err)