From 1f9d86f0151d13925517388de1461e7b6477f15e Mon Sep 17 00:00:00 2001 From: John Guo Date: Mon, 14 Feb 2022 11:46:20 +0800 Subject: [PATCH 1/8] improve configuration read from package frame/gins --- database/gredis/gredis.go | 20 +++---- frame/gins/gins_database.go | 13 ++--- frame/gins/gins_httpclient.go | 4 +- frame/gins/gins_redis.go | 48 ++++++++-------- frame/gins/gins_server.go | 103 +++++++++++++++++++--------------- frame/gins/gins_view.go | 40 ++++++------- os/gcfg/gcfg_adapter_file.go | 28 +++++---- 7 files changed, 128 insertions(+), 128 deletions(-) diff --git a/database/gredis/gredis.go b/database/gredis/gredis.go index ee693bc6b..0d510c6ca 100644 --- a/database/gredis/gredis.go +++ b/database/gredis/gredis.go @@ -13,25 +13,19 @@ // Redis Chinese Documentation: http://redisdoc.com/ package gredis -import ( - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" -) - // New creates and returns a redis client. // It creates a default redis adapter of go-redis. func New(config ...*Config) (*Redis, error) { - if len(config) > 0 { + if len(config) > 0 && config[0] != nil { + // Redis client with go redis implements adapter from given configuration. return &Redis{adapter: NewAdapterGoRedis(config[0])}, nil } - configFromGlobal, ok := GetConfig() - if !ok { - return nil, gerror.NewCode( - gcode.CodeMissingConfiguration, - `configuration not found for creating Redis client`, - ) + // Redis client with go redis implements adapter from package configuration. + if configFromGlobal, ok := GetConfig(); ok { + return &Redis{adapter: NewAdapterGoRedis(configFromGlobal)}, nil } - return &Redis{adapter: NewAdapterGoRedis(configFromGlobal)}, nil + // Redis client with empty adapter. + return &Redis{}, nil } // NewWithAdapter creates and returns a redis client with given adapter. diff --git a/frame/gins/gins_database.go b/frame/gins/gins_database.go index b50eadd0c..67e90bea8 100644 --- a/frame/gins/gins_database.go +++ b/frame/gins/gins_database.go @@ -180,19 +180,18 @@ func parseDBConfigNode(value interface{}) *gdb.ConfigNode { if !ok { return nil } - node := &gdb.ConfigNode{} - err := gconv.Struct(nodeMap, node) + var ( + node = &gdb.ConfigNode{} + err = gconv.Struct(nodeMap, node) + ) if err != nil { panic(err) } - // Be compatible with old version. - if _, v := gutil.MapPossibleItemByKey(nodeMap, "LinkInfo"); v != nil { - node.Link = gconv.String(v) - } + // Find possible `Link` configuration content. if _, v := gutil.MapPossibleItemByKey(nodeMap, "Link"); v != nil { node.Link = gconv.String(v) } - // Parse link syntax. + // Parse `Link` configuration syntax. if node.Link != "" && node.Type == "" { match, _ := gregex.MatchString(`([a-z]+):(.+)`, node.Link) if len(match) == 3 { diff --git a/frame/gins/gins_httpclient.go b/frame/gins/gins_httpclient.go index 26f784c5b..324307d39 100644 --- a/frame/gins/gins_httpclient.go +++ b/frame/gins/gins_httpclient.go @@ -18,9 +18,7 @@ const ( // HttpClient returns an instance of http client with specified name. func HttpClient(name ...interface{}) *gclient.Client { - var ( - instanceKey = fmt.Sprintf("%s.%v", frameCoreComponentNameHttpClient, name) - ) + var instanceKey = fmt.Sprintf("%s.%v", frameCoreComponentNameHttpClient, name) return localInstances.GetOrSetFuncLock(instanceKey, func() interface{} { return gclient.New() }).(*gclient.Client) diff --git a/frame/gins/gins_redis.go b/frame/gins/gins_redis.go index 7c2ccca39..5723b5c88 100644 --- a/frame/gins/gins_redis.go +++ b/frame/gins/gins_redis.go @@ -11,7 +11,7 @@ import ( "fmt" "github.com/gogf/gf/v2/database/gredis" - "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/gutil" ) @@ -25,6 +25,7 @@ const ( // Note that it panics if any error occurs duration instance creating. func Redis(name ...string) *gredis.Redis { var ( + err error ctx = context.Background() group = gredis.DefaultGroupName ) @@ -37,35 +38,32 @@ func Redis(name ...string) *gredis.Redis { if _, ok := gredis.GetConfig(group); ok { return gredis.Instance(group) } - // Or else, it parses the default configuration file and returns a new redis instance. - var ( - configMap map[string]interface{} - ) - - if configData, err := Config().Data(ctx); err != nil { - panic(gerror.Wrap(err, `retrieving redis configuration failed`)) - } else { - if _, v := gutil.MapPossibleItemByKey(configData, configNodeNameRedis); v != nil { + if Config().Available(ctx) { + var ( + configMap map[string]interface{} + redisConfig *gredis.Config + redisClient *gredis.Redis + ) + if configMap, err = Config().Data(ctx); err != nil { + intlog.Errorf(ctx, `retrieve config data map failed: %+v`, err) + } + if _, v := gutil.MapPossibleItemByKey(configMap, configNodeNameRedis); v != nil { configMap = gconv.Map(v) } - } - - if len(configMap) > 0 { - if v, ok := configMap[group]; ok { - redisConfig, err := gredis.ConfigFromMap(gconv.Map(v)) - if err != nil { - panic(err) + if len(configMap) > 0 { + if v, ok := configMap[group]; ok { + if redisConfig, err = gredis.ConfigFromMap(gconv.Map(v)); err != nil { + panic(err) + } } - redisClient, err := gredis.New(redisConfig) - if err != nil { - panic(err) - } - return redisClient + intlog.Printf(ctx, `missing configuration for redis group "%s"`, group) } else { - panic(fmt.Sprintf(`missing configuration for redis group "%s"`, group)) + intlog.Printf(ctx, `missing configuration for redis: "redis" node not found`) } - } else { - panic(`missing configuration for redis: "redis" node not found`) + if redisClient, err = gredis.New(redisConfig); err != nil { + panic(err) + } + return redisClient } return nil }) diff --git a/frame/gins/gins_server.go b/frame/gins/gins_server.go index 6580b25fc..2455d7925 100644 --- a/frame/gins/gins_server.go +++ b/frame/gins/gins_server.go @@ -17,15 +17,16 @@ import ( ) const ( - frameCoreComponentNameServer = "gf.core.component.server" - configNodeNameServer = "server" - configNodeNameServerSecondary = "httpserver" + frameCoreComponentNameServer = "gf.core.component.server" // Prefix for HTTP server instance. + configNodeNameServer = "server" // General version configuration item name. + configNodeNameServerSecondary = "httpserver" // New version configuration item name support from v2. ) // Server returns an instance of http server with specified name. // Note that it panics if any error occurs duration instance creating. func Server(name ...interface{}) *ghttp.Server { var ( + err error ctx = context.Background() instanceName = ghttp.DefaultServerName instanceKey = fmt.Sprintf("%s.%v", frameCoreComponentNameServer, name) @@ -34,57 +35,67 @@ func Server(name ...interface{}) *ghttp.Server { instanceName = gconv.String(name[0]) } return localInstances.GetOrSetFuncLock(instanceKey, func() interface{} { - s := ghttp.GetServer(instanceName) - // It ignores returned error to avoid file no found error while it's not necessary. - var ( - serverConfigMap map[string]interface{} - serverLoggerConfigMap map[string]interface{} - configNodeName string - ) - if configData, _ := Config().Data(ctx); len(configData) > 0 { - if v, _ := gutil.MapPossibleItemByKey(configData, configNodeNameServer); v != "" { - configNodeName = v + server := ghttp.GetServer(instanceName) + if Config().Available(ctx) { + // Server initialization from configuration. + var ( + configMap map[string]interface{} + serverConfigMap map[string]interface{} + serverLoggerConfigMap map[string]interface{} + configNodeName string + ) + if configMap, err = Config().Data(ctx); err != nil { + intlog.Errorf(ctx, `retrieve config data map failed: %+v`, err) } - if configNodeName == "" { - if v, _ := gutil.MapPossibleItemByKey(configData, configNodeNameServerSecondary); v != "" { + // Find possible server configuration item by possible names. + if len(configMap) > 0 { + if v, _ := gutil.MapPossibleItemByKey(configMap, configNodeNameServer); v != "" { configNodeName = v } + if configNodeName == "" { + if v, _ := gutil.MapPossibleItemByKey(configMap, configNodeNameServerSecondary); v != "" { + configNodeName = v + } + } + } + // Server configuration. + serverConfigMap = Config().MustGet( + ctx, + fmt.Sprintf(`%s.%s`, configNodeName, server.GetName()), + ).Map() + if len(serverConfigMap) == 0 { + serverConfigMap = Config().MustGet(ctx, configNodeName).Map() + } + if len(serverConfigMap) > 0 { + if err = server.SetConfigWithMap(serverConfigMap); err != nil { + panic(err) + } + } else { + // The configuration is not necessary, so it just prints internal logs. + intlog.Printf( + ctx, + `missing configuration from configuration component for HTTP server "%s"`, + instanceName, + ) + } + // Server logger configuration checks. + serverLoggerConfigMap = Config().MustGet( + ctx, + fmt.Sprintf(`%s.%s.%s`, configNodeName, server.GetName(), configNodeNameLogger), + ).Map() + if len(serverLoggerConfigMap) > 0 { + if err = server.Logger().SetConfigWithMap(serverLoggerConfigMap); err != nil { + panic(err) + } } } - // Server configuration. - certainConfigNodeName := fmt.Sprintf(`%s.%s`, configNodeName, s.GetName()) - if v, _ := Config().Get(ctx, certainConfigNodeName); !v.IsEmpty() { - serverConfigMap = v.Map() - } - if len(serverConfigMap) == 0 { - if v, _ := Config().Get(ctx, configNodeName); !v.IsEmpty() { - serverConfigMap = v.Map() - } - } - if len(serverConfigMap) > 0 { - if err := s.SetConfigWithMap(serverConfigMap); err != nil { - panic(err) - } - } else { - // The configuration is not necessary, so it just prints internal logs. - intlog.Printf(ctx, `missing configuration from configuration component for HTTP server "%s"`, instanceName) - } - if s.GetName() == "" || s.GetName() == ghttp.DefaultServerName { - s.SetName(instanceName) - } - // Server logger configuration checks. - serverLoggerNodeName := fmt.Sprintf(`%s.%s.%s`, configNodeName, s.GetName(), configNodeNameLogger) - if v, _ := Config().Get(ctx, serverLoggerNodeName); !v.IsEmpty() { - serverLoggerConfigMap = v.Map() - } - if len(serverLoggerConfigMap) > 0 { - if err := s.Logger().SetConfigWithMap(serverLoggerConfigMap); err != nil { - panic(err) - } + // The server name is necessary. It sets a default server name is it is not configured. + if server.GetName() == "" || server.GetName() == ghttp.DefaultServerName { + server.SetName(instanceName) } // As it might use template feature, // it initializes the view instance as well. _ = getViewInstance() - return s + return server }).(*ghttp.Server) } diff --git a/frame/gins/gins_view.go b/frame/gins/gins_view.go index b9e3b0e6a..953d39ff1 100644 --- a/frame/gins/gins_view.go +++ b/frame/gins/gins_view.go @@ -10,6 +10,7 @@ import ( "context" "fmt" + "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/os/gview" "github.com/gogf/gf/v2/util/gutil" ) @@ -35,6 +36,7 @@ func View(name ...string) *gview.View { func getViewInstance(name ...string) *gview.View { var ( + err error ctx = context.Background() instanceName = gview.DefaultName ) @@ -42,27 +44,27 @@ func getViewInstance(name ...string) *gview.View { instanceName = name[0] } view := gview.Instance(instanceName) - // To avoid file no found error while it's not necessary. - var ( - configMap map[string]interface{} - configNodeName = configNodeNameViewer - ) - if configData, _ := Config().Data(ctx); len(configData) > 0 { - if v, _ := gutil.MapPossibleItemByKey(configData, configNodeNameViewer); v != "" { - configNodeName = v + if Config().Available(ctx) { + var ( + configMap map[string]interface{} + configNodeName = configNodeNameViewer + ) + if configMap, err = Config().Data(ctx); err != nil { + intlog.Errorf(ctx, `retrieve config data map failed: %+v`, err) } - } - if v, _ := Config().Get(ctx, fmt.Sprintf(`%s.%s`, configNodeName, instanceName)); !v.IsEmpty() { - configMap = v.Map() - } - if len(configMap) == 0 { - if v, _ := Config().Get(ctx, configNodeName); !v.IsEmpty() { - configMap = v.Map() + if len(configMap) > 0 { + if v, _ := gutil.MapPossibleItemByKey(configMap, configNodeNameViewer); v != "" { + configNodeName = v + } } - } - if len(configMap) > 0 { - if err := view.SetConfigWithMap(configMap); err != nil { - panic(err) + configMap = Config().MustGet(ctx, fmt.Sprintf(`%s.%s`, configNodeName, instanceName)).Map() + if len(configMap) == 0 { + configMap = Config().MustGet(ctx, configNodeName).Map() + } + if len(configMap) > 0 { + if err = view.SetConfigWithMap(configMap); err != nil { + panic(err) + } } } return view diff --git a/os/gcfg/gcfg_adapter_file.go b/os/gcfg/gcfg_adapter_file.go index bede90555..80ea4c4c7 100644 --- a/os/gcfg/gcfg_adapter_file.go +++ b/os/gcfg/gcfg_adapter_file.go @@ -253,28 +253,26 @@ func (c *AdapterFile) getJson(fileName ...string) (configJson *gjson.Json, err e } else { configJson, err = gjson.LoadContent(content, true) } - if err == nil { - configJson.SetViolenceCheck(c.violenceCheck) - // Add monitor for this configuration file, - // any changes of this file will refresh its cache in Config object. - if filePath != "" && !gres.Contains(filePath) { - _, err = gfsnotify.Add(filePath, func(event *gfsnotify.Event) { - c.jsonMap.Remove(usedFileName) - }) - if err != nil { - return nil - } - } - return configJson - } if err != nil { if filePath != "" { err = gerror.Wrapf(err, `load config file "%s" failed`, filePath) } else { err = gerror.Wrap(err, `load configuration failed`) } + return nil } - return nil + configJson.SetViolenceCheck(c.violenceCheck) + // Add monitor for this configuration file, + // any changes of this file will refresh its cache in Config object. + if filePath != "" && !gres.Contains(filePath) { + _, err = gfsnotify.Add(filePath, func(event *gfsnotify.Event) { + c.jsonMap.Remove(usedFileName) + }) + if err != nil { + return nil + } + } + return configJson }) if result != nil { return result.(*gjson.Json), err From 5f2047d61b368430233958110061f0718aff7535 Mon Sep 17 00:00:00 2001 From: John Guo Date: Mon, 14 Feb 2022 14:50:25 +0800 Subject: [PATCH 2/8] fix issue in configuration StdoutColorDisabled for package glog; rename TempDir to Temp for package gfile --- .../gcompress/gcompress_z_unit_gzip_test.go | 4 +- .../gcompress/gcompress_z_unit_zip_test.go | 16 +++--- frame/gins/gins_z_unit_config_test.go | 16 +++--- frame/gins/gins_z_unit_database_test.go | 2 +- frame/gins/gins_z_unit_redis_test.go | 2 +- frame/gins/gins_z_unit_view_test.go | 2 +- net/gclient/gclient_z_unit_test.go | 2 +- net/ghttp/ghttp_z_example_test.go | 2 +- net/ghttp/ghttp_z_unit_feature_config_test.go | 4 +- net/ghttp/ghttp_z_unit_feature_log_test.go | 2 +- .../ghttp_z_unit_feature_request_file_test.go | 6 +-- net/ghttp/ghttp_z_unit_feature_static_test.go | 28 +++++----- os/gcfg/gcfg_z_unit_basic_test.go | 2 +- os/gfile/gfile.go | 4 +- os/gfile/gfile_z_example_cache_test.go | 2 +- os/gfile/gfile_z_example_contents_test.go | 22 ++++---- os/gfile/gfile_z_example_copy_test.go | 4 +- os/gfile/gfile_z_example_replace_test.go | 8 +-- os/gfile/gfile_z_example_scan_test.go | 8 +-- os/gfile/gfile_z_example_search_test.go | 2 +- os/gfile/gfile_z_example_size_test.go | 6 +-- os/gfile/gfile_z_example_time_test.go | 6 +-- os/gfile/gfile_z_exmaple_basic_test.go | 52 +++++++++---------- os/gfile/gfile_z_unit_copy_test.go | 8 +-- os/gfile/gfile_z_unit_test.go | 4 +- os/gfpool/gfpool_z_unit_test.go | 12 ++--- os/gfsnotify/gfsnotify_z_unit_test.go | 14 ++--- os/glog/glog_logger.go | 19 +++---- os/glog/glog_logger_config.go | 9 +++- os/glog/glog_z_unit_logger_chaining_test.go | 26 +++++----- os/glog/glog_z_unit_logger_rotate_test.go | 4 +- os/glog/glog_z_unit_test.go | 2 +- os/gproc/gproc_comm.go | 2 +- os/gres/gres_z_unit_test.go | 14 ++--- os/gsession/gsession_storage_file.go | 2 +- os/gview/gview_z_unit_test.go | 4 +- 36 files changed, 160 insertions(+), 162 deletions(-) diff --git a/encoding/gcompress/gcompress_z_unit_gzip_test.go b/encoding/gcompress/gcompress_z_unit_gzip_test.go index 19e6d6698..a5836c3b1 100644 --- a/encoding/gcompress/gcompress_z_unit_gzip_test.go +++ b/encoding/gcompress/gcompress_z_unit_gzip_test.go @@ -44,8 +44,8 @@ func Test_Gzip_UnGzip(t *testing.T) { func Test_Gzip_UnGzip_File(t *testing.T) { srcPath := gdebug.TestDataPath("gzip", "file.txt") - dstPath1 := gfile.TempDir(gtime.TimestampNanoStr(), "gzip.zip") - dstPath2 := gfile.TempDir(gtime.TimestampNanoStr(), "file.txt") + dstPath1 := gfile.Temp(gtime.TimestampNanoStr(), "gzip.zip") + dstPath2 := gfile.Temp(gtime.TimestampNanoStr(), "file.txt") // Compress. gtest.C(t, func(t *gtest.T) { diff --git a/encoding/gcompress/gcompress_z_unit_zip_test.go b/encoding/gcompress/gcompress_z_unit_zip_test.go index 0cd3348d6..45a40715f 100644 --- a/encoding/gcompress/gcompress_z_unit_zip_test.go +++ b/encoding/gcompress/gcompress_z_unit_zip_test.go @@ -29,7 +29,7 @@ func Test_ZipPath(t *testing.T) { defer gfile.Remove(dstPath) // unzip to temporary dir. - tempDirPath := gfile.TempDir(gtime.TimestampNanoStr()) + tempDirPath := gfile.Temp(gtime.TimestampNanoStr()) t.Assert(gfile.Mkdir(tempDirPath), nil) t.Assert(gcompress.UnZipFile(dstPath, tempDirPath), nil) defer gfile.Remove(tempDirPath) @@ -44,7 +44,7 @@ func Test_ZipPath(t *testing.T) { var ( srcPath1 = gdebug.TestDataPath("zip", "path1", "1.txt") srcPath2 = gdebug.TestDataPath("zip", "path2", "2.txt") - dstPath = gfile.TempDir(gtime.TimestampNanoStr(), "zip.zip") + dstPath = gfile.Temp(gtime.TimestampNanoStr(), "zip.zip") ) if p := gfile.Dir(dstPath); !gfile.Exists(p) { t.Assert(gfile.Mkdir(p), nil) @@ -57,7 +57,7 @@ func Test_ZipPath(t *testing.T) { defer gfile.Remove(dstPath) // unzip to another temporary dir. - tempDirPath := gfile.TempDir(gtime.TimestampNanoStr()) + tempDirPath := gfile.Temp(gtime.TimestampNanoStr()) t.Assert(gfile.Mkdir(tempDirPath), nil) err = gcompress.UnZipFile(dstPath, tempDirPath) t.Assert(err, nil) @@ -77,7 +77,7 @@ func Test_ZipPath(t *testing.T) { var ( srcPath1 = gdebug.TestDataPath("zip", "path1") srcPath2 = gdebug.TestDataPath("zip", "path2", "2.txt") - dstPath = gfile.TempDir(gtime.TimestampNanoStr(), "zip.zip") + dstPath = gfile.Temp(gtime.TimestampNanoStr(), "zip.zip") ) if p := gfile.Dir(dstPath); !gfile.Exists(p) { t.Assert(gfile.Mkdir(p), nil) @@ -90,7 +90,7 @@ func Test_ZipPath(t *testing.T) { defer gfile.Remove(dstPath) // unzip to another temporary dir. - tempDirPath := gfile.TempDir(gtime.TimestampNanoStr()) + tempDirPath := gfile.Temp(gtime.TimestampNanoStr()) t.Assert(gfile.Mkdir(tempDirPath), nil) err = gcompress.UnZipFile(dstPath, tempDirPath) t.Assert(err, nil) @@ -121,7 +121,7 @@ func Test_ZipPath(t *testing.T) { t.Assert(gfile.Exists(dstPath), true) defer gfile.Remove(dstPath) - tempDirPath := gfile.TempDir(gtime.TimestampNanoStr()) + tempDirPath := gfile.Temp(gtime.TimestampNanoStr()) err = gfile.Mkdir(tempDirPath) t.Assert(err, nil) @@ -157,7 +157,7 @@ func Test_ZipPath(t *testing.T) { t.Assert(gfile.Exists(dstPath), true) defer gfile.Remove(dstPath) - tempDirPath := gfile.TempDir(gtime.TimestampNanoStr()) + tempDirPath := gfile.Temp(gtime.TimestampNanoStr()) err = gfile.Mkdir(tempDirPath) t.Assert(err, nil) @@ -196,7 +196,7 @@ func Test_ZipPathWriter(t *testing.T) { t.Assert(err, nil) t.AssertGT(writer.Len(), 0) - tempDirPath := gfile.TempDir(gtime.TimestampNanoStr()) + tempDirPath := gfile.Temp(gtime.TimestampNanoStr()) err = gfile.Mkdir(tempDirPath) t.Assert(err, nil) diff --git a/frame/gins/gins_z_unit_config_test.go b/frame/gins/gins_z_unit_config_test.go index 848cbd92a..409fef420 100644 --- a/frame/gins/gins_z_unit_config_test.go +++ b/frame/gins/gins_z_unit_config_test.go @@ -40,7 +40,7 @@ func Test_Config2(t *testing.T) { // relative path gtest.C(t, func(t *gtest.T) { var err error - dirPath := gfile.TempDir(gtime.TimestampNanoStr()) + dirPath := gfile.Temp(gtime.TimestampNanoStr()) err = gfile.Mkdir(dirPath) t.Assert(err, nil) defer gfile.Remove(dirPath) @@ -64,7 +64,7 @@ func Test_Config2(t *testing.T) { // relative path, config folder gtest.C(t, func(t *gtest.T) { var err error - dirPath := gfile.TempDir(gtime.TimestampNanoStr()) + dirPath := gfile.Temp(gtime.TimestampNanoStr()) err = gfile.Mkdir(dirPath) t.Assert(err, nil) defer gfile.Remove(dirPath) @@ -90,7 +90,7 @@ func Test_Config2(t *testing.T) { func Test_Config3(t *testing.T) { gtest.C(t, func(t *gtest.T) { var err error - dirPath := gfile.TempDir(gtime.TimestampNanoStr()) + dirPath := gfile.Temp(gtime.TimestampNanoStr()) err = gfile.Mkdir(dirPath) t.Assert(err, nil) defer gfile.Remove(dirPath) @@ -114,7 +114,7 @@ func Test_Config3(t *testing.T) { gtest.C(t, func(t *gtest.T) { var err error - dirPath := gfile.TempDir(gtime.TimestampNanoStr()) + dirPath := gfile.Temp(gtime.TimestampNanoStr()) err = gfile.Mkdir(dirPath) t.Assert(err, nil) defer gfile.Remove(dirPath) @@ -140,7 +140,7 @@ func Test_Config3(t *testing.T) { func Test_Config4(t *testing.T) { // absolute path gtest.C(t, func(t *gtest.T) { - path := fmt.Sprintf(`%s/%d`, gfile.TempDir(), gtime.TimestampNano()) + path := fmt.Sprintf(`%s/%d`, gfile.Temp(), gtime.TimestampNano()) file := fmt.Sprintf(`%s/%s`, path, "config.toml") err := gfile.PutContents(file, configContent) t.Assert(err, nil) @@ -155,7 +155,7 @@ func Test_Config4(t *testing.T) { time.Sleep(500 * time.Millisecond) gtest.C(t, func(t *gtest.T) { - path := fmt.Sprintf(`%s/%d/config`, gfile.TempDir(), gtime.TimestampNano()) + path := fmt.Sprintf(`%s/%d/config`, gfile.Temp(), gtime.TimestampNano()) file := fmt.Sprintf(`%s/%s`, path, "config.toml") err := gfile.PutContents(file, configContent) t.Assert(err, nil) @@ -169,7 +169,7 @@ func Test_Config4(t *testing.T) { time.Sleep(500 * time.Millisecond) gtest.C(t, func(t *gtest.T) { - path := fmt.Sprintf(`%s/%d`, gfile.TempDir(), gtime.TimestampNano()) + path := fmt.Sprintf(`%s/%d`, gfile.Temp(), gtime.TimestampNano()) file := fmt.Sprintf(`%s/%s`, path, "test.toml") err := gfile.PutContents(file, configContent) t.Assert(err, nil) @@ -184,7 +184,7 @@ func Test_Config4(t *testing.T) { time.Sleep(500 * time.Millisecond) gtest.C(t, func(t *gtest.T) { - path := fmt.Sprintf(`%s/%d/config`, gfile.TempDir(), gtime.TimestampNano()) + path := fmt.Sprintf(`%s/%d/config`, gfile.Temp(), gtime.TimestampNano()) file := fmt.Sprintf(`%s/%s`, path, "test.toml") err := gfile.PutContents(file, configContent) t.Assert(err, nil) diff --git a/frame/gins/gins_z_unit_database_test.go b/frame/gins/gins_z_unit_database_test.go index 622e10fed..6fd224f6f 100644 --- a/frame/gins/gins_z_unit_database_test.go +++ b/frame/gins/gins_z_unit_database_test.go @@ -24,7 +24,7 @@ func Test_Database(t *testing.T) { ) gtest.C(t, func(t *gtest.T) { var err error - dirPath := gfile.TempDir(gtime.TimestampNanoStr()) + dirPath := gfile.Temp(gtime.TimestampNanoStr()) err = gfile.Mkdir(dirPath) t.Assert(err, nil) defer gfile.Remove(dirPath) diff --git a/frame/gins/gins_z_unit_redis_test.go b/frame/gins/gins_z_unit_redis_test.go index f69936622..7fe073a1a 100644 --- a/frame/gins/gins_z_unit_redis_test.go +++ b/frame/gins/gins_z_unit_redis_test.go @@ -25,7 +25,7 @@ func Test_Redis(t *testing.T) { gtest.C(t, func(t *gtest.T) { var err error - dirPath := gfile.TempDir(gtime.TimestampNanoStr()) + dirPath := gfile.Temp(gtime.TimestampNanoStr()) err = gfile.Mkdir(dirPath) t.Assert(err, nil) defer gfile.Remove(dirPath) diff --git a/frame/gins/gins_z_unit_view_test.go b/frame/gins/gins_z_unit_view_test.go index f14c10f70..f40e73730 100644 --- a/frame/gins/gins_z_unit_view_test.go +++ b/frame/gins/gins_z_unit_view_test.go @@ -36,7 +36,7 @@ func Test_View(t *testing.T) { t.Assert(b, "中国人") }) gtest.C(t, func(t *gtest.T) { - path := fmt.Sprintf(`%s/%d`, gfile.TempDir(), gtime.TimestampNano()) + path := fmt.Sprintf(`%s/%d`, gfile.Temp(), gtime.TimestampNano()) tpl := fmt.Sprintf(`%s/%s`, path, "t.tpl") err := gfile.PutContents(tpl, `{{"我是中国人" | substr 2 -1}}`) t.Assert(err, nil) diff --git a/net/gclient/gclient_z_unit_test.go b/net/gclient/gclient_z_unit_test.go index af6d137a9..6fcfa5f2e 100644 --- a/net/gclient/gclient_z_unit_test.go +++ b/net/gclient/gclient_z_unit_test.go @@ -316,7 +316,7 @@ func Test_Client_File_And_Param(t *testing.T) { p, _ := gtcp.GetFreePort() s := g.Server(p) s.BindHandler("/", func(r *ghttp.Request) { - tmpPath := gfile.TempDir(guid.S()) + tmpPath := gfile.Temp(guid.S()) err := gfile.Mkdir(tmpPath) gtest.Assert(err, nil) defer gfile.Remove(tmpPath) diff --git a/net/ghttp/ghttp_z_example_test.go b/net/ghttp/ghttp_z_example_test.go index ce07cda1f..f3a6016ef 100644 --- a/net/ghttp/ghttp_z_example_test.go +++ b/net/ghttp/ghttp_z_example_test.go @@ -31,7 +31,7 @@ func ExampleUploadFile_Save() { return } file.Filename = "MyCustomFileName.txt" - fileName, err := file.Save(gfile.TempDir()) + fileName, err := file.Save(gfile.Temp()) if err != nil { r.Response.Write(err) return diff --git a/net/ghttp/ghttp_z_unit_feature_config_test.go b/net/ghttp/ghttp_z_unit_feature_config_test.go index 0a9a3ea1a..b6986c5e9 100644 --- a/net/ghttp/ghttp_z_unit_feature_config_test.go +++ b/net/ghttp/ghttp_z_unit_feature_config_test.go @@ -124,7 +124,7 @@ func Test_ClientMaxBodySize_File(t *testing.T) { c := g.Client() c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p)) - path := gfile.TempDir(gtime.TimestampNanoStr()) + path := gfile.Temp(gtime.TimestampNanoStr()) data := make([]byte, 512) for i := 0; i < 512; i++ { data[i] = 'a' @@ -142,7 +142,7 @@ func Test_ClientMaxBodySize_File(t *testing.T) { c := g.Client() c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p)) - path := gfile.TempDir(gtime.TimestampNanoStr()) + path := gfile.Temp(gtime.TimestampNanoStr()) data := make([]byte, 1056) for i := 0; i < 1056; i++ { data[i] = 'a' diff --git a/net/ghttp/ghttp_z_unit_feature_log_test.go b/net/ghttp/ghttp_z_unit_feature_log_test.go index 56148c0c5..4b57c9ba8 100644 --- a/net/ghttp/ghttp_z_unit_feature_log_test.go +++ b/net/ghttp/ghttp_z_unit_feature_log_test.go @@ -24,7 +24,7 @@ import ( func Test_Log(t *testing.T) { gtest.C(t, func(t *gtest.T) { - logDir := gfile.TempDir(gtime.TimestampNanoStr()) + logDir := gfile.Temp(gtime.TimestampNanoStr()) p, _ := gtcp.GetFreePort() s := g.Server(p) s.BindHandler("/hello", func(r *ghttp.Request) { diff --git a/net/ghttp/ghttp_z_unit_feature_request_file_test.go b/net/ghttp/ghttp_z_unit_feature_request_file_test.go index 9f5d7b62a..6b3d92dea 100644 --- a/net/ghttp/ghttp_z_unit_feature_request_file_test.go +++ b/net/ghttp/ghttp_z_unit_feature_request_file_test.go @@ -22,7 +22,7 @@ import ( ) func Test_Params_File_Single(t *testing.T) { - dstDirPath := gfile.TempDir(gtime.TimestampNanoStr()) + dstDirPath := gfile.Temp(gtime.TimestampNanoStr()) p, _ := gtcp.GetFreePort() s := g.Server(p) s.BindHandler("/upload/single", func(r *ghttp.Request) { @@ -76,7 +76,7 @@ func Test_Params_File_Single(t *testing.T) { } func Test_Params_File_CustomName(t *testing.T) { - dstDirPath := gfile.TempDir(gtime.TimestampNanoStr()) + dstDirPath := gfile.Temp(gtime.TimestampNanoStr()) p, _ := gtcp.GetFreePort() s := g.Server(p) s.BindHandler("/upload/single", func(r *ghttp.Request) { @@ -113,7 +113,7 @@ func Test_Params_File_CustomName(t *testing.T) { } func Test_Params_File_Batch(t *testing.T) { - dstDirPath := gfile.TempDir(gtime.TimestampNanoStr()) + dstDirPath := gfile.Temp(gtime.TimestampNanoStr()) p, _ := gtcp.GetFreePort() s := g.Server(p) s.BindHandler("/upload/batch", func(r *ghttp.Request) { diff --git a/net/ghttp/ghttp_z_unit_feature_static_test.go b/net/ghttp/ghttp_z_unit_feature_static_test.go index 8f6f5a994..0d009c78d 100644 --- a/net/ghttp/ghttp_z_unit_feature_static_test.go +++ b/net/ghttp/ghttp_z_unit_feature_static_test.go @@ -26,7 +26,7 @@ func Test_Static_ServerRoot(t *testing.T) { gtest.C(t, func(t *gtest.T) { p, _ := gtcp.GetFreePort() s := g.Server(p) - path := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.TempDir(), p) + path := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.Temp(), p) defer gfile.Remove(path) gfile.PutContents(path+"/index.htm", "index") s.SetServerRoot(path) @@ -86,7 +86,7 @@ func Test_Static_Folder_Forbidden(t *testing.T) { gtest.C(t, func(t *gtest.T) { p, _ := gtcp.GetFreePort() s := g.Server(p) - path := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.TempDir(), p) + path := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.Temp(), p) defer gfile.Remove(path) gfile.PutContents(path+"/test.html", "test") s.SetServerRoot(path) @@ -107,7 +107,7 @@ func Test_Static_IndexFolder(t *testing.T) { gtest.C(t, func(t *gtest.T) { p, _ := gtcp.GetFreePort() s := g.Server(p) - path := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.TempDir(), p) + path := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.Temp(), p) defer gfile.Remove(path) gfile.PutContents(path+"/test.html", "test") s.SetIndexFolder(true) @@ -130,7 +130,7 @@ func Test_Static_IndexFiles1(t *testing.T) { gtest.C(t, func(t *gtest.T) { p, _ := gtcp.GetFreePort() s := g.Server(p) - path := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.TempDir(), p) + path := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.Temp(), p) defer gfile.Remove(path) gfile.PutContents(path+"/index.html", "index") gfile.PutContents(path+"/test.html", "test") @@ -152,7 +152,7 @@ func Test_Static_IndexFiles2(t *testing.T) { gtest.C(t, func(t *gtest.T) { p, _ := gtcp.GetFreePort() s := g.Server(p) - path := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.TempDir(), p) + path := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.Temp(), p) defer gfile.Remove(path) gfile.PutContents(path+"/test.html", "test") s.SetIndexFiles([]string{"index.html", "test.html"}) @@ -174,8 +174,8 @@ func Test_Static_AddSearchPath1(t *testing.T) { gtest.C(t, func(t *gtest.T) { p, _ := gtcp.GetFreePort() s := g.Server(p) - path1 := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.TempDir(), p) - path2 := fmt.Sprintf(`%s/ghttp/static/test/%d/%d`, gfile.TempDir(), p, p) + path1 := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.Temp(), p) + path2 := fmt.Sprintf(`%s/ghttp/static/test/%d/%d`, gfile.Temp(), p, p) defer gfile.Remove(path1) defer gfile.Remove(path2) gfile.PutContents(path2+"/test.html", "test") @@ -197,8 +197,8 @@ func Test_Static_AddSearchPath2(t *testing.T) { gtest.C(t, func(t *gtest.T) { p, _ := gtcp.GetFreePort() s := g.Server(p) - path1 := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.TempDir(), p) - path2 := fmt.Sprintf(`%s/ghttp/static/test/%d/%d`, gfile.TempDir(), p, p) + path1 := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.Temp(), p) + path2 := fmt.Sprintf(`%s/ghttp/static/test/%d/%d`, gfile.Temp(), p, p) defer gfile.Remove(path1) defer gfile.Remove(path2) gfile.PutContents(path1+"/test.html", "test1") @@ -221,8 +221,8 @@ func Test_Static_AddStaticPath(t *testing.T) { gtest.C(t, func(t *gtest.T) { p, _ := gtcp.GetFreePort() s := g.Server(p) - path1 := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.TempDir(), p) - path2 := fmt.Sprintf(`%s/ghttp/static/test/%d/%d`, gfile.TempDir(), p, p) + path1 := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.Temp(), p) + path2 := fmt.Sprintf(`%s/ghttp/static/test/%d/%d`, gfile.Temp(), p, p) defer gfile.Remove(path1) defer gfile.Remove(path2) gfile.PutContents(path1+"/test.html", "test1") @@ -246,8 +246,8 @@ func Test_Static_AddStaticPath_Priority(t *testing.T) { gtest.C(t, func(t *gtest.T) { p, _ := gtcp.GetFreePort() s := g.Server(p) - path1 := fmt.Sprintf(`%s/ghttp/static/test/%d/test`, gfile.TempDir(), p) - path2 := fmt.Sprintf(`%s/ghttp/static/test/%d/%d/test`, gfile.TempDir(), p, p) + path1 := fmt.Sprintf(`%s/ghttp/static/test/%d/test`, gfile.Temp(), p) + path2 := fmt.Sprintf(`%s/ghttp/static/test/%d/%d/test`, gfile.Temp(), p, p) defer gfile.Remove(path1) defer gfile.Remove(path2) gfile.PutContents(path1+"/test.html", "test1") @@ -271,7 +271,7 @@ func Test_Static_Rewrite(t *testing.T) { gtest.C(t, func(t *gtest.T) { p, _ := gtcp.GetFreePort() s := g.Server(p) - path := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.TempDir(), p) + path := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.Temp(), p) defer gfile.Remove(path) gfile.PutContents(path+"/test1.html", "test1") gfile.PutContents(path+"/test2.html", "test2") diff --git a/os/gcfg/gcfg_z_unit_basic_test.go b/os/gcfg/gcfg_z_unit_basic_test.go index 50090421c..0400c93fb 100644 --- a/os/gcfg/gcfg_z_unit_basic_test.go +++ b/os/gcfg/gcfg_z_unit_basic_test.go @@ -168,7 +168,7 @@ func TestCfg_Set(t *testing.T) { func TestCfg_Get_WrongConfigFile(t *testing.T) { gtest.C(t, func(t *gtest.T) { var err error - configPath := gfile.TempDir(gtime.TimestampNanoStr()) + configPath := gfile.Temp(gtime.TimestampNanoStr()) err = gfile.Mkdir(configPath) t.Assert(err, nil) defer gfile.Remove(configPath) diff --git a/os/gfile/gfile.go b/os/gfile/gfile.go index 79977dae3..590112bf7 100644 --- a/os/gfile/gfile.go +++ b/os/gfile/gfile.go @@ -433,12 +433,12 @@ func ExtName(path string) string { return strings.TrimLeft(Ext(path), ".") } -// TempDir retrieves and returns the temporary directory of current system. +// Temp retrieves and returns the temporary directory of current system. // It returns "/tmp" is current in *nix system, or else it returns os.TempDir(). // // The optional parameter `names` specifies the sub-folders/sub-files, // which will be joined with current system separator and returned with the path. -func TempDir(names ...string) string { +func Temp(names ...string) string { path := tempDir for _, name := range names { path += Separator + name diff --git a/os/gfile/gfile_z_example_cache_test.go b/os/gfile/gfile_z_example_cache_test.go index 3ca819779..a729dce46 100644 --- a/os/gfile/gfile_z_example_cache_test.go +++ b/os/gfile/gfile_z_example_cache_test.go @@ -17,7 +17,7 @@ func ExampleGetContentsWithCache() { // init var ( fileName = "gflie_example.txt" - tempDir = gfile.TempDir("gfile_example_cache") + tempDir = gfile.Temp("gfile_example_cache") tempFile = gfile.Join(tempDir, fileName) ) diff --git a/os/gfile/gfile_z_example_contents_test.go b/os/gfile/gfile_z_example_contents_test.go index 13e90500c..5d9ebb81e 100644 --- a/os/gfile/gfile_z_example_contents_test.go +++ b/os/gfile/gfile_z_example_contents_test.go @@ -16,7 +16,7 @@ func ExampleGetContents() { // init var ( fileName = "gflie_example.txt" - tempDir = gfile.TempDir("gfile_example_content") + tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) @@ -35,7 +35,7 @@ func ExampleGetBytes() { // init var ( fileName = "gflie_example.txt" - tempDir = gfile.TempDir("gfile_example_content") + tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) @@ -54,7 +54,7 @@ func ExamplePutContents() { // init var ( fileName = "gflie_example.txt" - tempDir = gfile.TempDir("gfile_example_content") + tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) @@ -73,7 +73,7 @@ func ExamplePutBytes() { // init var ( fileName = "gflie_example.txt" - tempDir = gfile.TempDir("gfile_example_content") + tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) @@ -91,7 +91,7 @@ func ExamplePutContentsAppend() { // init var ( fileName = "gflie_example.txt" - tempDir = gfile.TempDir("gfile_example_content") + tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) @@ -117,7 +117,7 @@ func ExamplePutBytesAppend() { // init var ( fileName = "gflie_example.txt" - tempDir = gfile.TempDir("gfile_example_content") + tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) @@ -142,7 +142,7 @@ func ExampleGetNextCharOffsetByPath() { // init var ( fileName = "gflie_example.txt" - tempDir = gfile.TempDir("gfile_example_content") + tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) @@ -161,7 +161,7 @@ func ExampleGetBytesTilCharByPath() { // init var ( fileName = "gflie_example.txt" - tempDir = gfile.TempDir("gfile_example_content") + tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) @@ -179,7 +179,7 @@ func ExampleGetBytesByTwoOffsetsByPath() { // init var ( fileName = "gflie_example.txt" - tempDir = gfile.TempDir("gfile_example_content") + tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) @@ -197,7 +197,7 @@ func ExampleReadLines() { // init var ( fileName = "gflie_example.txt" - tempDir = gfile.TempDir("gfile_example_content") + tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) @@ -220,7 +220,7 @@ func ExampleReadLinesBytes() { // init var ( fileName = "gflie_example.txt" - tempDir = gfile.TempDir("gfile_example_content") + tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) diff --git a/os/gfile/gfile_z_example_copy_test.go b/os/gfile/gfile_z_example_copy_test.go index 293d40a82..6136990cd 100644 --- a/os/gfile/gfile_z_example_copy_test.go +++ b/os/gfile/gfile_z_example_copy_test.go @@ -16,7 +16,7 @@ func ExampleCopy() { // init var ( srcFileName = "gflie_example.txt" - srcTempDir = gfile.TempDir("gfile_example_copy_src") + srcTempDir = gfile.Temp("gfile_example_copy_src") srcTempFile = gfile.Join(srcTempDir, srcFileName) // copy file @@ -24,7 +24,7 @@ func ExampleCopy() { dstTempFile = gfile.Join(srcTempDir, dstFileName) // copy dir - dstTempDir = gfile.TempDir("gfile_example_copy_dst") + dstTempDir = gfile.Temp("gfile_example_copy_dst") ) // write contents diff --git a/os/gfile/gfile_z_example_replace_test.go b/os/gfile/gfile_z_example_replace_test.go index df4d3a931..0f9e654fa 100644 --- a/os/gfile/gfile_z_example_replace_test.go +++ b/os/gfile/gfile_z_example_replace_test.go @@ -17,7 +17,7 @@ func ExampleReplaceFile() { // init var ( fileName = "gflie_example.txt" - tempDir = gfile.TempDir("gfile_example_replace") + tempDir = gfile.Temp("gfile_example_replace") tempFile = gfile.Join(tempDir, fileName) ) @@ -41,7 +41,7 @@ func ExampleReplaceFileFunc() { // init var ( fileName = "gflie_example.txt" - tempDir = gfile.TempDir("gfile_example_replace") + tempDir = gfile.Temp("gfile_example_replace") tempFile = gfile.Join(tempDir, fileName) ) @@ -69,7 +69,7 @@ func ExampleReplaceDir() { // init var ( fileName = "gflie_example.txt" - tempDir = gfile.TempDir("gfile_example_replace") + tempDir = gfile.Temp("gfile_example_replace") tempFile = gfile.Join(tempDir, fileName) ) @@ -94,7 +94,7 @@ func ExampleReplaceDirFunc() { // init var ( fileName = "gflie_example.txt" - tempDir = gfile.TempDir("gfile_example_replace") + tempDir = gfile.Temp("gfile_example_replace") tempFile = gfile.Join(tempDir, fileName) ) diff --git a/os/gfile/gfile_z_example_scan_test.go b/os/gfile/gfile_z_example_scan_test.go index 0238dbbb0..386f3c080 100644 --- a/os/gfile/gfile_z_example_scan_test.go +++ b/os/gfile/gfile_z_example_scan_test.go @@ -16,7 +16,7 @@ func ExampleScanDir() { // init var ( fileName = "gflie_example.txt" - tempDir = gfile.TempDir("gfile_example_scan_dir") + tempDir = gfile.Temp("gfile_example_scan_dir") tempFile = gfile.Join(tempDir, fileName) tempSubDir = gfile.Join(tempDir, "sub_dir") @@ -43,7 +43,7 @@ func ExampleScanDirFile() { // init var ( fileName = "gflie_example.txt" - tempDir = gfile.TempDir("gfile_example_scan_dir_file") + tempDir = gfile.Temp("gfile_example_scan_dir_file") tempFile = gfile.Join(tempDir, fileName) tempSubDir = gfile.Join(tempDir, "sub_dir") @@ -69,7 +69,7 @@ func ExampleScanDirFunc() { // init var ( fileName = "gflie_example.txt" - tempDir = gfile.TempDir("gfile_example_scan_dir_func") + tempDir = gfile.Temp("gfile_example_scan_dir_func") tempFile = gfile.Join(tempDir, fileName) tempSubDir = gfile.Join(tempDir, "sub_dir") @@ -100,7 +100,7 @@ func ExampleScanDirFileFunc() { // init var ( fileName = "gflie_example.txt" - tempDir = gfile.TempDir("gfile_example_scan_dir_file_func") + tempDir = gfile.Temp("gfile_example_scan_dir_file_func") tempFile = gfile.Join(tempDir, fileName) fileName1 = "gflie_example_ignores.txt" diff --git a/os/gfile/gfile_z_example_search_test.go b/os/gfile/gfile_z_example_search_test.go index 3fdaf4309..8a93bc6d0 100644 --- a/os/gfile/gfile_z_example_search_test.go +++ b/os/gfile/gfile_z_example_search_test.go @@ -16,7 +16,7 @@ func ExampleSearch() { // init var ( fileName = "gflie_example.txt" - tempDir = gfile.TempDir("gfile_example_search") + tempDir = gfile.Temp("gfile_example_search") tempFile = gfile.Join(tempDir, fileName) ) diff --git a/os/gfile/gfile_z_example_size_test.go b/os/gfile/gfile_z_example_size_test.go index b4696e6bc..6ddcd29ad 100644 --- a/os/gfile/gfile_z_example_size_test.go +++ b/os/gfile/gfile_z_example_size_test.go @@ -16,7 +16,7 @@ func ExampleSize() { // init var ( fileName = "gflie_example.txt" - tempDir = gfile.TempDir("gfile_example_size") + tempDir = gfile.Temp("gfile_example_size") tempFile = gfile.Join(tempDir, fileName) ) @@ -32,7 +32,7 @@ func ExampleSizeFormat() { // init var ( fileName = "gflie_example.txt" - tempDir = gfile.TempDir("gfile_example_size") + tempDir = gfile.Temp("gfile_example_size") tempFile = gfile.Join(tempDir, fileName) ) @@ -48,7 +48,7 @@ func ExampleReadableSize() { // init var ( fileName = "gflie_example.txt" - tempDir = gfile.TempDir("gfile_example_size") + tempDir = gfile.Temp("gfile_example_size") tempFile = gfile.Join(tempDir, fileName) ) diff --git a/os/gfile/gfile_z_example_time_test.go b/os/gfile/gfile_z_example_time_test.go index e4a11ef51..9d51ba1b0 100644 --- a/os/gfile/gfile_z_example_time_test.go +++ b/os/gfile/gfile_z_example_time_test.go @@ -13,7 +13,7 @@ import ( ) func ExampleMTime() { - t := gfile.MTime(gfile.TempDir()) + t := gfile.MTime(gfile.Temp()) fmt.Println(t) // May Output: @@ -21,7 +21,7 @@ func ExampleMTime() { } func ExampleMTimestamp() { - t := gfile.MTimestamp(gfile.TempDir()) + t := gfile.MTimestamp(gfile.Temp()) fmt.Println(t) // May Output: @@ -29,7 +29,7 @@ func ExampleMTimestamp() { } func ExampleMTimestampMilli() { - t := gfile.MTimestampMilli(gfile.TempDir()) + t := gfile.MTimestampMilli(gfile.Temp()) fmt.Println(t) // May Output: diff --git a/os/gfile/gfile_z_exmaple_basic_test.go b/os/gfile/gfile_z_exmaple_basic_test.go index 9a9f12d96..188d0a374 100644 --- a/os/gfile/gfile_z_exmaple_basic_test.go +++ b/os/gfile/gfile_z_exmaple_basic_test.go @@ -16,7 +16,7 @@ import ( func ExampleMkdir() { // init var ( - path = gfile.TempDir("gfile_example_basic_dir") + path = gfile.Temp("gfile_example_basic_dir") ) // Creates directory @@ -32,7 +32,7 @@ func ExampleMkdir() { func ExampleCreate() { // init var ( - path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1") + path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") dataByte = make([]byte, 50) ) // Check whether the file exists @@ -66,7 +66,7 @@ func ExampleCreate() { func ExampleOpen() { // init var ( - path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1") + path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") dataByte = make([]byte, 4096) ) // Open file or directory with READONLY model @@ -85,7 +85,7 @@ func ExampleOpen() { func ExampleOpenFile() { // init var ( - path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1") + path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") dataByte = make([]byte, 4096) ) // Opens file/directory with custom `flag` and `perm` @@ -111,7 +111,7 @@ func ExampleOpenFile() { func ExampleOpenWithFlag() { // init var ( - path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1") + path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") dataByte = make([]byte, 4096) ) @@ -138,7 +138,7 @@ func ExampleOpenWithFlag() { func ExampleJoin() { // init var ( - dirPath = gfile.TempDir("gfile_example_basic_dir") + dirPath = gfile.Temp("gfile_example_basic_dir") filePath = "file1" ) @@ -154,7 +154,7 @@ func ExampleJoin() { func ExampleExists() { // init var ( - path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1") + path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") ) // Checks whether given `path` exist. joinString := gfile.Exists(path) @@ -168,8 +168,8 @@ func ExampleExists() { func ExampleIsDir() { // init var ( - path = gfile.TempDir("gfile_example_basic_dir") - filePath = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1") + path = gfile.Temp("gfile_example_basic_dir") + filePath = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") ) // Checks whether given `path` a directory. fmt.Println(gfile.IsDir(path)) @@ -191,7 +191,7 @@ func ExamplePwd() { func ExampleChdir() { // init var ( - path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1") + path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") ) // Get current working directory fmt.Println(gfile.Pwd()) @@ -210,8 +210,8 @@ func ExampleChdir() { func ExampleIsFile() { // init var ( - filePath = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1") - dirPath = gfile.TempDir("gfile_example_basic_dir") + filePath = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") + dirPath = gfile.Temp("gfile_example_basic_dir") ) // Checks whether given `path` a file, which means it's not a directory. fmt.Println(gfile.IsFile(filePath)) @@ -225,7 +225,7 @@ func ExampleIsFile() { func ExampleStat() { // init var ( - path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1") + path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") ) // Get a FileInfo describing the named file. stat, _ := gfile.Stat(path) @@ -248,8 +248,8 @@ func ExampleStat() { func ExampleMove() { // init var ( - srcPath = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1") - dstPath = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file2") + srcPath = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") + dstPath = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file2") ) // Check is file fmt.Println(gfile.IsFile(dstPath)) @@ -270,8 +270,8 @@ func ExampleMove() { func ExampleRename() { // init var ( - srcPath = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file2") - dstPath = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1") + srcPath = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file2") + dstPath = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") ) // Check is file fmt.Println(gfile.IsFile(dstPath)) @@ -292,7 +292,7 @@ func ExampleRename() { func ExampleDirNames() { // init var ( - path = gfile.TempDir("gfile_example_basic_dir") + path = gfile.Temp("gfile_example_basic_dir") ) // Get sub-file names of given directory `path`. dirNames, _ := gfile.DirNames(path) @@ -353,7 +353,7 @@ func ExampleIsWritable() { func ExampleChmod() { // init var ( - path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1") + path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") ) // Get a FileInfo describing the named file. @@ -380,7 +380,7 @@ func ExampleChmod() { func ExampleAbs() { // init var ( - path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1") + path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") ) // Get an absolute representation of path. @@ -393,8 +393,8 @@ func ExampleAbs() { func ExampleRealPath() { // init var ( - realPath = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1") - worryPath = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "worryFile") + realPath = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") + worryPath = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "worryFile") ) // fetch an absolute representation of path. @@ -462,7 +462,7 @@ func ExampleName() { func ExampleDir() { // init var ( - path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1") + path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") ) // Get all but the last element of path, typically the path's directory. @@ -475,7 +475,7 @@ func ExampleDir() { func ExampleIsEmpty() { // init var ( - path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1") + path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") ) // Check whether the `path` is empty @@ -525,7 +525,7 @@ func ExampleTempDir() { ) // fetch an absolute representation of path. - path := gfile.TempDir(fileName) + path := gfile.Temp(fileName) fmt.Println(path) @@ -536,7 +536,7 @@ func ExampleTempDir() { func ExampleRemove() { // init var ( - path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1") + path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") ) // Checks whether given `path` a file, which means it's not a directory. diff --git a/os/gfile/gfile_z_unit_copy_test.go b/os/gfile/gfile_z_unit_copy_test.go index 6a4ebdfdf..73cb2689f 100644 --- a/os/gfile/gfile_z_unit_copy_test.go +++ b/os/gfile/gfile_z_unit_copy_test.go @@ -50,8 +50,8 @@ func Test_CopyFile(t *testing.T) { }) // Content replacement. gtest.C(t, func(t *gtest.T) { - src := gfile.TempDir(gtime.TimestampNanoStr()) - dst := gfile.TempDir(gtime.TimestampNanoStr()) + src := gfile.Temp(gtime.TimestampNanoStr()) + dst := gfile.Temp(gtime.TimestampNanoStr()) srcContent := "1" dstContent := "1" t.Assert(gfile.PutContents(src, srcContent), nil) @@ -111,8 +111,8 @@ func Test_CopyDir(t *testing.T) { }) // Content replacement. gtest.C(t, func(t *gtest.T) { - src := gfile.TempDir(gtime.TimestampNanoStr(), gtime.TimestampNanoStr()) - dst := gfile.TempDir(gtime.TimestampNanoStr(), gtime.TimestampNanoStr()) + src := gfile.Temp(gtime.TimestampNanoStr(), gtime.TimestampNanoStr()) + dst := gfile.Temp(gtime.TimestampNanoStr(), gtime.TimestampNanoStr()) defer func() { gfile.Remove(src) gfile.Remove(dst) diff --git a/os/gfile/gfile_z_unit_test.go b/os/gfile/gfile_z_unit_test.go index 4ef155e26..1b0c6596b 100644 --- a/os/gfile/gfile_z_unit_test.go +++ b/os/gfile/gfile_z_unit_test.go @@ -610,9 +610,9 @@ func Test_ExtName(t *testing.T) { func Test_TempDir(t *testing.T) { gtest.C(t, func(t *gtest.T) { if gfile.Separator != "/" || !gfile.Exists("/tmp") { - t.Assert(gfile.TempDir(), os.TempDir()) + t.Assert(gfile.Temp(), os.TempDir()) } else { - t.Assert(gfile.TempDir(), "/tmp") + t.Assert(gfile.Temp(), "/tmp") } }) } diff --git a/os/gfpool/gfpool_z_unit_test.go b/os/gfpool/gfpool_z_unit_test.go index 87e12a461..6ea9df9f0 100644 --- a/os/gfpool/gfpool_z_unit_test.go +++ b/os/gfpool/gfpool_z_unit_test.go @@ -147,7 +147,7 @@ func stop(testFile string) { func Test_ConcurrentOS(t *testing.T) { gtest.C(t, func(t *gtest.T) { - path := gfile.TempDir(gtime.TimestampNanoStr()) + path := gfile.Temp(gtime.TimestampNanoStr()) defer gfile.Remove(path) f1, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) t.Assert(err, nil) @@ -178,7 +178,7 @@ func Test_ConcurrentOS(t *testing.T) { }) gtest.C(t, func(t *gtest.T) { - path := gfile.TempDir(gtime.TimestampNanoStr()) + path := gfile.Temp(gtime.TimestampNanoStr()) defer gfile.Remove(path) f1, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) t.Assert(err, nil) @@ -199,7 +199,7 @@ func Test_ConcurrentOS(t *testing.T) { t.Assert(gstr.Count(gfile.GetContents(path), "@1234567890#"), 2000) }) gtest.C(t, func(t *gtest.T) { - path := gfile.TempDir(gtime.TimestampNanoStr()) + path := gfile.Temp(gtime.TimestampNanoStr()) defer gfile.Remove(path) f1, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) t.Assert(err, nil) @@ -227,7 +227,7 @@ func Test_ConcurrentOS(t *testing.T) { }) // DATA RACE // gtest.C(t, func(t *gtest.T) { - // path := gfile.TempDir(gtime.TimestampNanoStr()) + // path := gfile.Temp(gtime.TimestampNanoStr()) // defer gfile.Remove(path) // f1, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) // t.Assert(err, nil) @@ -265,7 +265,7 @@ func Test_ConcurrentOS(t *testing.T) { func Test_ConcurrentGFPool(t *testing.T) { gtest.C(t, func(t *gtest.T) { - path := gfile.TempDir(gtime.TimestampNanoStr()) + path := gfile.Temp(gtime.TimestampNanoStr()) defer gfile.Remove(path) f1, err := gfpool.Open(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) t.Assert(err, nil) @@ -287,7 +287,7 @@ func Test_ConcurrentGFPool(t *testing.T) { }) // DATA RACE // gtest.C(t, func(t *gtest.T) { - // path := gfile.TempDir(gtime.TimestampNanoStr()) + // path := gfile.Temp(gtime.TimestampNanoStr()) // defer gfile.Remove(path) // f1, err := gfpool.Open(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) // t.Assert(err, nil) diff --git a/os/gfsnotify/gfsnotify_z_unit_test.go b/os/gfsnotify/gfsnotify_z_unit_test.go index 020e4fe09..d72530b33 100644 --- a/os/gfsnotify/gfsnotify_z_unit_test.go +++ b/os/gfsnotify/gfsnotify_z_unit_test.go @@ -22,7 +22,7 @@ import ( func TestWatcher_AddOnce(t *testing.T) { gtest.C(t, func(t *gtest.T) { value := gtype.New() - path := gfile.TempDir(gconv.String(gtime.TimestampNano())) + path := gfile.Temp(gconv.String(gtime.TimestampNano())) err := gfile.PutContents(path, "init") t.Assert(err, nil) defer gfile.Remove(path) @@ -57,8 +57,8 @@ func TestWatcher_AddOnce(t *testing.T) { func TestWatcher_AddRemove(t *testing.T) { gtest.C(t, func(t *gtest.T) { - path1 := gfile.TempDir() + gfile.Separator + gconv.String(gtime.TimestampNano()) - path2 := gfile.TempDir() + gfile.Separator + gconv.String(gtime.TimestampNano()) + "2" + path1 := gfile.Temp() + gfile.Separator + gconv.String(gtime.TimestampNano()) + path2 := gfile.Temp() + gfile.Separator + gconv.String(gtime.TimestampNano()) + "2" gfile.PutContents(path1, "1") defer func() { gfile.Remove(path1) @@ -89,7 +89,7 @@ func TestWatcher_AddRemove(t *testing.T) { }) gtest.C(t, func(t *gtest.T) { - path1 := gfile.TempDir() + gfile.Separator + gconv.String(gtime.TimestampNano()) + path1 := gfile.Temp() + gfile.Separator + gconv.String(gtime.TimestampNano()) gfile.PutContents(path1, "1") defer func() { gfile.Remove(path1) @@ -124,7 +124,7 @@ func TestWatcher_AddRemove(t *testing.T) { func TestWatcher_Callback1(t *testing.T) { gtest.C(t, func(t *gtest.T) { - path1 := gfile.TempDir(gtime.TimestampNanoStr()) + path1 := gfile.Temp(gtime.TimestampNanoStr()) gfile.PutContents(path1, "1") defer func() { gfile.Remove(path1) @@ -154,7 +154,7 @@ func TestWatcher_Callback1(t *testing.T) { func TestWatcher_Callback2(t *testing.T) { // multiple callbacks gtest.C(t, func(t *gtest.T) { - path1 := gfile.TempDir(gtime.TimestampNanoStr()) + path1 := gfile.Temp(gtime.TimestampNanoStr()) t.Assert(gfile.PutContents(path1, "1"), nil) defer func() { gfile.Remove(path1) @@ -198,7 +198,7 @@ func TestWatcher_WatchFolderWithoutRecursively(t *testing.T) { var ( err error array = garray.New(true) - dirPath = gfile.TempDir(gtime.TimestampNanoStr()) + dirPath = gfile.Temp(gtime.TimestampNanoStr()) ) err = gfile.Mkdir(dirPath) t.AssertNil(err) diff --git a/os/glog/glog_logger.go b/os/glog/glog_logger.go index 9cfd8494f..8dd985759 100644 --- a/os/glog/glog_logger.go +++ b/os/glog/glog_logger.go @@ -276,21 +276,14 @@ func (l *Logger) printToStdout(ctx context.Context, input *HandlerInput) *bytes. if l.config.StdoutPrint { var ( err error - buffer = input.getRealBuffer(true) + buffer = input.getRealBuffer(!l.config.StdoutColorDisabled) ) - if l.config.StdoutColorDisabled { - // Output to stdout without color. - if _, err = os.Stdout.Write(buffer.Bytes()); err != nil { - intlog.Errorf(ctx, `%+v`, err) - } - } else { - // This will lose color in Windows os system. - // if _, err := os.Stdout.Write(input.getRealBuffer(true).Bytes()); err != nil { + // This will lose color in Windows os system. + // if _, err := os.Stdout.Write(input.getRealBuffer(true).Bytes()); err != nil { - // This will print color in Windows os system. - if _, err = fmt.Fprint(color.Output, buffer.String()); err != nil { - intlog.Errorf(ctx, `%+v`, err) - } + // This will print color in Windows os system. + if _, err = fmt.Fprint(color.Output, buffer.String()); err != nil { + intlog.Errorf(ctx, `%+v`, err) } return buffer } diff --git a/os/glog/glog_logger_config.go b/os/glog/glog_logger_config.go index 933d321d7..9dcd1ee51 100644 --- a/os/glog/glog_logger_config.go +++ b/os/glog/glog_logger_config.go @@ -193,7 +193,7 @@ func (l *Logger) GetCtxKeys() []interface{} { } // SetWriter sets the customized logging `writer` for logging. -// The `writer` object should implements the io.Writer interface. +// The `writer` object should implement the io.Writer interface. // Developer can use customized logging `writer` to redirect logging output to another service, // eg: kafka, mysql, mongodb, etc. func (l *Logger) SetWriter(writer io.Writer) { @@ -254,7 +254,12 @@ func (l *Logger) SetHandlers(handlers ...Handler) { l.config.Handlers = handlers } -// SetWriterColorEnable sets the file logging with color +// SetWriterColorEnable enables file/writer logging with color. func (l *Logger) SetWriterColorEnable(enabled bool) { l.config.WriterColorEnable = enabled } + +// SetStdoutColorDisabled disables stdout logging with color. +func (l *Logger) SetStdoutColorDisabled(disabled bool) { + l.config.StdoutColorDisabled = disabled +} diff --git a/os/glog/glog_z_unit_logger_chaining_test.go b/os/glog/glog_z_unit_logger_chaining_test.go index 0c41d9bcb..1a0d958db 100644 --- a/os/glog/glog_z_unit_logger_chaining_test.go +++ b/os/glog/glog_z_unit_logger_chaining_test.go @@ -30,7 +30,7 @@ func Test_To(t *testing.T) { func Test_Path(t *testing.T) { gtest.C(t, func(t *gtest.T) { - path := gfile.TempDir(gtime.TimestampNanoStr()) + path := gfile.Temp(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) @@ -48,7 +48,7 @@ func Test_Path(t *testing.T) { func Test_Cat(t *testing.T) { gtest.C(t, func(t *gtest.T) { cat := "category" - path := gfile.TempDir(gtime.TimestampNanoStr()) + path := gfile.Temp(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) @@ -65,7 +65,7 @@ func Test_Cat(t *testing.T) { func Test_Level(t *testing.T) { gtest.C(t, func(t *gtest.T) { - path := gfile.TempDir(gtime.TimestampNanoStr()) + path := gfile.Temp(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) @@ -82,7 +82,7 @@ func Test_Level(t *testing.T) { func Test_Skip(t *testing.T) { gtest.C(t, func(t *gtest.T) { - path := gfile.TempDir(gtime.TimestampNanoStr()) + path := gfile.Temp(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) @@ -101,7 +101,7 @@ func Test_Skip(t *testing.T) { func Test_Stack(t *testing.T) { gtest.C(t, func(t *gtest.T) { - path := gfile.TempDir(gtime.TimestampNanoStr()) + path := gfile.Temp(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) @@ -120,7 +120,7 @@ func Test_Stack(t *testing.T) { func Test_StackWithFilter(t *testing.T) { gtest.C(t, func(t *gtest.T) { - path := gfile.TempDir(gtime.TimestampNanoStr()) + path := gfile.Temp(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) @@ -136,7 +136,7 @@ func Test_StackWithFilter(t *testing.T) { }) gtest.C(t, func(t *gtest.T) { - path := gfile.TempDir(gtime.TimestampNanoStr()) + path := gfile.Temp(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) @@ -154,7 +154,7 @@ func Test_StackWithFilter(t *testing.T) { func Test_Header(t *testing.T) { gtest.C(t, func(t *gtest.T) { - path := gfile.TempDir(gtime.TimestampNanoStr()) + path := gfile.Temp(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) @@ -167,7 +167,7 @@ func Test_Header(t *testing.T) { t.Assert(gstr.Count(content, "1 2 3"), 1) }) gtest.C(t, func(t *gtest.T) { - path := gfile.TempDir(gtime.TimestampNanoStr()) + path := gfile.Temp(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) @@ -183,7 +183,7 @@ func Test_Header(t *testing.T) { func Test_Line(t *testing.T) { gtest.C(t, func(t *gtest.T) { - path := gfile.TempDir(gtime.TimestampNanoStr()) + path := gfile.Temp(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) @@ -199,7 +199,7 @@ func Test_Line(t *testing.T) { //t.Assert(gstr.Contains(content, gfile.Separator), true) }) gtest.C(t, func(t *gtest.T) { - path := gfile.TempDir(gtime.TimestampNanoStr()) + path := gfile.Temp(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) @@ -217,7 +217,7 @@ func Test_Line(t *testing.T) { func Test_Async(t *testing.T) { gtest.C(t, func(t *gtest.T) { - path := gfile.TempDir(gtime.TimestampNanoStr()) + path := gfile.Temp(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) @@ -235,7 +235,7 @@ func Test_Async(t *testing.T) { }) gtest.C(t, func(t *gtest.T) { - path := gfile.TempDir(gtime.TimestampNanoStr()) + path := gfile.Temp(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) diff --git a/os/glog/glog_z_unit_logger_rotate_test.go b/os/glog/glog_z_unit_logger_rotate_test.go index 36da85b1d..f17719054 100644 --- a/os/glog/glog_z_unit_logger_rotate_test.go +++ b/os/glog/glog_z_unit_logger_rotate_test.go @@ -27,7 +27,7 @@ var ( func Test_Rotate_Size(t *testing.T) { gtest.C(t, func(t *gtest.T) { l := glog.New() - p := gfile.TempDir(gtime.TimestampNanoStr()) + p := gfile.Temp(gtime.TimestampNanoStr()) err := l.SetConfigWithMap(g.Map{ "Path": p, "File": "access.log", @@ -66,7 +66,7 @@ func Test_Rotate_Size(t *testing.T) { func Test_Rotate_Expire(t *testing.T) { gtest.C(t, func(t *gtest.T) { l := glog.New() - p := gfile.TempDir(gtime.TimestampNanoStr()) + p := gfile.Temp(gtime.TimestampNanoStr()) err := l.SetConfigWithMap(g.Map{ "Path": p, "File": "access.log", diff --git a/os/glog/glog_z_unit_test.go b/os/glog/glog_z_unit_test.go index 548442718..f22677dbd 100644 --- a/os/glog/glog_z_unit_test.go +++ b/os/glog/glog_z_unit_test.go @@ -60,7 +60,7 @@ func Test_Concurrent(t *testing.T) { l := glog.New() s := "@1234567890#" f := "test.log" - p := gfile.TempDir(gtime.TimestampNanoStr()) + p := gfile.Temp(gtime.TimestampNanoStr()) t.Assert(l.SetPath(p), nil) defer gfile.Remove(p) wg := sync.WaitGroup{} diff --git a/os/gproc/gproc_comm.go b/os/gproc/gproc_comm.go index f2a66125e..40652bcc0 100644 --- a/os/gproc/gproc_comm.go +++ b/os/gproc/gproc_comm.go @@ -57,7 +57,7 @@ func init() { if homePath, _ := gfile.Home(); homePath != "" { availablePaths = append(availablePaths, gfile.Join(homePath, ".config")) } - availablePaths = append(availablePaths, gfile.TempDir()) + availablePaths = append(availablePaths, gfile.Temp()) for _, availablePath := range availablePaths { checkPath := gfile.Join(availablePath, defaultFolderNameForProcComm) if !gfile.Exists(checkPath) && gfile.Mkdir(checkPath) != nil { diff --git a/os/gres/gres_z_unit_test.go b/os/gres/gres_z_unit_test.go index 6ace54c95..1a1975410 100644 --- a/os/gres/gres_z_unit_test.go +++ b/os/gres/gres_z_unit_test.go @@ -24,7 +24,7 @@ func Test_PackToGoFile(t *testing.T) { gtest.C(t, func(t *gtest.T) { var ( srcPath = gdebug.TestDataPath("files") - goFilePath = gfile.TempDir(gtime.TimestampNanoStr(), "testdata.go") + goFilePath = gfile.Temp(gtime.TimestampNanoStr(), "testdata.go") pkgName = "testdata" err = gres.PackToGoFile(srcPath, goFilePath, pkgName) ) @@ -52,7 +52,7 @@ func Test_PackToFile(t *testing.T) { gtest.C(t, func(t *gtest.T) { var ( srcPath = gdebug.TestDataPath("files") - dstPath = gfile.TempDir(gtime.TimestampNanoStr()) + dstPath = gfile.Temp(gtime.TimestampNanoStr()) err = gres.PackToFile(srcPath, dstPath) ) t.Assert(err, nil) @@ -70,7 +70,7 @@ func Test_PackMulti(t *testing.T) { gtest.C(t, func(t *gtest.T) { var ( srcPath = gdebug.TestDataPath("files") - goFilePath = gfile.TempDir(gtime.TimestampNanoStr(), "data.go") + goFilePath = gfile.Temp(gtime.TimestampNanoStr(), "data.go") pkgName = "data" array, err = gfile.ScanDir(srcPath, "*", false) ) @@ -85,7 +85,7 @@ func Test_PackWithPrefix1(t *testing.T) { gtest.C(t, func(t *gtest.T) { var ( srcPath = gdebug.TestDataPath("files") - goFilePath = gfile.TempDir(gtime.TimestampNanoStr(), "testdata.go") + goFilePath = gfile.Temp(gtime.TimestampNanoStr(), "testdata.go") pkgName = "testdata" err = gres.PackToGoFile(srcPath, goFilePath, pkgName, "www/gf-site/test") ) @@ -98,7 +98,7 @@ func Test_PackWithPrefix2(t *testing.T) { gtest.C(t, func(t *gtest.T) { var ( srcPath = gdebug.TestDataPath("files") - goFilePath = gfile.TempDir(gtime.TimestampNanoStr(), "testdata.go") + goFilePath = gfile.Temp(gtime.TimestampNanoStr(), "testdata.go") pkgName = "testdata" err = gres.PackToGoFile(srcPath, goFilePath, pkgName, "/var/www/gf-site/test") ) @@ -237,7 +237,7 @@ func Test_Export(t *testing.T) { gtest.C(t, func(t *gtest.T) { var ( src = `template` - dst = gfile.TempDir(gtime.TimestampNanoStr()) + dst = gfile.Temp(gtime.TimestampNanoStr()) err = gres.Export(src, dst) ) defer gfile.Remove(dst) @@ -252,7 +252,7 @@ func Test_Export(t *testing.T) { gtest.C(t, func(t *gtest.T) { var ( src = `template` - dst = gfile.TempDir(gtime.TimestampNanoStr()) + dst = gfile.Temp(gtime.TimestampNanoStr()) err = gres.Export(src, dst, gres.ExportOption{ RemovePrefix: `template`, }) diff --git a/os/gsession/gsession_storage_file.go b/os/gsession/gsession_storage_file.go index 428322844..ae2411b91 100644 --- a/os/gsession/gsession_storage_file.go +++ b/os/gsession/gsession_storage_file.go @@ -38,7 +38,7 @@ const ( ) var ( - DefaultStorageFilePath = gfile.TempDir("gsessions") + DefaultStorageFilePath = gfile.Temp("gsessions") DefaultStorageFileCryptoKey = []byte("Session storage file crypto key!") ) diff --git a/os/gview/gview_z_unit_test.go b/os/gview/gview_z_unit_test.go index 771094afa..8d7f31833 100644 --- a/os/gview/gview_z_unit_test.go +++ b/os/gview/gview_z_unit_test.go @@ -222,7 +222,7 @@ func Test_FuncInclude(t *testing.T) { layout = `{{include "header.html" .}} {{include "main.html" .}} {{include "footer.html" .}}` - templatePath = gfile.TempDir("template") + templatePath = gfile.Temp("template") ) gfile.Mkdir(templatePath) @@ -294,7 +294,7 @@ func Test_ParseContent(t *testing.T) { func Test_HotReload(t *testing.T) { gtest.C(t, func(t *gtest.T) { dirPath := gfile.Join( - gfile.TempDir(), + gfile.Temp(), "testdata", "template-"+gconv.String(gtime.TimestampNano()), ) From 23c00eb83f2642bc17a6a311060bc2134bda9206 Mon Sep 17 00:00:00 2001 From: John Guo Date: Mon, 14 Feb 2022 16:08:26 +0800 Subject: [PATCH 3/8] fix issue #1394 --- container/gring/gring.go | 7 +++-- container/gring/gring_z_unit_test.go | 46 ++++++++++++++++++++++++++++ database/gdb/gdb_model_select.go | 21 ++++++------- os/gview/gview_parse.go | 6 ++-- 4 files changed, 64 insertions(+), 16 deletions(-) diff --git a/container/gring/gring.go b/container/gring/gring.go index 08c4e51ab..9a06d576a 100644 --- a/container/gring/gring.go +++ b/container/gring/gring.go @@ -171,10 +171,13 @@ func (r *Ring) Link(s *Ring) *Ring { // func (r *Ring) Unlink(n int) *Ring { r.mu.Lock() - r.ring = r.ring.Unlink(n) + resultRing := r.ring.Unlink(n) r.dirty.Set(true) r.mu.Unlock() - return r + resultGRing := New(resultRing.Len()) + resultGRing.ring = resultRing + resultGRing.dirty.Set(true) + return resultGRing } // RLockIteratorNext iterates and locks reading forward diff --git a/container/gring/gring_z_unit_test.go b/container/gring/gring_z_unit_test.go index 815f73622..55007ce26 100644 --- a/container/gring/gring_z_unit_test.go +++ b/container/gring/gring_z_unit_test.go @@ -7,6 +7,7 @@ package gring_test import ( + "container/ring" "testing" "github.com/gogf/gf/v2/container/gring" @@ -137,3 +138,48 @@ func TestRing_Slice(t *testing.T) { t.Assert(array4, g.Slice{1, 5, 4, 3, 2}) }) } + +// https://github.com/gogf/gf/issues/1394 +func Test_Issue1394(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + // gring. + gRing := gring.New(10) + for i := 0; i < 10; i++ { + gRing.Put(i) + } + t.Logf("the length:%d", gRing.Len()) + gRingResult := gRing.Unlink(6) + for i := 0; i < 10; i++ { + t.Log(gRing.Val()) + gRing = gRing.Next() + } + t.Logf("the ring length:%d", gRing.Len()) + t.Logf("the result length:%d", gRingResult.Len()) + + // stdring + stdRing := ring.New(10) + for i := 0; i < 10; i++ { + stdRing.Value = i + stdRing = stdRing.Next() + } + t.Logf("the length:%d", stdRing.Len()) + stdRingResult := stdRing.Unlink(6) + for i := 0; i < 10; i++ { + t.Log(stdRing.Value) + stdRing = stdRing.Next() + } + t.Logf("the ring length:%d", stdRing.Len()) + t.Logf("the result length:%d", stdRingResult.Len()) + + // Assertion. + t.Assert(gRing.Len(), stdRing.Len()) + t.Assert(gRingResult.Len(), stdRingResult.Len()) + + for i := 0; i < 10; i++ { + t.Assert(stdRing.Value, gRing.Val()) + stdRing = stdRing.Next() + gRing = gRing.Next() + } + }) + +} diff --git a/database/gdb/gdb_model_select.go b/database/gdb/gdb_model_select.go index 491b9c082..e1ce7e64d 100644 --- a/database/gdb/gdb_model_select.go +++ b/database/gdb/gdb_model_select.go @@ -504,6 +504,7 @@ func (m *Model) Having(having interface{}, args ...interface{}) *Model { // doGetAllBySql does the select statement on the database. func (m *Model) doGetAllBySql(sql string, args ...interface{}) (result Result, err error) { var ( + ok bool ctx = m.GetCtx() cacheKey = "" cacheObj = m.db.GetCache() @@ -512,20 +513,18 @@ func (m *Model) doGetAllBySql(sql string, args ...interface{}) (result Result, e if m.cacheEnabled && m.tx == nil { cacheKey = m.cacheOption.Name if len(cacheKey) == 0 { - cacheKey = "gcache:" + gmd5.MustEncryptString(sql+", @PARAMS:"+gconv.String(args)) + cacheKey = "GCache:" + gmd5.MustEncryptString(sql+", @PARAMS:"+gconv.String(args)) } if v, _ := cacheObj.Get(ctx, cacheKey); !v.IsNil() { - if result, ok := v.Val().(Result); ok { + if result, ok = v.Val().(Result); ok { // In-memory cache. return result, nil + } + // Other cache, it needs conversion. + if err = json.UnmarshalUseNumber(v.Bytes(), &result); err != nil { + return nil, err } else { - // Other cache, it needs conversion. - var result Result - if err = json.UnmarshalUseNumber(v.Bytes(), &result); err != nil { - return nil, err - } else { - return result, nil - } + return result, nil } } } @@ -535,7 +534,7 @@ func (m *Model) doGetAllBySql(sql string, args ...interface{}) (result Result, e // Cache the result. if cacheKey != "" && err == nil { if m.cacheOption.Duration < 0 { - if _, err := cacheObj.Remove(ctx, cacheKey); err != nil { + if _, err = cacheObj.Remove(ctx, cacheKey); err != nil { intlog.Errorf(m.GetCtx(), `%+v`, err) } } else { @@ -543,7 +542,7 @@ func (m *Model) doGetAllBySql(sql string, args ...interface{}) (result Result, e if result.IsEmpty() && m.cacheOption.Force { result = Result{} } - if err := cacheObj.Set(ctx, cacheKey, result, m.cacheOption.Duration); err != nil { + if err = cacheObj.Set(ctx, cacheKey, result, m.cacheOption.Duration); err != nil { intlog.Errorf(m.GetCtx(), `%+v`, err) } } diff --git a/os/gview/gview_parse.go b/os/gview/gview_parse.go index 8fb8a0c38..943d9c232 100644 --- a/os/gview/gview_parse.go +++ b/os/gview/gview_parse.go @@ -80,7 +80,7 @@ func (view *View) Parse(ctx context.Context, file string, params ...Params) (res } // Monitor template files changes using fsnotify asynchronously. if resource == nil { - if _, err := gfsnotify.AddOnce("gview.Parse:"+folder, folder, func(event *gfsnotify.Event) { + if _, err = gfsnotify.AddOnce("gview.Parse:"+folder, folder, func(event *gfsnotify.Event) { // CLEAR THEM ALL. view.fileCacheMap.Clear() templates.Clear() @@ -137,11 +137,11 @@ func (view *View) Parse(ctx context.Context, file string, params ...Params) (res if err != nil { return "", err } - if err := newTpl.Execute(buffer, variables); err != nil { + if err = newTpl.Execute(buffer, variables); err != nil { return "", err } } else { - if err := tpl.(*texttpl.Template).Execute(buffer, variables); err != nil { + if err = tpl.(*texttpl.Template).Execute(buffer, variables); err != nil { return "", err } } From 14268aa1c05375b9b56f10853625f0d88154d0c1 Mon Sep 17 00:00:00 2001 From: John Guo Date: Mon, 14 Feb 2022 16:33:07 +0800 Subject: [PATCH 4/8] fix issue #1405 --- database/gdb/gdb_model.go | 2 +- database/gdb/gdb_model_with.go | 13 +++++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/database/gdb/gdb_model.go b/database/gdb/gdb_model.go index 29fabe314..c51fe2d7b 100644 --- a/database/gdb/gdb_model.go +++ b/database/gdb/gdb_model.go @@ -42,7 +42,7 @@ type Model struct { filter bool // Filter data and where key-value pairs according to the fields of the table. distinct string // Force the query to only return distinct results. lockInfo string // Lock for update or in shared lock. - cacheEnabled bool // Enable sql result cache feature. + cacheEnabled bool // Enable sql result cache feature, which is mainly for indicating cache duration(especially 0) usage. cacheOption CacheOption // Cache option for query statement. unscoped bool // Disables soft deleting features when select/delete operations. safe bool // If true, it clones and returns a new model object whenever operation done; or else it changes the attribute of current model. diff --git a/database/gdb/gdb_model_with.go b/database/gdb/gdb_model_with.go index 7390230b8..a14955778 100644 --- a/database/gdb/gdb_model_with.go +++ b/database/gdb/gdb_model_with.go @@ -156,7 +156,13 @@ func (m *Model) doWithScanStruct(pointer interface{}) error { if parsedTagOutput.Order != "" { model = model.Order(parsedTagOutput.Order) } - err = model.Fields(fieldKeys).Where(relatedSourceName, relatedTargetValue).Scan(bindToReflectValue) + // With cache feature. + if m.cacheEnabled && m.cacheOption.Name == "" { + model = model.Cache(m.cacheOption) + } + err = model.Fields(fieldKeys). + Where(relatedSourceName, relatedTargetValue). + Scan(bindToReflectValue) // It ignores sql.ErrNoRows in with feature. if err != nil && err != sql.ErrNoRows { return err @@ -263,7 +269,10 @@ func (m *Model) doWithScanStructs(pointer interface{}) error { if parsedTagOutput.Order != "" { model = model.Order(parsedTagOutput.Order) } - + // With cache feature. + if m.cacheEnabled && m.cacheOption.Name == "" { + model = model.Cache(m.cacheOption) + } err = model.Fields(fieldKeys). Where(relatedSourceName, relatedTargetValue). ScanList(pointer, fieldName, parsedTagOutput.With) From 887cad3b96a7889d219a377fe092f91bfe298952 Mon Sep 17 00:00:00 2001 From: John Guo Date: Mon, 14 Feb 2022 17:04:14 +0800 Subject: [PATCH 5/8] fix issue #1458 --- contrib/drivers/mssql/mssql.go | 23 +++++++++++++---------- contrib/drivers/pgsql/pgsql.go | 7 +++---- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/contrib/drivers/mssql/mssql.go b/contrib/drivers/mssql/mssql.go index 1c440efa3..c5ff3d6e3 100644 --- a/contrib/drivers/mssql/mssql.go +++ b/contrib/drivers/mssql/mssql.go @@ -134,11 +134,12 @@ func (d *DriverMssql) parseSql(sql string) string { if err != nil { return "" } - index := 0 - keyword := strings.TrimSpace(res[index][0]) - keyword = strings.ToUpper(keyword) + var ( + index = 0 + keyword = strings.TrimSpace(res[index][0]) + ) index++ - switch keyword { + switch strings.ToUpper(keyword) { case "SELECT": // LIMIT statement checks. if len(res) < 2 || @@ -150,9 +151,11 @@ func (d *DriverMssql) parseSql(sql string) string { break } // ORDER BY statement checks. - selectStr := "" - orderStr := "" - haveOrder := gregex.IsMatchString("((?i)SELECT)(.+)((?i)ORDER BY)", sql) + var ( + selectStr = "" + orderStr = "" + haveOrder = gregex.IsMatchString("((?i)SELECT)(.+)((?i)ORDER BY)", sql) + ) if haveOrder { queryExpr, _ := gregex.MatchString("((?i)SELECT)(.+)((?i)ORDER BY)", sql) if len(queryExpr) != 4 || @@ -283,7 +286,7 @@ LEFT JOIN sys.extended_properties g ON a.id=g.major_id AND a.colid=g.minor_id LEFT JOIN sys.extended_properties f ON d.id=f.major_id AND f.minor_id =0 WHERE d.name='%s' ORDER BY a.id,a.colorder`, - strings.ToUpper(table), + table, ) structureSql, _ = gregex.ReplaceString(`[\n\r\s]+`, " ", gstr.Trim(structureSql)) result, err = d.DoGetAll(ctx, link, structureSql) @@ -294,8 +297,8 @@ ORDER BY a.id,a.colorder`, for i, m := range result { fields[strings.ToLower(m["Field"].String())] = &gdb.TableField{ Index: i, - Name: strings.ToLower(m["Field"].String()), - Type: strings.ToLower(m["Type"].String()), + Name: m["Field"].String(), + Type: m["Type"].String(), Null: m["Null"].Bool(), Key: m["Key"].String(), Default: m["Default"].Val(), diff --git a/contrib/drivers/pgsql/pgsql.go b/contrib/drivers/pgsql/pgsql.go index 5ed9af2f6..396cdd1b5 100644 --- a/contrib/drivers/pgsql/pgsql.go +++ b/contrib/drivers/pgsql/pgsql.go @@ -13,13 +13,12 @@ package pgsql import ( - _ "github.com/lib/pq" - "context" "database/sql" "database/sql/driver" "fmt" - "strings" + + _ "github.com/lib/pq" "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/database/gdb" @@ -180,7 +179,7 @@ FROM pg_attribute a left join information_schema.columns ic on ic.column_name = a.attname and ic.table_name = c.relname WHERE c.relname = '%s' and a.attisdropped is false and a.attnum > 0 ORDER BY a.attnum`, - strings.ToLower(table), + table, ) ) if link, err = d.SlaveLink(useSchema); err != nil { From 01ba56c38b5bc1fa9c038aebd83fa2a2224a695a Mon Sep 17 00:00:00 2001 From: John Guo Date: Mon, 14 Feb 2022 17:20:27 +0800 Subject: [PATCH 6/8] remove function Set for package gcfg --- os/gcfg/gcfg.go | 43 +++++++------------------------ os/gcfg/gcfg_z_unit_basic_test.go | 19 -------------- 2 files changed, 9 insertions(+), 53 deletions(-) diff --git a/os/gcfg/gcfg.go b/os/gcfg/gcfg.go index 19b624795..74cad55d0 100644 --- a/os/gcfg/gcfg.go +++ b/os/gcfg/gcfg.go @@ -11,7 +11,6 @@ import ( "context" "fmt" - "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" @@ -24,7 +23,6 @@ import ( // Config is the configuration management object. type Config struct { adapter Adapter - dataMap *gmap.StrAnyMap } const ( @@ -39,7 +37,6 @@ func New() (*Config, error) { } return &Config{ adapter: adapterFile, - dataMap: gmap.NewStrAnyMap(true), }, nil } @@ -47,7 +44,6 @@ func New() (*Config, error) { func NewWithAdapter(adapter Adapter) *Config { return &Config{ adapter: adapter, - dataMap: gmap.NewStrAnyMap(true), } } @@ -103,13 +99,6 @@ func (c *Config) Available(ctx context.Context, resource ...string) (ok bool) { return c.adapter.Available(ctx, resource...) } -// Set sets value with specified `pattern`. -// It supports hierarchical data access by char separator, which is '.' in default. -// It is commonly used for updates certain configuration value in runtime. -func (c *Config) Set(ctx context.Context, pattern string, value interface{}) { - c.dataMap.Set(pattern, value) -} - // Get retrieves and returns value by specified `pattern`. // It returns all values of current Json object if `pattern` is given empty or string ".". // It returns nil if no value found by `pattern`. @@ -120,17 +109,15 @@ func (c *Config) Get(ctx context.Context, pattern string, def ...interface{}) (* err error value interface{} ) - if value = c.dataMap.Get(pattern); value == nil { - value, err = c.adapter.Get(ctx, pattern) - if err != nil { - return nil, err - } - if value == nil { - if len(def) > 0 { - return gvar.New(def[0]), nil - } - return nil, nil + value, err = c.adapter.Get(ctx, pattern) + if err != nil { + return nil, err + } + if value == nil { + if len(def) > 0 { + return gvar.New(def[0]), nil } + return nil, nil } return gvar.New(value), nil } @@ -181,19 +168,7 @@ func (c *Config) GetWithCmd(ctx context.Context, pattern string, def ...interfac // Data retrieves and returns all configuration data as map type. func (c *Config) Data(ctx context.Context) (data map[string]interface{}, err error) { - adapterData, err := c.adapter.Data(ctx) - if err != nil { - return nil, err - } - data = make(map[string]interface{}) - for k, v := range adapterData { - data[k] = v - } - c.dataMap.Iterator(func(k string, v interface{}) bool { - data[k] = v - return true - }) - return + return c.adapter.Data(ctx) } // MustGet acts as function Get, but it panics if error occurs. diff --git a/os/gcfg/gcfg_z_unit_basic_test.go b/os/gcfg/gcfg_z_unit_basic_test.go index 0400c93fb..c9c11d24f 100644 --- a/os/gcfg/gcfg_z_unit_basic_test.go +++ b/os/gcfg/gcfg_z_unit_basic_test.go @@ -146,25 +146,6 @@ func Test_SetFileName(t *testing.T) { }) } -func TestCfg_Set(t *testing.T) { - config := `log-path = "logs"` - gtest.C(t, func(t *gtest.T) { - path := gcfg.DefaultConfigFile - err := gfile.PutContents(path, config) - t.Assert(err, nil) - defer gfile.Remove(path) - - adapterFile, err := gcfg.NewAdapterFile() - t.AssertNil(err) - t.Assert(adapterFile.MustGet(ctx, "log-path"), "logs") - - c := gcfg.NewWithAdapter(adapterFile) - c.Set(ctx, "log-path", "custom-logs") - t.Assert(err, nil) - t.Assert(c.MustGet(ctx, "log-path"), "custom-logs") - }) -} - func TestCfg_Get_WrongConfigFile(t *testing.T) { gtest.C(t, func(t *gtest.T) { var err error From 2428b27168b05234250cbaa60cb11fe3adbb60ba Mon Sep 17 00:00:00 2001 From: John Guo Date: Tue, 15 Feb 2022 00:21:05 +0800 Subject: [PATCH 7/8] fix issue #1488 --- net/ghttp/ghttp_request_param_param.go | 10 ++++ ...http_z_unit_feature_request_struct_test.go | 47 +++++++++++++++++++ os/gstructs/gstructs.go | 12 +++-- os/gstructs/gstructs_tag.go | 5 +- util/gconv/gconv.go | 4 +- util/gconv/gconv_struct.go | 12 +++-- 6 files changed, 81 insertions(+), 9 deletions(-) diff --git a/net/ghttp/ghttp_request_param_param.go b/net/ghttp/ghttp_request_param_param.go index b5a625d71..1cb86c985 100644 --- a/net/ghttp/ghttp_request_param_param.go +++ b/net/ghttp/ghttp_request_param_param.go @@ -16,6 +16,16 @@ func (r *Request) SetParam(key string, value interface{}) { r.paramsMap[key] = value } +// SetParamMap sets custom parameter with key-value pair map. +func (r *Request) SetParamMap(data map[string]interface{}) { + if r.paramsMap == nil { + r.paramsMap = make(map[string]interface{}) + } + for k, v := range data { + r.paramsMap[k] = v + } +} + // GetParam returns custom parameter with given name `key`. // It returns `def` if `key` does not exist. // It returns nil if `def` is not passed. diff --git a/net/ghttp/ghttp_z_unit_feature_request_struct_test.go b/net/ghttp/ghttp_z_unit_feature_request_struct_test.go index b470addf3..45673c7f8 100644 --- a/net/ghttp/ghttp_z_unit_feature_request_struct_test.go +++ b/net/ghttp/ghttp_z_unit_feature_request_struct_test.go @@ -527,3 +527,50 @@ func Test_Params_Struct_Validation(t *testing.T) { t.Assert(c.PostContent(ctx, "/", `id=1`), `The name field is required`) }) } + +// https://github.com/gogf/gf/issues/1488 +func Test_Params_Parse_Issue1488(t *testing.T) { + p, _ := gtcp.GetFreePort() + s := g.Server(p) + s.Group("/", func(group *ghttp.RouterGroup) { + group.ALL("/", func(r *ghttp.Request) { + type Request struct { + Type []int `p:"type"` + Keyword string `p:"keyword"` + Limit int `p:"per_page" d:"10"` + Page int `p:"page" d:"1"` + Order string + CreatedAtLte string + CreatedAtGte string + CreatorID []int + } + for i := 0; i < 10; i++ { + r.SetParamMap(g.Map{ + "type[]": 0, + "keyword": "", + "t_start": "", + "t_end": "", + "reserve_at_start": "", + "reserve_at_end": "", + "user_name": "", + "flag": "", + "per_page": 6, + }) + var parsed Request + _ = r.Parse(&parsed) + r.Response.Write(parsed.Page, parsed.Limit) + } + }) + }) + s.SetPort(p) + s.SetDumpRouterMap(false) + s.Start() + defer s.Shutdown() + + time.Sleep(100 * time.Millisecond) + gtest.C(t, func(t *gtest.T) { + c := g.Client() + c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p)) + t.Assert(c.GetContent(ctx, "/", ``), `16161616161616161616`) + }) +} diff --git a/os/gstructs/gstructs.go b/os/gstructs/gstructs.go index de1b40b46..b44cbccac 100644 --- a/os/gstructs/gstructs.go +++ b/os/gstructs/gstructs.go @@ -18,9 +18,15 @@ type Type struct { // Field contains information of a struct field . type Field struct { - Value reflect.Value // The underlying value of the field. - Field reflect.StructField // The underlying field of the field. - TagValue string // Retrieved tag value. There might be more than one tags in the field, but only one can be retrieved according to calling function rules. + Value reflect.Value // The underlying value of the field. + Field reflect.StructField // The underlying field of the field. + + // Retrieved tag name. It depends TagValue. + TagName string + + // Retrieved tag value. + // There might be more than one tags in the field, but only one can be retrieved according to calling function rules. + TagValue string } // FieldsInput is the input parameter struct type for function Fields. diff --git a/os/gstructs/gstructs_tag.go b/os/gstructs/gstructs_tag.go index d513fa9af..fdc563df8 100644 --- a/os/gstructs/gstructs_tag.go +++ b/os/gstructs/gstructs_tag.go @@ -180,7 +180,8 @@ func getFieldValuesByTagPriority(pointer interface{}, priority []string, tagMap return nil, err } var ( - tagValue = "" + tagName string + tagValue string tagFields = make([]Field, 0) ) for _, field := range fields { @@ -190,6 +191,7 @@ func getFieldValuesByTagPriority(pointer interface{}, priority []string, tagMap } tagValue = "" for _, p := range priority { + tagName = p tagValue = field.Tag(p) if tagValue != "" && tagValue != "-" { break @@ -201,6 +203,7 @@ func getFieldValuesByTagPriority(pointer interface{}, priority []string, tagMap continue } tagField := field + tagField.TagName = tagName tagField.TagValue = tagValue tagFields = append(tagFields, tagField) } diff --git a/util/gconv/gconv.go b/util/gconv/gconv.go index 47754a3df..c426ddf78 100644 --- a/util/gconv/gconv.go +++ b/util/gconv/gconv.go @@ -34,8 +34,8 @@ var ( } // StructTagPriority defines the default priority tags for Map*/Struct* functions. - // Note, the "gconv", "param", "params" tags are used by old version of package. - // It is strongly recommended using short tag "c" or "p" instead in the future. + // Note, the `gconv/param/params` tags are used by old version of package. + // It is strongly recommended using short tag `c/p` instead in the future. StructTagPriority = []string{"gconv", "param", "params", "c", "p", "json"} ) diff --git a/util/gconv/gconv_struct.go b/util/gconv/gconv_struct.go index 03b3a5839..23a5c2595 100644 --- a/util/gconv/gconv_struct.go +++ b/util/gconv/gconv_struct.go @@ -248,6 +248,12 @@ func doStruct(params interface{}, pointer interface{}, mapping map[string]string // orm:"id, priority" // orm:"name, with:uid=id" tagMap[attributeName] = utils.RemoveSymbols(strings.Split(tagName, ",")[0]) + + // If tag and attribute values both exist in `paramsMap`, + // it then uses the tag value overwriting the attribute value in `paramsMap`. + if paramsMap[tagName] != nil && paramsMap[attributeName] != nil { + paramsMap[attributeName] = paramsMap[tagName] + } } var ( @@ -269,7 +275,7 @@ func doStruct(params interface{}, pointer interface{}, mapping map[string]string // string cases and chars like '-'/'_'/'.'/' '. // Matching the parameters to struct tag names. - // The `tagV` is the attribute name of the struct. + // The `attrKey` is the attribute name of the struct. for attrKey, cmpKey := range tagMap { if strings.EqualFold(checkName, cmpKey) { attrName = attrKey @@ -297,12 +303,12 @@ func doStruct(params interface{}, pointer interface{}, mapping map[string]string continue } // If the attribute name is already checked converting, then skip it. - if _, ok := doneMap[attrName]; ok { + if _, ok = doneMap[attrName]; ok { continue } // Mark it done. doneMap[attrName] = struct{}{} - if err := bindVarToStructAttr(pointerElemReflectValue, attrName, mapV, mapping); err != nil { + if err = bindVarToStructAttr(pointerElemReflectValue, attrName, mapV, mapping); err != nil { return err } } From f0b78253b2d69bbdbe989e8b3b632f7e35f2e782 Mon Sep 17 00:00:00 2001 From: John Guo Date: Tue, 15 Feb 2022 01:10:03 +0800 Subject: [PATCH 8/8] fix issue #1605 --- database/gredis/gredis_adapter_goredis.go | 8 ++++++++ database/gredis/gredis_config.go | 2 +- database/gredis/gredis_redis.go | 10 ++++++++-- frame/gins/gins_redis.go | 5 +++-- 4 files changed, 20 insertions(+), 5 deletions(-) diff --git a/database/gredis/gredis_adapter_goredis.go b/database/gredis/gredis_adapter_goredis.go index 027d806f3..28ac0ebf1 100644 --- a/database/gredis/gredis_adapter_goredis.go +++ b/database/gredis/gredis_adapter_goredis.go @@ -28,6 +28,7 @@ const ( defaultPoolIdleTimeout = 10 * time.Second defaultPoolWaitTimeout = 10 * time.Second defaultPoolMaxLifeTime = 30 * time.Second + defaultMaxRetries = -1 ) // NewAdapterGoRedis creates and returns a redis adapter using go-redis. @@ -37,6 +38,7 @@ func NewAdapterGoRedis(config *Config) *AdapterGoRedis { Addrs: gstr.SplitAndTrim(config.Address, ","), Password: config.Pass, DB: config.Db, + MaxRetries: defaultMaxRetries, MinIdleConns: config.MinIdle, MaxConnAge: config.MaxConnLifetime, IdleTimeout: config.IdleTimeout, @@ -90,4 +92,10 @@ func fillWithDefaultConfiguration(config *Config) { if config.MaxConnLifetime == 0 { config.MaxConnLifetime = defaultPoolMaxLifeTime } + if config.WriteTimeout == 0 { + config.WriteTimeout = -1 + } + if config.ReadTimeout == 0 { + config.ReadTimeout = -1 + } } diff --git a/database/gredis/gredis_config.go b/database/gredis/gredis_config.go index 26600e124..d381332ff 100644 --- a/database/gredis/gredis_config.go +++ b/database/gredis/gredis_config.go @@ -30,7 +30,7 @@ type Config struct { IdleTimeout time.Duration `json:"idleTimeout"` // Maximum idle time for connection (default is 10 seconds, not allowed to be set to 0) WaitTimeout time.Duration `json:"waitTimeout"` // Timed out duration waiting to get a connection from the connection pool. DialTimeout time.Duration `json:"dialTimeout"` // Dial connection timeout for TCP. - ReadTimeout time.Duration `json:"readTimeout"` // Read timeout for TCP. + ReadTimeout time.Duration `json:"readTimeout"` // Read timeout for TCP. DO NOT set it if not necessary. WriteTimeout time.Duration `json:"writeTimeout"` // Write timeout for TCP. MasterName string `json:"masterName"` // Used in Redis Sentinel mode. TLS bool `json:"tls"` // Specifies whether TLS should be used when connecting to the server. diff --git a/database/gredis/gredis_redis.go b/database/gredis/gredis_redis.go index 445876b74..389a9d4db 100644 --- a/database/gredis/gredis_redis.go +++ b/database/gredis/gredis_redis.go @@ -46,6 +46,12 @@ func (r *Redis) Conn(ctx context.Context) (*RedisConn, error) { if r == nil { return nil, gerror.NewCode(gcode.CodeInvalidParameter, errorNilRedis) } + if r.adapter == nil { + return nil, gerror.NewCodef( + gcode.CodeMissingConfiguration, + `redis adapter not initialized, missing configuration or adapter register?`, + ) + } conn, err := r.adapter.Conn(ctx) if err != nil { return nil, err @@ -67,8 +73,8 @@ func (r *Redis) Do(ctx context.Context, command string, args ...interface{}) (*g return nil, err } defer func() { - if err := conn.Close(ctx); err != nil { - intlog.Errorf(ctx, `%+v`, err) + if closeErr := conn.Close(ctx); closeErr != nil { + intlog.Errorf(ctx, `%+v`, closeErr) } }() return conn.Do(ctx, command, args...) diff --git a/frame/gins/gins_redis.go b/frame/gins/gins_redis.go index 5723b5c88..ea5b2aebb 100644 --- a/frame/gins/gins_redis.go +++ b/frame/gins/gins_redis.go @@ -55,10 +55,11 @@ func Redis(name ...string) *gredis.Redis { if redisConfig, err = gredis.ConfigFromMap(gconv.Map(v)); err != nil { panic(err) } + } else { + intlog.Printf(ctx, `missing configuration for redis group "%s"`, group) } - intlog.Printf(ctx, `missing configuration for redis group "%s"`, group) } else { - intlog.Printf(ctx, `missing configuration for redis: "redis" node not found`) + intlog.Print(ctx, `missing configuration for redis: "redis" node not found`) } if redisClient, err = gredis.New(redisConfig); err != nil { panic(err)