From 41790b80acf9fd93bc0582e9c895b2fa1a263c53 Mon Sep 17 00:00:00 2001 From: loyalsoldier <10487845+Loyalsoldier@users.noreply.github.com> Date: Sun, 6 Jun 2021 21:00:27 +0800 Subject: [PATCH] Fix lint and format code in core dir --- CHANGELOG.md | 1 + core/admin/profile.go | 7 ++-- core/bean/context.go | 3 +- core/berror/pre_define_code.go | 1 + core/config/base_config_test.go | 1 - core/config/config.go | 4 +-- core/config/config_test.go | 2 -- core/config/etcd/config.go | 5 +-- core/config/etcd/config_test.go | 1 - core/config/global.go | 9 +++++ core/config/ini.go | 3 +- core/config/ini_test.go | 3 -- core/config/json/json.go | 3 +- core/config/json/json_test.go | 2 -- core/config/toml/toml.go | 6 ---- core/config/xml/xml.go | 2 -- core/config/xml/xml_test.go | 2 -- core/config/yaml/yaml.go | 2 -- core/config/yaml/yaml_test.go | 1 - core/logs/alils/alils.go | 2 -- core/logs/alils/log_project.go | 6 ---- core/logs/alils/log_store.go | 1 - core/logs/conn.go | 1 - core/logs/conn_test.go | 1 - core/logs/console.go | 3 -- core/logs/es/es.go | 3 -- core/logs/file.go | 2 -- core/logs/file_test.go | 12 ++++--- core/logs/jianliao.go | 1 - core/logs/log.go | 7 ++-- core/logs/logger.go | 6 ++-- core/logs/multifile.go | 1 - core/logs/multifile_test.go | 3 +- core/utils/debug.go | 56 +++++++++++++++--------------- core/utils/debug_test.go | 4 +-- core/utils/kv_test.go | 1 - core/utils/rand.go | 2 +- core/utils/safemap.go | 3 +- core/utils/slice.go | 1 + core/utils/time.go | 2 -- core/validation/validation.go | 7 ++-- core/validation/validation_test.go | 1 - 42 files changed, 75 insertions(+), 109 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 057e5a39..3a8f4cb8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,6 +52,7 @@ - Optimize AddAutoPrefix: only register one router in case-insensitive mode. [4582](https://github.com/beego/beego/pull/4582) - Init exceptMethod by using reflection. [4583](https://github.com/beego/beego/pull/4583) - Deprecated BeeMap and replace all usage with `sync.map` [4616](https://github.com/beego/beego/pull/4616) +- Fix lint and format code in core dir [4654](https://github.com/beego/beego/pull/4654) - TaskManager support graceful shutdown [4635](https://github.com/beego/beego/pull/4635) - Fix lint and format code in adapter/cache dir [4645](https://github.com/beego/beego/pull/4645) diff --git a/core/admin/profile.go b/core/admin/profile.go index 6162a2d4..bd9eff4d 100644 --- a/core/admin/profile.go +++ b/core/admin/profile.go @@ -29,8 +29,10 @@ import ( "github.com/beego/beego/v2/core/utils" ) -var startTime = time.Now() -var pid int +var ( + startTime = time.Now() + pid int +) func init() { pid = os.Getpid() @@ -105,7 +107,6 @@ func PrintGCSummary(w io.Writer) { } func printGC(memStats *runtime.MemStats, gcstats *debug.GCStats, w io.Writer) { - if gcstats.NumGC > 0 { lastPause := gcstats.Pause[0] elapsed := time.Since(startTime) diff --git a/core/bean/context.go b/core/bean/context.go index 7cee2c7e..78666437 100644 --- a/core/bean/context.go +++ b/core/bean/context.go @@ -16,5 +16,4 @@ package bean // ApplicationContext define for future // when we decide to support DI, IoC, this will be core API -type ApplicationContext interface { -} +type ApplicationContext interface{} diff --git a/core/berror/pre_define_code.go b/core/berror/pre_define_code.go index 275f86c1..ff8eb46b 100644 --- a/core/berror/pre_define_code.go +++ b/core/berror/pre_define_code.go @@ -46,6 +46,7 @@ func init() { func goCodeBlock(code string) string { return codeBlock("go", code) } + func codeBlock(lan string, code string) string { return fmt.Sprintf("```%s\n%s\n```", lan, code) } diff --git a/core/config/base_config_test.go b/core/config/base_config_test.go index 74a669a7..340d05db 100644 --- a/core/config/base_config_test.go +++ b/core/config/base_config_test.go @@ -66,7 +66,6 @@ func newBaseConfier(str1 string) *BaseConfiger { } else { return "", errors.New("mock error") } - }, } } diff --git a/core/config/config.go b/core/config/config.go index 98080fe3..5c931995 100644 --- a/core/config/config.go +++ b/core/config/config.go @@ -165,6 +165,7 @@ func (c *BaseConfiger) DefaultBool(key string, defaultVal bool) bool { } return defaultVal } + func (c *BaseConfiger) DefaultFloat(key string, defaultVal float64) float64 { if res, err := c.Float(key); err == nil { return res @@ -370,5 +371,4 @@ func ToString(x interface{}) string { type DecodeOption func(options decodeOptions) -type decodeOptions struct { -} +type decodeOptions struct{} diff --git a/core/config/config_test.go b/core/config/config_test.go index 15d6ffa6..86d3a2c5 100644 --- a/core/config/config_test.go +++ b/core/config/config_test.go @@ -20,7 +20,6 @@ import ( ) func TestExpandValueEnv(t *testing.T) { - testCases := []struct { item string want string @@ -51,5 +50,4 @@ func TestExpandValueEnv(t *testing.T) { t.Errorf("expand value error, item %q want %q, got %q", c.item, c.want, got) } } - } diff --git a/core/config/etcd/config.go b/core/config/etcd/config.go index 0f7d81c8..fb12b065 100644 --- a/core/config/etcd/config.go +++ b/core/config/etcd/config.go @@ -119,7 +119,6 @@ func (e *EtcdConfiger) Sub(key string) (config.Configer, error) { // TODO remove this before release v2.0.0 func (e *EtcdConfiger) OnChange(key string, fn func(value string)) { - buildOptsFunc := func() []clientv3.OpOption { return []clientv3.OpOption{} } @@ -144,11 +143,9 @@ func (e *EtcdConfiger) OnChange(key string, fn func(value string)) { rch = e.client.Watch(context.Background(), e.prefix+key, buildOptsFunc()...) } }() - } -type EtcdConfigerProvider struct { -} +type EtcdConfigerProvider struct{} // Parse = ParseData([]byte(key)) // key must be json diff --git a/core/config/etcd/config_test.go b/core/config/etcd/config_test.go index 6907fd26..ffaf2727 100644 --- a/core/config/etcd/config_test.go +++ b/core/config/etcd/config_test.go @@ -32,7 +32,6 @@ func TestEtcdConfigerProvider_Parse(t *testing.T) { } func TestEtcdConfiger(t *testing.T) { - provider := &EtcdConfigerProvider{} cfger, _ := provider.Parse(readEtcdConfig()) diff --git a/core/config/global.go b/core/config/global.go index d0b74253..3a334cb6 100644 --- a/core/config/global.go +++ b/core/config/global.go @@ -42,15 +42,19 @@ func String(key string) (string, error) { func Strings(key string) ([]string, error) { return globalInstance.Strings(key) } + func Int(key string) (int, error) { return globalInstance.Int(key) } + func Int64(key string) (int64, error) { return globalInstance.Int64(key) } + func Bool(key string) (bool, error) { return globalInstance.Bool(key) } + func Float(key string) (float64, error) { return globalInstance.Float(key) } @@ -64,15 +68,19 @@ func DefaultString(key string, defaultVal string) string { func DefaultStrings(key string, defaultVal []string) []string { return globalInstance.DefaultStrings(key, defaultVal) } + func DefaultInt(key string, defaultVal int) int { return globalInstance.DefaultInt(key, defaultVal) } + func DefaultInt64(key string, defaultVal int64) int64 { return globalInstance.DefaultInt64(key, defaultVal) } + func DefaultBool(key string, defaultVal bool) bool { return globalInstance.DefaultBool(key, defaultVal) } + func DefaultFloat(key string, defaultVal float64) float64 { return globalInstance.DefaultFloat(key, defaultVal) } @@ -89,6 +97,7 @@ func GetSection(section string) (map[string]string, error) { func Unmarshaler(prefix string, obj interface{}, opt ...DecodeOption) error { return globalInstance.Unmarshaler(prefix, obj, opt...) } + func Sub(key string) (Configer, error) { return globalInstance.Sub(key) } diff --git a/core/config/ini.go b/core/config/ini.go index 205760c2..4d80fbbf 100644 --- a/core/config/ini.go +++ b/core/config/ini.go @@ -46,8 +46,7 @@ var ( ) // IniConfig implements Config to parse ini file. -type IniConfig struct { -} +type IniConfig struct{} // Parse creates a new Config and parses the file configuration from the named file. func (ini *IniConfig) Parse(name string) (Configer, error) { diff --git a/core/config/ini_test.go b/core/config/ini_test.go index b7a03aa2..37ec7203 100644 --- a/core/config/ini_test.go +++ b/core/config/ini_test.go @@ -23,7 +23,6 @@ import ( ) func TestIni(t *testing.T) { - var ( inicontext = ` ;comment one @@ -129,11 +128,9 @@ password = ${GOPATH} if res != "astaxie" { t.Fatal("get name error") } - } func TestIniSave(t *testing.T) { - const ( inicontext = ` app = app diff --git a/core/config/json/json.go b/core/config/json/json.go index c1a29cad..21f2b958 100644 --- a/core/config/json/json.go +++ b/core/config/json/json.go @@ -31,8 +31,7 @@ import ( ) // JSONConfig is a json config parser and implements Config interface. -type JSONConfig struct { -} +type JSONConfig struct{} // Parse returns a ConfigContainer with parsed json config map. func (js *JSONConfig) Parse(filename string) (config.Configer, error) { diff --git a/core/config/json/json_test.go b/core/config/json/json_test.go index 8f5b2c83..2d107183 100644 --- a/core/config/json/json_test.go +++ b/core/config/json/json_test.go @@ -25,7 +25,6 @@ import ( ) func TestJsonStartsWithArray(t *testing.T) { - const jsoncontextwitharray = `[ { "url": "user", @@ -72,7 +71,6 @@ func TestJsonStartsWithArray(t *testing.T) { } func TestJson(t *testing.T) { - var ( jsoncontext = `{ "appname": "beeapi", diff --git a/core/config/toml/toml.go b/core/config/toml/toml.go index 9261cd27..0c678164 100644 --- a/core/config/toml/toml.go +++ b/core/config/toml/toml.go @@ -47,7 +47,6 @@ func (c *Config) ParseData(data []byte) (config.Configer, error) { return &configContainer{ t: t, }, nil - } // configContainer support key looks like "a.b.c" @@ -70,7 +69,6 @@ func (c *configContainer) Set(key, val string) error { // return error if key not found or value is invalid type func (c *configContainer) String(key string) (string, error) { res, err := c.get(key) - if err != nil { return "", err } @@ -90,7 +88,6 @@ func (c *configContainer) String(key string) (string, error) { // return error if key not found or value is invalid type func (c *configContainer) Strings(key string) ([]string, error) { val, err := c.get(key) - if err != nil { return []string{}, err } @@ -141,9 +138,7 @@ func (c *configContainer) Int64(key string) (int64, error) { // bool return bool value // return error if key not found or value is invalid type func (c *configContainer) Bool(key string) (bool, error) { - res, err := c.get(key) - if err != nil { return false, err } @@ -330,7 +325,6 @@ func (c *configContainer) get(key string) (interface{}, error) { segs := strings.Split(key, keySeparator) t, err := subTree(c.t, segs[0:len(segs)-1]) - if err != nil { return nil, err } diff --git a/core/config/xml/xml.go b/core/config/xml/xml.go index 9eed2fa0..067d4811 100644 --- a/core/config/xml/xml.go +++ b/core/config/xml/xml.go @@ -102,7 +102,6 @@ func (c *ConfigContainer) Sub(key string) (config.Configer, error) { return &ConfigContainer{ data: sub, }, nil - } func (c *ConfigContainer) sub(key string) (map[string]interface{}, error) { @@ -170,7 +169,6 @@ func (c *ConfigContainer) DefaultInt64(key string, defaultVal int64) int64 { return defaultVal } return v - } // Float returns the float value for a given key. diff --git a/core/config/xml/xml_test.go b/core/config/xml/xml_test.go index 37c5fe7f..c71488fe 100644 --- a/core/config/xml/xml_test.go +++ b/core/config/xml/xml_test.go @@ -25,7 +25,6 @@ import ( ) func TestXML(t *testing.T) { - var ( // xml parse should incluce in tags xmlcontext = ` @@ -149,7 +148,6 @@ func TestXML(t *testing.T) { err = xmlconf.Unmarshaler("mysection", sec) assert.Nil(t, err) assert.Equal(t, "MySection", sec.Name) - } type Section struct { diff --git a/core/config/yaml/yaml.go b/core/config/yaml/yaml.go index 10335123..2dec5eb5 100644 --- a/core/config/yaml/yaml.go +++ b/core/config/yaml/yaml.go @@ -302,7 +302,6 @@ func (c *ConfigContainer) DefaultStrings(key string, defaultVal []string) []stri // GetSection returns map for the given section func (c *ConfigContainer) GetSection(section string) (map[string]string, error) { - if v, ok := c.data[section]; ok { return v.(map[string]string), nil } @@ -335,7 +334,6 @@ func (c *ConfigContainer) DIY(key string) (v interface{}, err error) { } func (c *ConfigContainer) getData(key string) (interface{}, error) { - if len(key) == 0 { return nil, errors.New("key is empty") } diff --git a/core/config/yaml/yaml_test.go b/core/config/yaml/yaml_test.go index cf889613..164abe9f 100644 --- a/core/config/yaml/yaml_test.go +++ b/core/config/yaml/yaml_test.go @@ -25,7 +25,6 @@ import ( ) func TestYaml(t *testing.T) { - var ( yamlcontext = ` "appname": beeapi diff --git a/core/logs/alils/alils.go b/core/logs/alils/alils.go index 7a3e4ddf..6fd8702a 100644 --- a/core/logs/alils/alils.go +++ b/core/logs/alils/alils.go @@ -180,7 +180,6 @@ func (c *aliLSWriter) WriteMsg(lm *logs.LogMsg) error { // Flush implementing method. empty. func (c *aliLSWriter) Flush() { - // flush all group for _, lg := range c.group { c.flush(lg) @@ -192,7 +191,6 @@ func (c *aliLSWriter) Destroy() { } func (c *aliLSWriter) flush(lg *LogGroup) { - c.lock.Lock() defer c.lock.Unlock() err := c.store.PutLogs(lg) diff --git a/core/logs/alils/log_project.go b/core/logs/alils/log_project.go index 7ede3fef..f993003e 100755 --- a/core/logs/alils/log_project.go +++ b/core/logs/alils/log_project.go @@ -128,7 +128,6 @@ func (p *LogProject) GetLogStore(name string) (s *LogStore, err error) { // and ttl is time-to-live(in day) of logs, // and shardCnt is the number of shards. func (p *LogProject) CreateLogStore(name string, ttl, shardCnt int) (err error) { - type Body struct { Name string `json:"logstoreName"` TTL int `json:"ttl"` @@ -212,7 +211,6 @@ func (p *LogProject) DeleteLogStore(name string) (err error) { // UpdateLogStore updates a logstore according by logstore name, // obviously we can't modify the logstore name itself. func (p *LogProject) UpdateLogStore(name string, ttl, shardCnt int) (err error) { - type Body struct { Name string `json:"logstoreName"` TTL int `json:"ttl"` @@ -355,7 +353,6 @@ func (p *LogProject) GetMachineGroup(name string) (m *MachineGroup, err error) { // CreateMachineGroup creates a new machine group in SLS. func (p *LogProject) CreateMachineGroup(m *MachineGroup) (err error) { - body, err := json.Marshal(m) if err != nil { return @@ -395,7 +392,6 @@ func (p *LogProject) CreateMachineGroup(m *MachineGroup) (err error) { // UpdateMachineGroup updates a machine group. func (p *LogProject) UpdateMachineGroup(m *MachineGroup) (err error) { - body, err := json.Marshal(m) if err != nil { return @@ -555,7 +551,6 @@ func (p *LogProject) GetConfig(name string) (c *LogConfig, err error) { // UpdateConfig updates a config. func (p *LogProject) UpdateConfig(c *LogConfig) (err error) { - body, err := json.Marshal(c) if err != nil { return @@ -595,7 +590,6 @@ func (p *LogProject) UpdateConfig(c *LogConfig) (err error) { // CreateConfig creates a new config in SLS. func (p *LogProject) CreateConfig(c *LogConfig) (err error) { - body, err := json.Marshal(c) if err != nil { return diff --git a/core/logs/alils/log_store.go b/core/logs/alils/log_store.go index d5ff25e2..fd9d9eaf 100755 --- a/core/logs/alils/log_store.go +++ b/core/logs/alils/log_store.go @@ -241,7 +241,6 @@ func (s *LogStore) GetLogsBytes(shardID int, cursor string, // LogsBytesDecode decodes logs binary data retruned by GetLogsBytes API func LogsBytesDecode(data []byte) (gl *LogGroupList, err error) { - gl = &LogGroupList{} err = proto.Unmarshal(data, gl) if err != nil { diff --git a/core/logs/conn.go b/core/logs/conn.go index 1fd71be7..cfeb3f91 100644 --- a/core/logs/conn.go +++ b/core/logs/conn.go @@ -95,7 +95,6 @@ func (c *connWriter) WriteMsg(lm *LogMsg) error { // Flush implementing method. empty. func (c *connWriter) Flush() { - } // Destroy destroy connection writer and close tcp listener. diff --git a/core/logs/conn_test.go b/core/logs/conn_test.go index ca9ea1c7..85b95c10 100644 --- a/core/logs/conn_test.go +++ b/core/logs/conn_test.go @@ -26,7 +26,6 @@ import ( // ConnTCPListener takes a TCP listener and accepts n TCP connections // Returns connections using connChan func connTCPListener(t *testing.T, n int, ln net.Listener, connChan chan<- net.Conn) { - // Listen and accept n incoming connections for i := 0; i < n; i++ { conn, err := ln.Accept() diff --git a/core/logs/console.go b/core/logs/console.go index 66e2c7ea..849e9c6e 100644 --- a/core/logs/console.go +++ b/core/logs/console.go @@ -88,7 +88,6 @@ func newConsole() *consoleWriter { // Init initianlizes the console logger. // jsonConfig must be in the format '{"level":LevelTrace}' func (c *consoleWriter) Init(config string) error { - if len(config) == 0 { return nil } @@ -116,12 +115,10 @@ func (c *consoleWriter) WriteMsg(lm *LogMsg) error { // Destroy implementing method. empty. func (c *consoleWriter) Destroy() { - } // Flush implementing method. empty. func (c *consoleWriter) Flush() { - } func init() { diff --git a/core/logs/es/es.go b/core/logs/es/es.go index 1140da97..2073ab3d 100644 --- a/core/logs/es/es.go +++ b/core/logs/es/es.go @@ -41,7 +41,6 @@ type esLogger struct { } func (el *esLogger) Format(lm *logs.LogMsg) string { - msg := lm.OldStyleFormat() idx := LogDocument{ Timestamp: lm.When.Format(time.RFC3339), @@ -60,7 +59,6 @@ func (el *esLogger) SetFormatter(f logs.LogFormatter) { // {"dsn":"http://localhost:9200/","level":1} func (el *esLogger) Init(config string) error { - err := json.Unmarshal([]byte(config), el) if err != nil { return err @@ -113,7 +111,6 @@ func (el *esLogger) Destroy() { // Flush is a empty method func (el *esLogger) Flush() { - } type LogDocument struct { diff --git a/core/logs/file.go b/core/logs/file.go index 97c4a72d..80114db2 100644 --- a/core/logs/file.go +++ b/core/logs/file.go @@ -117,7 +117,6 @@ func (w *fileLogWriter) SetFormatter(f LogFormatter) { // "perm":"0600" // } func (w *fileLogWriter) Init(config string) error { - err := json.Unmarshal([]byte(config), w) if err != nil { return err @@ -165,7 +164,6 @@ func (w *fileLogWriter) needRotateHourly(hour int) bool { return (w.MaxLines > 0 && w.maxLinesCurLines >= w.MaxLines) || (w.MaxSize > 0 && w.maxSizeCurSize >= w.MaxSize) || (w.Hourly && hour != w.hourlyOpenDate) - } // WriteMsg writes logger message into file. diff --git a/core/logs/file_test.go b/core/logs/file_test.go index e9a8922b..16220936 100644 --- a/core/logs/file_test.go +++ b/core/logs/file_test.go @@ -42,7 +42,7 @@ func TestFilePerm(t *testing.T) { if err != nil { t.Fatal(err) } - if file.Mode() != 0666 { + if file.Mode() != 0o666 { t.Fatal("unexpected log file permission") } os.Remove("test.log") @@ -74,7 +74,7 @@ func TestFile1(t *testing.T) { lineNum++ } } - var expected = LevelDebug + 1 + expected := LevelDebug + 1 if lineNum != expected { t.Fatal(lineNum, "not "+strconv.Itoa(expected)+" lines") } @@ -107,7 +107,7 @@ func TestFile2(t *testing.T) { lineNum++ } } - var expected = LevelError + 1 + expected := LevelError + 1 if lineNum != expected { t.Fatal(lineNum, "not "+strconv.Itoa(expected)+" lines") } @@ -164,6 +164,7 @@ func TestFileDailyRotate_05(t *testing.T) { testFileDailyRotate(t, fn1, fn2) os.Remove(fn) } + func TestFileDailyRotate_06(t *testing.T) { // test file mode log := NewLogger(10000) log.SetLogger("file", `{"filename":"test3.log","maxlines":4}`) @@ -177,7 +178,7 @@ func TestFileDailyRotate_06(t *testing.T) { // test file mode log.Emergency("emergency") rotateName := "test3" + fmt.Sprintf(".%s.%03d", time.Now().Format("2006-01-02"), 1) + ".log" s, _ := os.Lstat(rotateName) - if s.Mode() != 0440 { + if s.Mode() != 0o440 { os.Remove(rotateName) os.Remove("test3.log") t.Fatal("rotate file mode error") @@ -250,7 +251,7 @@ func TestFileHourlyRotate_06(t *testing.T) { // test file mode log.Emergency("emergency") rotateName := "test3" + fmt.Sprintf(".%s.%03d", time.Now().Format("2006010215"), 1) + ".log" s, _ := os.Lstat(rotateName) - if s.Mode() != 0440 { + if s.Mode() != 0o440 { os.Remove(rotateName) os.Remove("test3.log") t.Fatal("rotate file mode error") @@ -369,6 +370,7 @@ func testFileHourlyRotate(t *testing.T, fn1, fn2 string) { } fw.Destroy() } + func exists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { diff --git a/core/logs/jianliao.go b/core/logs/jianliao.go index c82a0957..95835c06 100644 --- a/core/logs/jianliao.go +++ b/core/logs/jianliao.go @@ -31,7 +31,6 @@ func newJLWriter() Logger { // Init JLWriter with json config string func (s *JLWriter) Init(config string) error { - res := json.Unmarshal([]byte(config), s) if res == nil && len(s.Formatter) > 0 { fmtr, ok := GetFormatter(s.Formatter) diff --git a/core/logs/log.go b/core/logs/log.go index cf3ce8e0..ad2ef953 100644 --- a/core/logs/log.go +++ b/core/logs/log.go @@ -92,8 +92,10 @@ type Logger interface { SetFormatter(f LogFormatter) } -var adapters = make(map[string]newLoggerFunc) -var levelPrefix = [LevelDebug + 1]string{"[M]", "[A]", "[C]", "[E]", "[W]", "[N]", "[I]", "[D]"} +var ( + adapters = make(map[string]newLoggerFunc) + levelPrefix = [LevelDebug + 1]string{"[M]", "[A]", "[C]", "[E]", "[W]", "[N]", "[I]", "[D]"} +) // Register makes a log provide available by the provided name. // If Register is called twice with the same name or if driver is nil, @@ -201,7 +203,6 @@ func (bl *BeeLogger) setLogger(adapterName string, configs ...string) error { } err := lg.Init(config) - if err != nil { fmt.Fprintln(os.Stderr, "logs.BeeLogger.SetLogger: "+err.Error()) return err diff --git a/core/logs/logger.go b/core/logs/logger.go index 77e68ea2..29e33a82 100644 --- a/core/logs/logger.go +++ b/core/logs/logger.go @@ -112,8 +112,10 @@ var ( reset = string([]byte{27, 91, 48, 109}) ) -var once sync.Once -var colorMap map[string]string +var ( + once sync.Once + colorMap map[string]string +) func initColor() { if runtime.GOOS == "windows" { diff --git a/core/logs/multifile.go b/core/logs/multifile.go index 79178211..0ad8244f 100644 --- a/core/logs/multifile.go +++ b/core/logs/multifile.go @@ -45,7 +45,6 @@ var levelNames = [...]string{"emergency", "alert", "critical", "error", "warning // } func (f *multiFileLogWriter) Init(config string) error { - writer := newFileWriter().(*fileLogWriter) err := writer.Init(config) if err != nil { diff --git a/core/logs/multifile_test.go b/core/logs/multifile_test.go index 57b96094..8050bc6b 100644 --- a/core/logs/multifile_test.go +++ b/core/logs/multifile_test.go @@ -60,7 +60,7 @@ func TestFiles_1(t *testing.T) { lineNum++ } } - var expected = 1 + expected := 1 if fn == "" { expected = LevelDebug + 1 } @@ -74,5 +74,4 @@ func TestFiles_1(t *testing.T) { } os.Remove(file) } - } diff --git a/core/utils/debug.go b/core/utils/debug.go index 93c27b70..93279181 100644 --- a/core/utils/debug.go +++ b/core/utils/debug.go @@ -47,20 +47,20 @@ func GetDisplayString(data ...interface{}) string { } func display(displayed bool, data ...interface{}) string { - var pc, file, line, ok = runtime.Caller(2) + pc, file, line, ok := runtime.Caller(2) if !ok { return "" } - var buf = new(bytes.Buffer) + buf := new(bytes.Buffer) fmt.Fprintf(buf, "[Debug] at %s() [%s:%d]\n", function(pc), file, line) fmt.Fprintf(buf, "\n[Variables]\n") for i := 0; i < len(data); i += 2 { - var output = fomateinfo(len(data[i].(string))+3, data[i+1]) + output := fomateinfo(len(data[i].(string))+3, data[i+1]) fmt.Fprintf(buf, "%s = %s", data[i], output) } @@ -72,7 +72,7 @@ func display(displayed bool, data ...interface{}) string { // return data dump and format bytes func fomateinfo(headlen int, data ...interface{}) []byte { - var buf = new(bytes.Buffer) + buf := new(bytes.Buffer) if len(data) > 1 { fmt.Fprint(buf, " ") @@ -83,9 +83,9 @@ func fomateinfo(headlen int, data ...interface{}) []byte { } for k, v := range data { - var buf2 = new(bytes.Buffer) + buf2 := new(bytes.Buffer) var pointers *pointerInfo - var interfaces = make([]reflect.Value, 0, 10) + interfaces := make([]reflect.Value, 0, 10) printKeyValue(buf2, reflect.ValueOf(v), &pointers, &interfaces, nil, true, " ", 1) @@ -140,13 +140,13 @@ func isSimpleType(val reflect.Value, kind reflect.Kind, pointers **pointerInfo, return true } - var elem = val.Elem() + elem := val.Elem() if isSimpleType(elem, elem.Kind(), pointers, interfaces) { return true } - var addr = val.Elem().UnsafeAddr() + addr := val.Elem().UnsafeAddr() for p := *pointers; p != nil; p = p.prev { if addr == p.addr { @@ -162,7 +162,7 @@ func isSimpleType(val reflect.Value, kind reflect.Kind, pointers **pointerInfo, // dump value func printKeyValue(buf *bytes.Buffer, val reflect.Value, pointers **pointerInfo, interfaces *[]reflect.Value, structFilter func(string, string) bool, formatOutput bool, indent string, level int) { - var t = val.Kind() + t := val.Kind() switch t { case reflect.Bool: @@ -183,7 +183,7 @@ func printKeyValue(buf *bytes.Buffer, val reflect.Value, pointers **pointerInfo, return } - var addr = val.Elem().UnsafeAddr() + addr := val.Elem().UnsafeAddr() for p := *pointers; p != nil; p = p.prev { if addr == p.addr { @@ -206,7 +206,7 @@ func printKeyValue(buf *bytes.Buffer, val reflect.Value, pointers **pointerInfo, case reflect.String: fmt.Fprint(buf, "\"", val.String(), "\"") case reflect.Interface: - var value = val.Elem() + value := val.Elem() if !value.IsValid() { fmt.Fprint(buf, "nil") @@ -223,7 +223,7 @@ func printKeyValue(buf *bytes.Buffer, val reflect.Value, pointers **pointerInfo, printKeyValue(buf, value, pointers, interfaces, structFilter, formatOutput, indent, level+1) } case reflect.Struct: - var t = val.Type() + t := val.Type() fmt.Fprint(buf, t) fmt.Fprint(buf, "{") @@ -235,7 +235,7 @@ func printKeyValue(buf *bytes.Buffer, val reflect.Value, pointers **pointerInfo, fmt.Fprint(buf, " ") } - var name = t.Field(i).Name + name := t.Field(i).Name if formatOutput { for ind := 0; ind < level; ind++ { @@ -270,12 +270,12 @@ func printKeyValue(buf *bytes.Buffer, val reflect.Value, pointers **pointerInfo, fmt.Fprint(buf, val.Type()) fmt.Fprint(buf, "{") - var allSimple = true + allSimple := true for i := 0; i < val.Len(); i++ { - var elem = val.Index(i) + elem := val.Index(i) - var isSimple = isSimpleType(elem, elem.Kind(), pointers, interfaces) + isSimple := isSimpleType(elem, elem.Kind(), pointers, interfaces) if !isSimple { allSimple = false @@ -312,18 +312,18 @@ func printKeyValue(buf *bytes.Buffer, val reflect.Value, pointers **pointerInfo, fmt.Fprint(buf, "}") case reflect.Map: - var t = val.Type() - var keys = val.MapKeys() + t := val.Type() + keys := val.MapKeys() fmt.Fprint(buf, t) fmt.Fprint(buf, "{") - var allSimple = true + allSimple := true for i := 0; i < len(keys); i++ { - var elem = val.MapIndex(keys[i]) + elem := val.MapIndex(keys[i]) - var isSimple = isSimpleType(elem, elem.Kind(), pointers, interfaces) + isSimple := isSimpleType(elem, elem.Kind(), pointers, interfaces) if !isSimple { allSimple = false @@ -372,8 +372,8 @@ func printKeyValue(buf *bytes.Buffer, val reflect.Value, pointers **pointerInfo, // PrintPointerInfo dump pointer value func PrintPointerInfo(buf *bytes.Buffer, headlen int, pointers *pointerInfo) { - var anyused = false - var pointerNum = 0 + anyused := false + pointerNum := 0 for p := pointers; p != nil; p = p.prev { if len(p.used) > 0 { @@ -384,10 +384,10 @@ func PrintPointerInfo(buf *bytes.Buffer, headlen int, pointers *pointerInfo) { } if anyused { - var pointerBufs = make([][]rune, pointerNum+1) + pointerBufs := make([][]rune, pointerNum+1) for i := 0; i < len(pointerBufs); i++ { - var pointerBuf = make([]rune, buf.Len()+headlen) + pointerBuf := make([]rune, buf.Len()+headlen) for j := 0; j < len(pointerBuf); j++ { pointerBuf[j] = ' ' @@ -402,7 +402,7 @@ func PrintPointerInfo(buf *bytes.Buffer, headlen int, pointers *pointerInfo) { if pn == p.n { pointerBufs[pn][p.pos+headlen] = '└' - var maxpos = 0 + maxpos := 0 for i, pos := range p.used { if i < len(p.used)-1 { @@ -440,10 +440,10 @@ func PrintPointerInfo(buf *bytes.Buffer, headlen int, pointers *pointerInfo) { // Stack get stack bytes func Stack(skip int, indent string) []byte { - var buf = new(bytes.Buffer) + buf := new(bytes.Buffer) for i := skip; ; i++ { - var pc, file, line, ok = runtime.Caller(i) + pc, file, line, ok := runtime.Caller(i) if !ok { break diff --git a/core/utils/debug_test.go b/core/utils/debug_test.go index efb8924e..a748d20a 100644 --- a/core/utils/debug_test.go +++ b/core/utils/debug_test.go @@ -28,8 +28,8 @@ func TestPrint(t *testing.T) { } func TestPrintPoint(t *testing.T) { - var v1 = new(mytype) - var v2 = new(mytype) + v1 := new(mytype) + v2 := new(mytype) v1.prev = nil v1.next = v2 diff --git a/core/utils/kv_test.go b/core/utils/kv_test.go index 4c9643dc..cd0dc5c3 100644 --- a/core/utils/kv_test.go +++ b/core/utils/kv_test.go @@ -34,5 +34,4 @@ func TestKVs(t *testing.T) { v = kvs.GetValueOr(`key-not-exists`, 8546) assert.Equal(t, 8546, v) - } diff --git a/core/utils/rand.go b/core/utils/rand.go index 344d1cd5..f80dad7d 100644 --- a/core/utils/rand.go +++ b/core/utils/rand.go @@ -27,7 +27,7 @@ func RandomCreateBytes(n int, alphabets ...byte) []byte { if len(alphabets) == 0 { alphabets = alphaNum } - var bytes = make([]byte, n) + bytes := make([]byte, n) var randBy bool if num, err := rand.Read(bytes); num != n || err != nil { r.Seed(time.Now().UnixNano()) diff --git a/core/utils/safemap.go b/core/utils/safemap.go index 05763786..1f9923f1 100644 --- a/core/utils/safemap.go +++ b/core/utils/safemap.go @@ -18,8 +18,7 @@ import ( "sync" ) - -//deprecated +// deprecated type BeeMap struct { lock *sync.RWMutex bm map[interface{}]interface{} diff --git a/core/utils/slice.go b/core/utils/slice.go index 8f2cef98..0eda4670 100644 --- a/core/utils/slice.go +++ b/core/utils/slice.go @@ -20,6 +20,7 @@ import ( ) type reducetype func(interface{}) interface{} + type filtertype func(interface{}) bool // InSlice checks given string in string slice or not. diff --git a/core/utils/time.go b/core/utils/time.go index 579b292a..00d13861 100644 --- a/core/utils/time.go +++ b/core/utils/time.go @@ -21,7 +21,6 @@ import ( // short string format func ToShortTimeFormat(d time.Duration) string { - u := uint64(d) if u < uint64(time.Second) { switch { @@ -44,5 +43,4 @@ func ToShortTimeFormat(d time.Duration) string { return fmt.Sprintf("%.2fh", float64(u)/1000/1000/1000/60/60) } } - } diff --git a/core/validation/validation.go b/core/validation/validation.go index 6be10ef3..78a31f13 100644 --- a/core/validation/validation.go +++ b/core/validation/validation.go @@ -235,8 +235,11 @@ func (v *Validation) Tel(obj interface{}, key string) *Result { // Phone Test that the obj is chinese mobile or telephone number if type is string func (v *Validation) Phone(obj interface{}, key string) *Result { - return v.apply(Phone{Mobile{Match: Match{Regexp: mobilePattern}}, - Tel{Match: Match{Regexp: telPattern}}, key}, obj) + return v.apply(Phone{ + Mobile{Match: Match{Regexp: mobilePattern}}, + Tel{Match: Match{Regexp: telPattern}}, + key, + }, obj) } // ZipCode Test that the obj is chinese zip code if type is string diff --git a/core/validation/validation_test.go b/core/validation/validation_test.go index bca4f560..00a45a98 100644 --- a/core/validation/validation_test.go +++ b/core/validation/validation_test.go @@ -605,7 +605,6 @@ func TestCanSkipAlso(t *testing.T) { if !b { t.Fatal("validation should be passed") } - } func TestFieldNoEmpty(t *testing.T) {