Merge pull request #4654 from Loyalsoldier/core-fix-lint

Fix lint and format code in core dir
This commit is contained in:
Ming Deng 2021-06-06 23:16:30 +08:00 committed by GitHub
commit 83798989c3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
42 changed files with 75 additions and 109 deletions

View File

@ -50,6 +50,7 @@
- Optimize AddAutoPrefix: only register one router in case-insensitive mode. [4582](https://github.com/beego/beego/pull/4582) - 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) - 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) - 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) - TaskManager support graceful shutdown [4635](https://github.com/beego/beego/pull/4635)
## Fix Sonar ## Fix Sonar

View File

@ -29,8 +29,10 @@ import (
"github.com/beego/beego/v2/core/utils" "github.com/beego/beego/v2/core/utils"
) )
var startTime = time.Now() var (
var pid int startTime = time.Now()
pid int
)
func init() { func init() {
pid = os.Getpid() pid = os.Getpid()
@ -105,7 +107,6 @@ func PrintGCSummary(w io.Writer) {
} }
func printGC(memStats *runtime.MemStats, gcstats *debug.GCStats, w io.Writer) { func printGC(memStats *runtime.MemStats, gcstats *debug.GCStats, w io.Writer) {
if gcstats.NumGC > 0 { if gcstats.NumGC > 0 {
lastPause := gcstats.Pause[0] lastPause := gcstats.Pause[0]
elapsed := time.Since(startTime) elapsed := time.Since(startTime)

View File

@ -16,5 +16,4 @@ package bean
// ApplicationContext define for future // ApplicationContext define for future
// when we decide to support DI, IoC, this will be core API // when we decide to support DI, IoC, this will be core API
type ApplicationContext interface { type ApplicationContext interface{}
}

View File

@ -46,6 +46,7 @@ func init() {
func goCodeBlock(code string) string { func goCodeBlock(code string) string {
return codeBlock("go", code) return codeBlock("go", code)
} }
func codeBlock(lan string, code string) string { func codeBlock(lan string, code string) string {
return fmt.Sprintf("```%s\n%s\n```", lan, code) return fmt.Sprintf("```%s\n%s\n```", lan, code)
} }

View File

@ -66,7 +66,6 @@ func newBaseConfier(str1 string) *BaseConfiger {
} else { } else {
return "", errors.New("mock error") return "", errors.New("mock error")
} }
}, },
} }
} }

View File

@ -165,6 +165,7 @@ func (c *BaseConfiger) DefaultBool(key string, defaultVal bool) bool {
} }
return defaultVal return defaultVal
} }
func (c *BaseConfiger) DefaultFloat(key string, defaultVal float64) float64 { func (c *BaseConfiger) DefaultFloat(key string, defaultVal float64) float64 {
if res, err := c.Float(key); err == nil { if res, err := c.Float(key); err == nil {
return res return res
@ -370,5 +371,4 @@ func ToString(x interface{}) string {
type DecodeOption func(options decodeOptions) type DecodeOption func(options decodeOptions)
type decodeOptions struct { type decodeOptions struct{}
}

View File

@ -20,7 +20,6 @@ import (
) )
func TestExpandValueEnv(t *testing.T) { func TestExpandValueEnv(t *testing.T) {
testCases := []struct { testCases := []struct {
item string item string
want 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) t.Errorf("expand value error, item %q want %q, got %q", c.item, c.want, got)
} }
} }
} }

View File

@ -119,7 +119,6 @@ func (e *EtcdConfiger) Sub(key string) (config.Configer, error) {
// TODO remove this before release v2.0.0 // TODO remove this before release v2.0.0
func (e *EtcdConfiger) OnChange(key string, fn func(value string)) { func (e *EtcdConfiger) OnChange(key string, fn func(value string)) {
buildOptsFunc := func() []clientv3.OpOption { buildOptsFunc := func() []clientv3.OpOption {
return []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()...) rch = e.client.Watch(context.Background(), e.prefix+key, buildOptsFunc()...)
} }
}() }()
} }
type EtcdConfigerProvider struct { type EtcdConfigerProvider struct{}
}
// Parse = ParseData([]byte(key)) // Parse = ParseData([]byte(key))
// key must be json // key must be json

View File

@ -32,7 +32,6 @@ func TestEtcdConfigerProvider_Parse(t *testing.T) {
} }
func TestEtcdConfiger(t *testing.T) { func TestEtcdConfiger(t *testing.T) {
provider := &EtcdConfigerProvider{} provider := &EtcdConfigerProvider{}
cfger, _ := provider.Parse(readEtcdConfig()) cfger, _ := provider.Parse(readEtcdConfig())

View File

@ -42,15 +42,19 @@ func String(key string) (string, error) {
func Strings(key string) ([]string, error) { func Strings(key string) ([]string, error) {
return globalInstance.Strings(key) return globalInstance.Strings(key)
} }
func Int(key string) (int, error) { func Int(key string) (int, error) {
return globalInstance.Int(key) return globalInstance.Int(key)
} }
func Int64(key string) (int64, error) { func Int64(key string) (int64, error) {
return globalInstance.Int64(key) return globalInstance.Int64(key)
} }
func Bool(key string) (bool, error) { func Bool(key string) (bool, error) {
return globalInstance.Bool(key) return globalInstance.Bool(key)
} }
func Float(key string) (float64, error) { func Float(key string) (float64, error) {
return globalInstance.Float(key) return globalInstance.Float(key)
} }
@ -64,15 +68,19 @@ func DefaultString(key string, defaultVal string) string {
func DefaultStrings(key string, defaultVal []string) []string { func DefaultStrings(key string, defaultVal []string) []string {
return globalInstance.DefaultStrings(key, defaultVal) return globalInstance.DefaultStrings(key, defaultVal)
} }
func DefaultInt(key string, defaultVal int) int { func DefaultInt(key string, defaultVal int) int {
return globalInstance.DefaultInt(key, defaultVal) return globalInstance.DefaultInt(key, defaultVal)
} }
func DefaultInt64(key string, defaultVal int64) int64 { func DefaultInt64(key string, defaultVal int64) int64 {
return globalInstance.DefaultInt64(key, defaultVal) return globalInstance.DefaultInt64(key, defaultVal)
} }
func DefaultBool(key string, defaultVal bool) bool { func DefaultBool(key string, defaultVal bool) bool {
return globalInstance.DefaultBool(key, defaultVal) return globalInstance.DefaultBool(key, defaultVal)
} }
func DefaultFloat(key string, defaultVal float64) float64 { func DefaultFloat(key string, defaultVal float64) float64 {
return globalInstance.DefaultFloat(key, defaultVal) 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 { func Unmarshaler(prefix string, obj interface{}, opt ...DecodeOption) error {
return globalInstance.Unmarshaler(prefix, obj, opt...) return globalInstance.Unmarshaler(prefix, obj, opt...)
} }
func Sub(key string) (Configer, error) { func Sub(key string) (Configer, error) {
return globalInstance.Sub(key) return globalInstance.Sub(key)
} }

View File

@ -46,8 +46,7 @@ var (
) )
// IniConfig implements Config to parse ini file. // 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. // Parse creates a new Config and parses the file configuration from the named file.
func (ini *IniConfig) Parse(name string) (Configer, error) { func (ini *IniConfig) Parse(name string) (Configer, error) {

View File

@ -23,7 +23,6 @@ import (
) )
func TestIni(t *testing.T) { func TestIni(t *testing.T) {
var ( var (
inicontext = ` inicontext = `
;comment one ;comment one
@ -129,11 +128,9 @@ password = ${GOPATH}
if res != "astaxie" { if res != "astaxie" {
t.Fatal("get name error") t.Fatal("get name error")
} }
} }
func TestIniSave(t *testing.T) { func TestIniSave(t *testing.T) {
const ( const (
inicontext = ` inicontext = `
app = app app = app

View File

@ -31,8 +31,7 @@ import (
) )
// JSONConfig is a json config parser and implements Config interface. // 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. // Parse returns a ConfigContainer with parsed json config map.
func (js *JSONConfig) Parse(filename string) (config.Configer, error) { func (js *JSONConfig) Parse(filename string) (config.Configer, error) {

View File

@ -25,7 +25,6 @@ import (
) )
func TestJsonStartsWithArray(t *testing.T) { func TestJsonStartsWithArray(t *testing.T) {
const jsoncontextwitharray = `[ const jsoncontextwitharray = `[
{ {
"url": "user", "url": "user",
@ -72,7 +71,6 @@ func TestJsonStartsWithArray(t *testing.T) {
} }
func TestJson(t *testing.T) { func TestJson(t *testing.T) {
var ( var (
jsoncontext = `{ jsoncontext = `{
"appname": "beeapi", "appname": "beeapi",

View File

@ -47,7 +47,6 @@ func (c *Config) ParseData(data []byte) (config.Configer, error) {
return &configContainer{ return &configContainer{
t: t, t: t,
}, nil }, nil
} }
// configContainer support key looks like "a.b.c" // 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 // return error if key not found or value is invalid type
func (c *configContainer) String(key string) (string, error) { func (c *configContainer) String(key string) (string, error) {
res, err := c.get(key) res, err := c.get(key)
if err != nil { if err != nil {
return "", err 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 // return error if key not found or value is invalid type
func (c *configContainer) Strings(key string) ([]string, error) { func (c *configContainer) Strings(key string) ([]string, error) {
val, err := c.get(key) val, err := c.get(key)
if err != nil { if err != nil {
return []string{}, err return []string{}, err
} }
@ -141,9 +138,7 @@ func (c *configContainer) Int64(key string) (int64, error) {
// bool return bool value // bool return bool value
// return error if key not found or value is invalid type // return error if key not found or value is invalid type
func (c *configContainer) Bool(key string) (bool, error) { func (c *configContainer) Bool(key string) (bool, error) {
res, err := c.get(key) res, err := c.get(key)
if err != nil { if err != nil {
return false, err return false, err
} }
@ -330,7 +325,6 @@ func (c *configContainer) get(key string) (interface{}, error) {
segs := strings.Split(key, keySeparator) segs := strings.Split(key, keySeparator)
t, err := subTree(c.t, segs[0:len(segs)-1]) t, err := subTree(c.t, segs[0:len(segs)-1])
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -102,7 +102,6 @@ func (c *ConfigContainer) Sub(key string) (config.Configer, error) {
return &ConfigContainer{ return &ConfigContainer{
data: sub, data: sub,
}, nil }, nil
} }
func (c *ConfigContainer) sub(key string) (map[string]interface{}, error) { 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 defaultVal
} }
return v return v
} }
// Float returns the float value for a given key. // Float returns the float value for a given key.

View File

@ -25,7 +25,6 @@ import (
) )
func TestXML(t *testing.T) { func TestXML(t *testing.T) {
var ( var (
// xml parse should incluce in <config></config> tags // xml parse should incluce in <config></config> tags
xmlcontext = `<?xml version="1.0" encoding="UTF-8"?> xmlcontext = `<?xml version="1.0" encoding="UTF-8"?>
@ -149,7 +148,6 @@ func TestXML(t *testing.T) {
err = xmlconf.Unmarshaler("mysection", sec) err = xmlconf.Unmarshaler("mysection", sec)
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, "MySection", sec.Name) assert.Equal(t, "MySection", sec.Name)
} }
type Section struct { type Section struct {

View File

@ -302,7 +302,6 @@ func (c *ConfigContainer) DefaultStrings(key string, defaultVal []string) []stri
// GetSection returns map for the given section // GetSection returns map for the given section
func (c *ConfigContainer) GetSection(section string) (map[string]string, error) { func (c *ConfigContainer) GetSection(section string) (map[string]string, error) {
if v, ok := c.data[section]; ok { if v, ok := c.data[section]; ok {
return v.(map[string]string), nil 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) { func (c *ConfigContainer) getData(key string) (interface{}, error) {
if len(key) == 0 { if len(key) == 0 {
return nil, errors.New("key is empty") return nil, errors.New("key is empty")
} }

View File

@ -25,7 +25,6 @@ import (
) )
func TestYaml(t *testing.T) { func TestYaml(t *testing.T) {
var ( var (
yamlcontext = ` yamlcontext = `
"appname": beeapi "appname": beeapi

View File

@ -180,7 +180,6 @@ func (c *aliLSWriter) WriteMsg(lm *logs.LogMsg) error {
// Flush implementing method. empty. // Flush implementing method. empty.
func (c *aliLSWriter) Flush() { func (c *aliLSWriter) Flush() {
// flush all group // flush all group
for _, lg := range c.group { for _, lg := range c.group {
c.flush(lg) c.flush(lg)
@ -192,7 +191,6 @@ func (c *aliLSWriter) Destroy() {
} }
func (c *aliLSWriter) flush(lg *LogGroup) { func (c *aliLSWriter) flush(lg *LogGroup) {
c.lock.Lock() c.lock.Lock()
defer c.lock.Unlock() defer c.lock.Unlock()
err := c.store.PutLogs(lg) err := c.store.PutLogs(lg)

View File

@ -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 ttl is time-to-live(in day) of logs,
// and shardCnt is the number of shards. // and shardCnt is the number of shards.
func (p *LogProject) CreateLogStore(name string, ttl, shardCnt int) (err error) { func (p *LogProject) CreateLogStore(name string, ttl, shardCnt int) (err error) {
type Body struct { type Body struct {
Name string `json:"logstoreName"` Name string `json:"logstoreName"`
TTL int `json:"ttl"` TTL int `json:"ttl"`
@ -212,7 +211,6 @@ func (p *LogProject) DeleteLogStore(name string) (err error) {
// UpdateLogStore updates a logstore according by logstore name, // UpdateLogStore updates a logstore according by logstore name,
// obviously we can't modify the logstore name itself. // obviously we can't modify the logstore name itself.
func (p *LogProject) UpdateLogStore(name string, ttl, shardCnt int) (err error) { func (p *LogProject) UpdateLogStore(name string, ttl, shardCnt int) (err error) {
type Body struct { type Body struct {
Name string `json:"logstoreName"` Name string `json:"logstoreName"`
TTL int `json:"ttl"` 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. // CreateMachineGroup creates a new machine group in SLS.
func (p *LogProject) CreateMachineGroup(m *MachineGroup) (err error) { func (p *LogProject) CreateMachineGroup(m *MachineGroup) (err error) {
body, err := json.Marshal(m) body, err := json.Marshal(m)
if err != nil { if err != nil {
return return
@ -395,7 +392,6 @@ func (p *LogProject) CreateMachineGroup(m *MachineGroup) (err error) {
// UpdateMachineGroup updates a machine group. // UpdateMachineGroup updates a machine group.
func (p *LogProject) UpdateMachineGroup(m *MachineGroup) (err error) { func (p *LogProject) UpdateMachineGroup(m *MachineGroup) (err error) {
body, err := json.Marshal(m) body, err := json.Marshal(m)
if err != nil { if err != nil {
return return
@ -555,7 +551,6 @@ func (p *LogProject) GetConfig(name string) (c *LogConfig, err error) {
// UpdateConfig updates a config. // UpdateConfig updates a config.
func (p *LogProject) UpdateConfig(c *LogConfig) (err error) { func (p *LogProject) UpdateConfig(c *LogConfig) (err error) {
body, err := json.Marshal(c) body, err := json.Marshal(c)
if err != nil { if err != nil {
return return
@ -595,7 +590,6 @@ func (p *LogProject) UpdateConfig(c *LogConfig) (err error) {
// CreateConfig creates a new config in SLS. // CreateConfig creates a new config in SLS.
func (p *LogProject) CreateConfig(c *LogConfig) (err error) { func (p *LogProject) CreateConfig(c *LogConfig) (err error) {
body, err := json.Marshal(c) body, err := json.Marshal(c)
if err != nil { if err != nil {
return return

View File

@ -241,7 +241,6 @@ func (s *LogStore) GetLogsBytes(shardID int, cursor string,
// LogsBytesDecode decodes logs binary data retruned by GetLogsBytes API // LogsBytesDecode decodes logs binary data retruned by GetLogsBytes API
func LogsBytesDecode(data []byte) (gl *LogGroupList, err error) { func LogsBytesDecode(data []byte) (gl *LogGroupList, err error) {
gl = &LogGroupList{} gl = &LogGroupList{}
err = proto.Unmarshal(data, gl) err = proto.Unmarshal(data, gl)
if err != nil { if err != nil {

View File

@ -95,7 +95,6 @@ func (c *connWriter) WriteMsg(lm *LogMsg) error {
// Flush implementing method. empty. // Flush implementing method. empty.
func (c *connWriter) Flush() { func (c *connWriter) Flush() {
} }
// Destroy destroy connection writer and close tcp listener. // Destroy destroy connection writer and close tcp listener.

View File

@ -26,7 +26,6 @@ import (
// ConnTCPListener takes a TCP listener and accepts n TCP connections // ConnTCPListener takes a TCP listener and accepts n TCP connections
// Returns connections using connChan // Returns connections using connChan
func connTCPListener(t *testing.T, n int, ln net.Listener, connChan chan<- net.Conn) { func connTCPListener(t *testing.T, n int, ln net.Listener, connChan chan<- net.Conn) {
// Listen and accept n incoming connections // Listen and accept n incoming connections
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
conn, err := ln.Accept() conn, err := ln.Accept()

View File

@ -88,7 +88,6 @@ func newConsole() *consoleWriter {
// Init initianlizes the console logger. // Init initianlizes the console logger.
// jsonConfig must be in the format '{"level":LevelTrace}' // jsonConfig must be in the format '{"level":LevelTrace}'
func (c *consoleWriter) Init(config string) error { func (c *consoleWriter) Init(config string) error {
if len(config) == 0 { if len(config) == 0 {
return nil return nil
} }
@ -116,12 +115,10 @@ func (c *consoleWriter) WriteMsg(lm *LogMsg) error {
// Destroy implementing method. empty. // Destroy implementing method. empty.
func (c *consoleWriter) Destroy() { func (c *consoleWriter) Destroy() {
} }
// Flush implementing method. empty. // Flush implementing method. empty.
func (c *consoleWriter) Flush() { func (c *consoleWriter) Flush() {
} }
func init() { func init() {

View File

@ -41,7 +41,6 @@ type esLogger struct {
} }
func (el *esLogger) Format(lm *logs.LogMsg) string { func (el *esLogger) Format(lm *logs.LogMsg) string {
msg := lm.OldStyleFormat() msg := lm.OldStyleFormat()
idx := LogDocument{ idx := LogDocument{
Timestamp: lm.When.Format(time.RFC3339), Timestamp: lm.When.Format(time.RFC3339),
@ -60,7 +59,6 @@ func (el *esLogger) SetFormatter(f logs.LogFormatter) {
// {"dsn":"http://localhost:9200/","level":1} // {"dsn":"http://localhost:9200/","level":1}
func (el *esLogger) Init(config string) error { func (el *esLogger) Init(config string) error {
err := json.Unmarshal([]byte(config), el) err := json.Unmarshal([]byte(config), el)
if err != nil { if err != nil {
return err return err
@ -113,7 +111,6 @@ func (el *esLogger) Destroy() {
// Flush is a empty method // Flush is a empty method
func (el *esLogger) Flush() { func (el *esLogger) Flush() {
} }
type LogDocument struct { type LogDocument struct {

View File

@ -117,7 +117,6 @@ func (w *fileLogWriter) SetFormatter(f LogFormatter) {
// "perm":"0600" // "perm":"0600"
// } // }
func (w *fileLogWriter) Init(config string) error { func (w *fileLogWriter) Init(config string) error {
err := json.Unmarshal([]byte(config), w) err := json.Unmarshal([]byte(config), w)
if err != nil { if err != nil {
return err return err
@ -165,7 +164,6 @@ func (w *fileLogWriter) needRotateHourly(hour int) bool {
return (w.MaxLines > 0 && w.maxLinesCurLines >= w.MaxLines) || return (w.MaxLines > 0 && w.maxLinesCurLines >= w.MaxLines) ||
(w.MaxSize > 0 && w.maxSizeCurSize >= w.MaxSize) || (w.MaxSize > 0 && w.maxSizeCurSize >= w.MaxSize) ||
(w.Hourly && hour != w.hourlyOpenDate) (w.Hourly && hour != w.hourlyOpenDate)
} }
// WriteMsg writes logger message into file. // WriteMsg writes logger message into file.

View File

@ -42,7 +42,7 @@ func TestFilePerm(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if file.Mode() != 0666 { if file.Mode() != 0o666 {
t.Fatal("unexpected log file permission") t.Fatal("unexpected log file permission")
} }
os.Remove("test.log") os.Remove("test.log")
@ -74,7 +74,7 @@ func TestFile1(t *testing.T) {
lineNum++ lineNum++
} }
} }
var expected = LevelDebug + 1 expected := LevelDebug + 1
if lineNum != expected { if lineNum != expected {
t.Fatal(lineNum, "not "+strconv.Itoa(expected)+" lines") t.Fatal(lineNum, "not "+strconv.Itoa(expected)+" lines")
} }
@ -107,7 +107,7 @@ func TestFile2(t *testing.T) {
lineNum++ lineNum++
} }
} }
var expected = LevelError + 1 expected := LevelError + 1
if lineNum != expected { if lineNum != expected {
t.Fatal(lineNum, "not "+strconv.Itoa(expected)+" lines") t.Fatal(lineNum, "not "+strconv.Itoa(expected)+" lines")
} }
@ -164,6 +164,7 @@ func TestFileDailyRotate_05(t *testing.T) {
testFileDailyRotate(t, fn1, fn2) testFileDailyRotate(t, fn1, fn2)
os.Remove(fn) os.Remove(fn)
} }
func TestFileDailyRotate_06(t *testing.T) { // test file mode func TestFileDailyRotate_06(t *testing.T) { // test file mode
log := NewLogger(10000) log := NewLogger(10000)
log.SetLogger("file", `{"filename":"test3.log","maxlines":4}`) log.SetLogger("file", `{"filename":"test3.log","maxlines":4}`)
@ -177,7 +178,7 @@ func TestFileDailyRotate_06(t *testing.T) { // test file mode
log.Emergency("emergency") log.Emergency("emergency")
rotateName := "test3" + fmt.Sprintf(".%s.%03d", time.Now().Format("2006-01-02"), 1) + ".log" rotateName := "test3" + fmt.Sprintf(".%s.%03d", time.Now().Format("2006-01-02"), 1) + ".log"
s, _ := os.Lstat(rotateName) s, _ := os.Lstat(rotateName)
if s.Mode() != 0440 { if s.Mode() != 0o440 {
os.Remove(rotateName) os.Remove(rotateName)
os.Remove("test3.log") os.Remove("test3.log")
t.Fatal("rotate file mode error") t.Fatal("rotate file mode error")
@ -250,7 +251,7 @@ func TestFileHourlyRotate_06(t *testing.T) { // test file mode
log.Emergency("emergency") log.Emergency("emergency")
rotateName := "test3" + fmt.Sprintf(".%s.%03d", time.Now().Format("2006010215"), 1) + ".log" rotateName := "test3" + fmt.Sprintf(".%s.%03d", time.Now().Format("2006010215"), 1) + ".log"
s, _ := os.Lstat(rotateName) s, _ := os.Lstat(rotateName)
if s.Mode() != 0440 { if s.Mode() != 0o440 {
os.Remove(rotateName) os.Remove(rotateName)
os.Remove("test3.log") os.Remove("test3.log")
t.Fatal("rotate file mode error") t.Fatal("rotate file mode error")
@ -369,6 +370,7 @@ func testFileHourlyRotate(t *testing.T, fn1, fn2 string) {
} }
fw.Destroy() fw.Destroy()
} }
func exists(path string) (bool, error) { func exists(path string) (bool, error) {
_, err := os.Stat(path) _, err := os.Stat(path)
if err == nil { if err == nil {

View File

@ -31,7 +31,6 @@ func newJLWriter() Logger {
// Init JLWriter with json config string // Init JLWriter with json config string
func (s *JLWriter) Init(config string) error { func (s *JLWriter) Init(config string) error {
res := json.Unmarshal([]byte(config), s) res := json.Unmarshal([]byte(config), s)
if res == nil && len(s.Formatter) > 0 { if res == nil && len(s.Formatter) > 0 {
fmtr, ok := GetFormatter(s.Formatter) fmtr, ok := GetFormatter(s.Formatter)

View File

@ -92,8 +92,10 @@ type Logger interface {
SetFormatter(f LogFormatter) SetFormatter(f LogFormatter)
} }
var adapters = make(map[string]newLoggerFunc) var (
var levelPrefix = [LevelDebug + 1]string{"[M]", "[A]", "[C]", "[E]", "[W]", "[N]", "[I]", "[D]"} 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. // Register makes a log provide available by the provided name.
// If Register is called twice with the same name or if driver is nil, // 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) err := lg.Init(config)
if err != nil { if err != nil {
fmt.Fprintln(os.Stderr, "logs.BeeLogger.SetLogger: "+err.Error()) fmt.Fprintln(os.Stderr, "logs.BeeLogger.SetLogger: "+err.Error())
return err return err

View File

@ -112,8 +112,10 @@ var (
reset = string([]byte{27, 91, 48, 109}) reset = string([]byte{27, 91, 48, 109})
) )
var once sync.Once var (
var colorMap map[string]string once sync.Once
colorMap map[string]string
)
func initColor() { func initColor() {
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {

View File

@ -45,7 +45,6 @@ var levelNames = [...]string{"emergency", "alert", "critical", "error", "warning
// } // }
func (f *multiFileLogWriter) Init(config string) error { func (f *multiFileLogWriter) Init(config string) error {
writer := newFileWriter().(*fileLogWriter) writer := newFileWriter().(*fileLogWriter)
err := writer.Init(config) err := writer.Init(config)
if err != nil { if err != nil {

View File

@ -60,7 +60,7 @@ func TestFiles_1(t *testing.T) {
lineNum++ lineNum++
} }
} }
var expected = 1 expected := 1
if fn == "" { if fn == "" {
expected = LevelDebug + 1 expected = LevelDebug + 1
} }
@ -74,5 +74,4 @@ func TestFiles_1(t *testing.T) {
} }
os.Remove(file) os.Remove(file)
} }
} }

View File

@ -47,20 +47,20 @@ func GetDisplayString(data ...interface{}) string {
} }
func display(displayed bool, 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 { if !ok {
return "" 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, "[Debug] at %s() [%s:%d]\n", function(pc), file, line)
fmt.Fprintf(buf, "\n[Variables]\n") fmt.Fprintf(buf, "\n[Variables]\n")
for i := 0; i < len(data); i += 2 { 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) 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 // return data dump and format bytes
func fomateinfo(headlen int, data ...interface{}) []byte { func fomateinfo(headlen int, data ...interface{}) []byte {
var buf = new(bytes.Buffer) buf := new(bytes.Buffer)
if len(data) > 1 { if len(data) > 1 {
fmt.Fprint(buf, " ") fmt.Fprint(buf, " ")
@ -83,9 +83,9 @@ func fomateinfo(headlen int, data ...interface{}) []byte {
} }
for k, v := range data { for k, v := range data {
var buf2 = new(bytes.Buffer) buf2 := new(bytes.Buffer)
var pointers *pointerInfo 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) 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 return true
} }
var elem = val.Elem() elem := val.Elem()
if isSimpleType(elem, elem.Kind(), pointers, interfaces) { if isSimpleType(elem, elem.Kind(), pointers, interfaces) {
return true return true
} }
var addr = val.Elem().UnsafeAddr() addr := val.Elem().UnsafeAddr()
for p := *pointers; p != nil; p = p.prev { for p := *pointers; p != nil; p = p.prev {
if addr == p.addr { if addr == p.addr {
@ -162,7 +162,7 @@ func isSimpleType(val reflect.Value, kind reflect.Kind, pointers **pointerInfo,
// dump value // 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) { 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 { switch t {
case reflect.Bool: case reflect.Bool:
@ -183,7 +183,7 @@ func printKeyValue(buf *bytes.Buffer, val reflect.Value, pointers **pointerInfo,
return return
} }
var addr = val.Elem().UnsafeAddr() addr := val.Elem().UnsafeAddr()
for p := *pointers; p != nil; p = p.prev { for p := *pointers; p != nil; p = p.prev {
if addr == p.addr { if addr == p.addr {
@ -206,7 +206,7 @@ func printKeyValue(buf *bytes.Buffer, val reflect.Value, pointers **pointerInfo,
case reflect.String: case reflect.String:
fmt.Fprint(buf, "\"", val.String(), "\"") fmt.Fprint(buf, "\"", val.String(), "\"")
case reflect.Interface: case reflect.Interface:
var value = val.Elem() value := val.Elem()
if !value.IsValid() { if !value.IsValid() {
fmt.Fprint(buf, "nil") 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) printKeyValue(buf, value, pointers, interfaces, structFilter, formatOutput, indent, level+1)
} }
case reflect.Struct: case reflect.Struct:
var t = val.Type() t := val.Type()
fmt.Fprint(buf, t) fmt.Fprint(buf, t)
fmt.Fprint(buf, "{") fmt.Fprint(buf, "{")
@ -235,7 +235,7 @@ func printKeyValue(buf *bytes.Buffer, val reflect.Value, pointers **pointerInfo,
fmt.Fprint(buf, " ") fmt.Fprint(buf, " ")
} }
var name = t.Field(i).Name name := t.Field(i).Name
if formatOutput { if formatOutput {
for ind := 0; ind < level; ind++ { 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, val.Type())
fmt.Fprint(buf, "{") fmt.Fprint(buf, "{")
var allSimple = true allSimple := true
for i := 0; i < val.Len(); i++ { 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 { if !isSimple {
allSimple = false allSimple = false
@ -312,18 +312,18 @@ func printKeyValue(buf *bytes.Buffer, val reflect.Value, pointers **pointerInfo,
fmt.Fprint(buf, "}") fmt.Fprint(buf, "}")
case reflect.Map: case reflect.Map:
var t = val.Type() t := val.Type()
var keys = val.MapKeys() keys := val.MapKeys()
fmt.Fprint(buf, t) fmt.Fprint(buf, t)
fmt.Fprint(buf, "{") fmt.Fprint(buf, "{")
var allSimple = true allSimple := true
for i := 0; i < len(keys); i++ { 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 { if !isSimple {
allSimple = false allSimple = false
@ -372,8 +372,8 @@ func printKeyValue(buf *bytes.Buffer, val reflect.Value, pointers **pointerInfo,
// PrintPointerInfo dump pointer value // PrintPointerInfo dump pointer value
func PrintPointerInfo(buf *bytes.Buffer, headlen int, pointers *pointerInfo) { func PrintPointerInfo(buf *bytes.Buffer, headlen int, pointers *pointerInfo) {
var anyused = false anyused := false
var pointerNum = 0 pointerNum := 0
for p := pointers; p != nil; p = p.prev { for p := pointers; p != nil; p = p.prev {
if len(p.used) > 0 { if len(p.used) > 0 {
@ -384,10 +384,10 @@ func PrintPointerInfo(buf *bytes.Buffer, headlen int, pointers *pointerInfo) {
} }
if anyused { if anyused {
var pointerBufs = make([][]rune, pointerNum+1) pointerBufs := make([][]rune, pointerNum+1)
for i := 0; i < len(pointerBufs); i++ { 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++ { for j := 0; j < len(pointerBuf); j++ {
pointerBuf[j] = ' ' pointerBuf[j] = ' '
@ -402,7 +402,7 @@ func PrintPointerInfo(buf *bytes.Buffer, headlen int, pointers *pointerInfo) {
if pn == p.n { if pn == p.n {
pointerBufs[pn][p.pos+headlen] = '└' pointerBufs[pn][p.pos+headlen] = '└'
var maxpos = 0 maxpos := 0
for i, pos := range p.used { for i, pos := range p.used {
if i < len(p.used)-1 { if i < len(p.used)-1 {
@ -440,10 +440,10 @@ func PrintPointerInfo(buf *bytes.Buffer, headlen int, pointers *pointerInfo) {
// Stack get stack bytes // Stack get stack bytes
func Stack(skip int, indent string) []byte { func Stack(skip int, indent string) []byte {
var buf = new(bytes.Buffer) buf := new(bytes.Buffer)
for i := skip; ; i++ { for i := skip; ; i++ {
var pc, file, line, ok = runtime.Caller(i) pc, file, line, ok := runtime.Caller(i)
if !ok { if !ok {
break break

View File

@ -28,8 +28,8 @@ func TestPrint(t *testing.T) {
} }
func TestPrintPoint(t *testing.T) { func TestPrintPoint(t *testing.T) {
var v1 = new(mytype) v1 := new(mytype)
var v2 = new(mytype) v2 := new(mytype)
v1.prev = nil v1.prev = nil
v1.next = v2 v1.next = v2

View File

@ -34,5 +34,4 @@ func TestKVs(t *testing.T) {
v = kvs.GetValueOr(`key-not-exists`, 8546) v = kvs.GetValueOr(`key-not-exists`, 8546)
assert.Equal(t, 8546, v) assert.Equal(t, 8546, v)
} }

View File

@ -27,7 +27,7 @@ func RandomCreateBytes(n int, alphabets ...byte) []byte {
if len(alphabets) == 0 { if len(alphabets) == 0 {
alphabets = alphaNum alphabets = alphaNum
} }
var bytes = make([]byte, n) bytes := make([]byte, n)
var randBy bool var randBy bool
if num, err := rand.Read(bytes); num != n || err != nil { if num, err := rand.Read(bytes); num != n || err != nil {
r.Seed(time.Now().UnixNano()) r.Seed(time.Now().UnixNano())

View File

@ -18,8 +18,7 @@ import (
"sync" "sync"
) )
// deprecated
//deprecated
type BeeMap struct { type BeeMap struct {
lock *sync.RWMutex lock *sync.RWMutex
bm map[interface{}]interface{} bm map[interface{}]interface{}

View File

@ -20,6 +20,7 @@ import (
) )
type reducetype func(interface{}) interface{} type reducetype func(interface{}) interface{}
type filtertype func(interface{}) bool type filtertype func(interface{}) bool
// InSlice checks given string in string slice or not. // InSlice checks given string in string slice or not.

View File

@ -21,7 +21,6 @@ import (
// short string format // short string format
func ToShortTimeFormat(d time.Duration) string { func ToShortTimeFormat(d time.Duration) string {
u := uint64(d) u := uint64(d)
if u < uint64(time.Second) { if u < uint64(time.Second) {
switch { switch {
@ -44,5 +43,4 @@ func ToShortTimeFormat(d time.Duration) string {
return fmt.Sprintf("%.2fh", float64(u)/1000/1000/1000/60/60) return fmt.Sprintf("%.2fh", float64(u)/1000/1000/1000/60/60)
} }
} }
} }

View File

@ -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 // Phone Test that the obj is chinese mobile or telephone number if type is string
func (v *Validation) Phone(obj interface{}, key string) *Result { func (v *Validation) Phone(obj interface{}, key string) *Result {
return v.apply(Phone{Mobile{Match: Match{Regexp: mobilePattern}}, return v.apply(Phone{
Tel{Match: Match{Regexp: telPattern}}, key}, obj) 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 // ZipCode Test that the obj is chinese zip code if type is string

View File

@ -605,7 +605,6 @@ func TestCanSkipAlso(t *testing.T) {
if !b { if !b {
t.Fatal("validation should be passed") t.Fatal("validation should be passed")
} }
} }
func TestFieldNoEmpty(t *testing.T) { func TestFieldNoEmpty(t *testing.T) {