From b849cfc18cc70268360e7b99e40f5ea43e695209 Mon Sep 17 00:00:00 2001 From: shubhendra Date: Thu, 25 Feb 2021 15:58:42 +0530 Subject: [PATCH 1/6] Fix unnecessary allocations due to `Index` calls --- .deepsource.toml | 12 ++++++++++++ adapter/httplib/httplib_test.go | 9 +++++---- client/httplib/httplib_test.go | 5 +++-- 3 files changed, 20 insertions(+), 6 deletions(-) create mode 100644 .deepsource.toml diff --git a/.deepsource.toml b/.deepsource.toml new file mode 100644 index 00000000..7901d2d2 --- /dev/null +++ b/.deepsource.toml @@ -0,0 +1,12 @@ +version = 1 + +test_patterns = ["**/*_test.go"] + +exclude_patterns = ["scripts/**"] + +[[analyzers]] +name = "go" +enabled = true + + [analyzers.meta] + import_paths = ["github.com/beego/beego"] diff --git a/adapter/httplib/httplib_test.go b/adapter/httplib/httplib_test.go index 350f716e..298d84f9 100644 --- a/adapter/httplib/httplib_test.go +++ b/adapter/httplib/httplib_test.go @@ -15,6 +15,7 @@ package httplib import ( + "bytes" "errors" "io/ioutil" "net" @@ -66,7 +67,7 @@ func TestDoRequest(t *testing.T) { } func TestGet(t *testing.T) { - + req := Get(getUrl) b, err := req.Bytes() if err != nil { @@ -222,7 +223,7 @@ func TestWithSetting(t *testing.T) { } func TestToJson(t *testing.T) { - + req := Get(ipUrl) resp, err := req.Response() if err != nil { @@ -261,7 +262,7 @@ func TestToFile(t *testing.T) { } defer os.Remove(f) b, err := ioutil.ReadFile(f) - if n := strings.Index(string(b), "origin"); n == -1 { + if n := bytes.Index(b, []byte("origin")); n == -1 { t.Fatal(err) } } @@ -275,7 +276,7 @@ func TestToFileDir(t *testing.T) { } defer os.RemoveAll("./files") b, err := ioutil.ReadFile(f) - if n := strings.Index(string(b), "origin"); n == -1 { + if n := bytes.Index(b, []byte("origin")); n == -1 { t.Fatal(err) } } diff --git a/client/httplib/httplib_test.go b/client/httplib/httplib_test.go index 1fde708a..9133ad5f 100644 --- a/client/httplib/httplib_test.go +++ b/client/httplib/httplib_test.go @@ -15,6 +15,7 @@ package httplib import ( + "bytes" "context" "errors" "io/ioutil" @@ -259,7 +260,7 @@ func TestToFile(t *testing.T) { } defer os.Remove(f) b, err := ioutil.ReadFile(f) - if n := strings.Index(string(b), "origin"); n == -1 { + if n := bytes.Index(b, []byte("origin")); n == -1 { t.Fatal(err) } } @@ -273,7 +274,7 @@ func TestToFileDir(t *testing.T) { } defer os.RemoveAll("./files") b, err := ioutil.ReadFile(f) - if n := strings.Index(string(b), "origin"); n == -1 { + if n := bytes.Index(b, []byte("origin")); n == -1 { t.Fatal(err) } } From ec0e382e11b07335eb0e05fc9f44c266110f8d94 Mon Sep 17 00:00:00 2001 From: shubhendra Date: Thu, 25 Feb 2021 15:58:43 +0530 Subject: [PATCH 2/6] Fix inefficient string comparison --- server/web/filter/cors/cors.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/web/filter/cors/cors.go b/server/web/filter/cors/cors.go index c5d28819..fd7d444b 100644 --- a/server/web/filter/cors/cors.go +++ b/server/web/filter/cors/cors.go @@ -143,7 +143,7 @@ func (o *Options) PreflightHeader(origin, rMethod, rHeaders string) (headers map rHeader = strings.TrimSpace(rHeader) lookupLoop: for _, allowedHeader := range o.AllowHeaders { - if strings.ToLower(rHeader) == strings.ToLower(allowedHeader) { + if strings.EqualFold(rHeader, allowedHeader) { allowed = append(allowed, rHeader) break lookupLoop } From 9a17c76718727732c592398fce560241d97d87df Mon Sep 17 00:00:00 2001 From: shubhendra Date: Thu, 25 Feb 2021 15:58:43 +0530 Subject: [PATCH 3/6] Remove unnecessary wrapping of function call --- server/web/session/sess_file.go | 4 +--- server/web/template.go | 4 +--- test/bindata.go | 4 +--- 3 files changed, 3 insertions(+), 9 deletions(-) diff --git a/server/web/session/sess_file.go b/server/web/session/sess_file.go index 90de9a79..a96bacb8 100644 --- a/server/web/session/sess_file.go +++ b/server/web/session/sess_file.go @@ -211,9 +211,7 @@ func (fp *FileProvider) SessionGC(context.Context) { // it walks save path to count files. func (fp *FileProvider) SessionAll(context.Context) int { a := &activeSession{} - err := filepath.Walk(fp.savePath, func(path string, f os.FileInfo, err error) error { - return a.visit(path, f, err) - }) + err := filepath.Walk(fp.savePath, a.visit) if err != nil { SLogger.Printf("filepath.Walk() returned %v\n", err) return 0 diff --git a/server/web/template.go b/server/web/template.go index 65935ca8..78ea958a 100644 --- a/server/web/template.go +++ b/server/web/template.go @@ -202,9 +202,7 @@ func BuildTemplate(dir string, files ...string) error { root: dir, files: make(map[string][]string), } - err = Walk(fs, dir, func(path string, f os.FileInfo, err error) error { - return self.visit(path, f, err) - }) + err = Walk(fs, dir, self.visit) if err != nil { fmt.Printf("Walk() returned %v\n", err) return err diff --git a/test/bindata.go b/test/bindata.go index 6dbc08ab..120d327c 100644 --- a/test/bindata.go +++ b/test/bindata.go @@ -287,9 +287,7 @@ func _filePath(dir, name string) string { } func assetFS() *assetfs.AssetFS { - assetInfo := func(path string) (os.FileInfo, error) { - return os.Stat(path) - } + assetInfo := os.Stat for k := range _bintree.Children { return &assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, AssetInfo: assetInfo, Prefix: k} } From 512133e14be8089150622cb540c14f8d7f13bc5a Mon Sep 17 00:00:00 2001 From: shubhendra Date: Thu, 25 Feb 2021 15:58:44 +0530 Subject: [PATCH 4/6] Remove unnecessary use of slice --- adapter/orm/utils.go | 6 +++--- client/orm/utils.go | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/adapter/orm/utils.go b/adapter/orm/utils.go index 22bf8d63..cd54f867 100644 --- a/adapter/orm/utils.go +++ b/adapter/orm/utils.go @@ -195,7 +195,7 @@ func snakeStringWithAcronym(s string) string { } data = append(data, d) } - return strings.ToLower(string(data[:])) + return strings.ToLower(string(data)) } // snake string, XxYy to xx_yy , XxYY to xx_y_y @@ -213,7 +213,7 @@ func snakeString(s string) string { } data = append(data, d) } - return strings.ToLower(string(data[:])) + return strings.ToLower(string(data)) } // SetNameStrategy set different name strategy @@ -241,7 +241,7 @@ func camelString(s string) string { } data = append(data, d) } - return string(data[:]) + return string(data) } type argString []string diff --git a/client/orm/utils.go b/client/orm/utils.go index d6c0a8e8..8d05c080 100644 --- a/client/orm/utils.go +++ b/client/orm/utils.go @@ -228,7 +228,7 @@ func snakeStringWithAcronym(s string) string { } data = append(data, d) } - return strings.ToLower(string(data[:])) + return strings.ToLower(string(data)) } // snake string, XxYy to xx_yy , XxYY to xx_y_y @@ -246,7 +246,7 @@ func snakeString(s string) string { } data = append(data, d) } - return strings.ToLower(string(data[:])) + return strings.ToLower(string(data)) } // SetNameStrategy set different name strategy @@ -274,7 +274,7 @@ func camelString(s string) string { } data = append(data, d) } - return string(data[:]) + return string(data) } type argString []string From 644291c028cd8df27d63644c3bc939f117d4afcf Mon Sep 17 00:00:00 2001 From: shubhendra Date: Thu, 25 Feb 2021 15:58:45 +0530 Subject: [PATCH 5/6] Replace `time.Now().Sub` with `time.Since` --- .deepsource.toml | 12 ------------ client/cache/memory.go | 4 ++-- client/orm/filter/prometheus/filter.go | 2 +- client/orm/orm_log.go | 2 +- core/admin/profile.go | 4 ++-- 5 files changed, 6 insertions(+), 18 deletions(-) delete mode 100644 .deepsource.toml diff --git a/.deepsource.toml b/.deepsource.toml deleted file mode 100644 index 7901d2d2..00000000 --- a/.deepsource.toml +++ /dev/null @@ -1,12 +0,0 @@ -version = 1 - -test_patterns = ["**/*_test.go"] - -exclude_patterns = ["scripts/**"] - -[[analyzers]] -name = "go" -enabled = true - - [analyzers.meta] - import_paths = ["github.com/beego/beego"] diff --git a/client/cache/memory.go b/client/cache/memory.go index e4b704c9..f294595d 100644 --- a/client/cache/memory.go +++ b/client/cache/memory.go @@ -42,7 +42,7 @@ func (mi *MemoryItem) isExpire() bool { if mi.lifespan == 0 { return false } - return time.Now().Sub(mi.createdTime) > mi.lifespan + return time.Since(mi.createdTime) > mi.lifespan } // MemoryCache is a memory cache adapter. @@ -66,7 +66,7 @@ func (bc *MemoryCache) Get(ctx context.Context, key string) (interface{}, error) bc.RLock() defer bc.RUnlock() if itm, ok := - bc.items[key]; ok { + bc.items[key]; ok { if itm.isExpire() { return nil, ErrKeyExpired } diff --git a/client/orm/filter/prometheus/filter.go b/client/orm/filter/prometheus/filter.go index 270deaf6..b2c83dcf 100644 --- a/client/orm/filter/prometheus/filter.go +++ b/client/orm/filter/prometheus/filter.go @@ -85,7 +85,7 @@ func (builder *FilterChainBuilder) report(ctx context.Context, inv *orm.Invocati } func (builder *FilterChainBuilder) reportTxn(ctx context.Context, inv *orm.Invocation) { - dur := time.Now().Sub(inv.TxStartTime) / time.Millisecond + dur := time.Since(inv.TxStartTime) / time.Millisecond summaryVec.WithLabelValues(inv.Method, inv.TxName, strconv.FormatBool(inv.InsideTx), inv.TxName).Observe(float64(dur)) } diff --git a/client/orm/orm_log.go b/client/orm/orm_log.go index 8ac373b5..6a89f557 100644 --- a/client/orm/orm_log.go +++ b/client/orm/orm_log.go @@ -41,7 +41,7 @@ func NewLog(out io.Writer) *Log { func debugLogQueies(alias *alias, operaton, query string, t time.Time, err error, args ...interface{}) { var logMap = make(map[string]interface{}) - sub := time.Now().Sub(t) / 1e5 + sub := time.Since(t) / 1e5 elsp := float64(int(sub)) / 10.0 logMap["cost_time"] = elsp flag := " OK" diff --git a/core/admin/profile.go b/core/admin/profile.go index 5b3fdb21..6162a2d4 100644 --- a/core/admin/profile.go +++ b/core/admin/profile.go @@ -108,7 +108,7 @@ func printGC(memStats *runtime.MemStats, gcstats *debug.GCStats, w io.Writer) { if gcstats.NumGC > 0 { lastPause := gcstats.Pause[0] - elapsed := time.Now().Sub(startTime) + elapsed := time.Since(startTime) overhead := float64(gcstats.PauseTotal) / float64(elapsed) * 100 allocatedRate := float64(memStats.TotalAlloc) / elapsed.Seconds() @@ -125,7 +125,7 @@ func printGC(memStats *runtime.MemStats, gcstats *debug.GCStats, w io.Writer) { utils.ToShortTimeFormat(gcstats.PauseQuantiles[99])) } else { // while GC has disabled - elapsed := time.Now().Sub(startTime) + elapsed := time.Since(startTime) allocatedRate := float64(memStats.TotalAlloc) / elapsed.Seconds() fmt.Fprintf(w, "Alloc:%s Sys:%s Alloc(Rate):%s/s\n", From b25bd7bc4c4d236233be42be48f38f354c71b19b Mon Sep 17 00:00:00 2001 From: Shubhendra Singh Chauhan Date: Thu, 25 Feb 2021 16:06:06 +0530 Subject: [PATCH 6/6] Update CHANGELOG.md --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9af933de..41f8757f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,9 +23,10 @@ - Fix 4451: support QueryExecutor interface. [4461](https://github.com/beego/beego/pull/4461) - Add some testing scripts [4461](https://github.com/beego/beego/pull/4461) - Refactor httplib: Move debug code to a filter [4440](https://github.com/beego/beego/issues/4440) +- fix: code quality issues [4513](https://github.com/beego/beego/pull/4513) ## Fix Sonar - [4473](https://github.com/beego/beego/pull/4473) - [4474](https://github.com/beego/beego/pull/4474) -- [4479](https://github.com/beego/beego/pull/4479) \ No newline at end of file +- [4479](https://github.com/beego/beego/pull/4479)