From f3e3a5af5aa356521b36faa9af900c0c03640161 Mon Sep 17 00:00:00 2001 From: houseme Date: Wed, 8 Nov 2023 21:16:23 +0800 Subject: [PATCH 01/52] feat: improve code for shutdown of otel (#3136) --- contrib/trace/otlpgrpc/otlpgrpc.go | 17 ++++++++++++++--- contrib/trace/otlphttp/otlphttp.go | 17 ++++++++++++++--- example/trace/grpc_with_db/client/client.go | 4 ++-- example/trace/grpc_with_db/server/server.go | 4 ++-- example/trace/http/client/client.go | 4 ++-- example/trace/http/server/server.go | 4 ++-- example/trace/http_with_db/client/client.go | 4 ++-- example/trace/http_with_db/server/server.go | 4 ++-- example/trace/inprocess/main.go | 4 ++-- example/trace/otlp/grpc/main.go | 4 ++-- example/trace/otlp/http/main.go | 4 ++-- 11 files changed, 46 insertions(+), 24 deletions(-) diff --git a/contrib/trace/otlpgrpc/otlpgrpc.go b/contrib/trace/otlpgrpc/otlpgrpc.go index b602116cb5a..6c9ae2993b5 100644 --- a/contrib/trace/otlpgrpc/otlpgrpc.go +++ b/contrib/trace/otlpgrpc/otlpgrpc.go @@ -9,8 +9,8 @@ package otlpgrpc import ( "context" + "time" - "github.com/gogf/gf/v2/net/gipv4" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/exporters/otlp/otlptrace" @@ -20,6 +20,9 @@ import ( sdktrace "go.opentelemetry.io/otel/sdk/trace" semconv "go.opentelemetry.io/otel/semconv/v1.20.0" "google.golang.org/grpc" + + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/net/gipv4" ) const ( @@ -30,7 +33,7 @@ const ( // // The output parameter `Shutdown` is used for waiting exported trace spans to be uploaded, // which is useful if your program is ending, and you do not want to lose recent spans. -func Init(serviceName, endpoint, traceToken string) (*sdktrace.TracerProvider, error) { +func Init(serviceName, endpoint, traceToken string) (func(), error) { // Try retrieving host ip for tracing info. var ( intranetIPArray, err = gipv4.GetIntranetIpArray() @@ -87,5 +90,13 @@ func Init(serviceName, endpoint, traceToken string) (*sdktrace.TracerProvider, e otel.SetTextMapPropagator(propagation.TraceContext{}) otel.SetTracerProvider(tracerProvider) - return tracerProvider, nil + return func() { + ctx, cancel := context.WithTimeout(ctx, time.Second) + defer cancel() + if err = traceExp.Shutdown(ctx); err != nil { + g.Log().Errorf(ctx, "Shutdown traceExp failed err:%+v", err) + otel.Handle(err) + } + g.Log().Debug(ctx, "Shutdown traceExp success") + }, nil } diff --git a/contrib/trace/otlphttp/otlphttp.go b/contrib/trace/otlphttp/otlphttp.go index a4c2d210b38..5778074d4e0 100644 --- a/contrib/trace/otlphttp/otlphttp.go +++ b/contrib/trace/otlphttp/otlphttp.go @@ -9,8 +9,8 @@ package otlphttp import ( "context" + "time" - "github.com/gogf/gf/v2/net/gipv4" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/exporters/otlp/otlptrace" @@ -19,6 +19,9 @@ import ( "go.opentelemetry.io/otel/sdk/resource" sdktrace "go.opentelemetry.io/otel/sdk/trace" semconv "go.opentelemetry.io/otel/semconv/v1.20.0" + + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/net/gipv4" ) const ( @@ -29,7 +32,7 @@ const ( // // The output parameter `Shutdown` is used for waiting exported trace spans to be uploaded, // which is useful if your program is ending, and you do not want to lose recent spans. -func Init(serviceName, endpoint, path string) (*sdktrace.TracerProvider, error) { +func Init(serviceName, endpoint, path string) (func(), error) { // Try retrieving host ip for tracing info. var ( intranetIPArray, err = gipv4.GetIntranetIpArray() @@ -85,5 +88,13 @@ func Init(serviceName, endpoint, path string) (*sdktrace.TracerProvider, error) otel.SetTextMapPropagator(propagation.TraceContext{}) otel.SetTracerProvider(tracerProvider) - return tracerProvider, nil + return func() { + ctx, cancel := context.WithTimeout(ctx, time.Second) + defer cancel() + if err = traceExp.Shutdown(ctx); err != nil { + g.Log().Errorf(ctx, "Shutdown traceExp failed err:%+v", err) + otel.Handle(err) + } + g.Log().Debug(ctx, "Shutdown traceExp success") + }, nil } diff --git a/example/trace/grpc_with_db/client/client.go b/example/trace/grpc_with_db/client/client.go index 8ad147a536e..c1b4fcb1126 100644 --- a/example/trace/grpc_with_db/client/client.go +++ b/example/trace/grpc_with_db/client/client.go @@ -20,11 +20,11 @@ func main() { grpcx.Resolver.Register(etcd.New("127.0.0.1:2379")) var ctx = gctx.New() - tp, err := otlpgrpc.Init(serviceName, endpoint, traceToken) + shutdown, err := otlpgrpc.Init(serviceName, endpoint, traceToken) if err != nil { g.Log().Fatal(ctx, err) } - defer tp.Shutdown(ctx) + defer shutdown() StartRequests() } diff --git a/example/trace/grpc_with_db/server/server.go b/example/trace/grpc_with_db/server/server.go index 5a938ce2e57..0a55f2e6b77 100644 --- a/example/trace/grpc_with_db/server/server.go +++ b/example/trace/grpc_with_db/server/server.go @@ -33,11 +33,11 @@ func main() { grpcx.Resolver.Register(etcd.New("127.0.0.1:2379")) var ctx = gctx.New() - tp, err := otlpgrpc.Init(serviceName, endpoint, traceToken) + shutdown, err := otlpgrpc.Init(serviceName, endpoint, traceToken) if err != nil { g.Log().Fatal(ctx, err) } - defer tp.Shutdown(ctx) + defer shutdown() // Set ORM cache adapter with redis. g.DB().GetCache().SetAdapter(gcache.NewAdapterRedis(g.Redis())) diff --git a/example/trace/http/client/client.go b/example/trace/http/client/client.go index 5ebb7cf52ff..254f47c088c 100644 --- a/example/trace/http/client/client.go +++ b/example/trace/http/client/client.go @@ -15,11 +15,11 @@ const ( func main() { var ctx = gctx.New() - tp, err := otlphttp.Init(serviceName, endpoint, path) + shutdown, err := otlphttp.Init(serviceName, endpoint, path) if err != nil { g.Log().Fatal(ctx, err) } - defer tp.Shutdown(ctx) + defer shutdown() StartRequests() } diff --git a/example/trace/http/server/server.go b/example/trace/http/server/server.go index eb0a5be8c6e..2e734ace361 100644 --- a/example/trace/http/server/server.go +++ b/example/trace/http/server/server.go @@ -16,11 +16,11 @@ const ( func main() { var ctx = gctx.New() - tp, err := otlphttp.Init(serviceName, endpoint, path) + shutdown, err := otlphttp.Init(serviceName, endpoint, path) if err != nil { g.Log().Fatal(ctx, err) } - defer tp.Shutdown(ctx) + defer shutdown() s := g.Server() s.Group("/", func(group *ghttp.RouterGroup) { diff --git a/example/trace/http_with_db/client/client.go b/example/trace/http_with_db/client/client.go index bcf766610b5..676d4de9b16 100644 --- a/example/trace/http_with_db/client/client.go +++ b/example/trace/http_with_db/client/client.go @@ -17,11 +17,11 @@ const ( func main() { var ctx = gctx.New() - tp, err := otlphttp.Init(serviceName, endpoint, path) + shutdown, err := otlphttp.Init(serviceName, endpoint, path) if err != nil { g.Log().Fatal(ctx, err) } - defer tp.Shutdown(ctx) + defer shutdown() StartRequests() } diff --git a/example/trace/http_with_db/server/server.go b/example/trace/http_with_db/server/server.go index 3057f7fd630..7c4139a503f 100644 --- a/example/trace/http_with_db/server/server.go +++ b/example/trace/http_with_db/server/server.go @@ -24,11 +24,11 @@ const ( func main() { var ctx = gctx.New() - tp, err := otlphttp.Init(serviceName, endpoint, path) + shutdown, err := otlphttp.Init(serviceName, endpoint, path) if err != nil { g.Log().Fatal(ctx, err) } - defer tp.Shutdown(ctx) + defer shutdown() // Set ORM cache adapter with redis. g.DB().GetCache().SetAdapter(gcache.NewAdapterRedis(g.Redis())) diff --git a/example/trace/inprocess/main.go b/example/trace/inprocess/main.go index ad25fa60ae4..b792094bbbb 100644 --- a/example/trace/inprocess/main.go +++ b/example/trace/inprocess/main.go @@ -18,11 +18,11 @@ const ( func main() { var ctx = gctx.New() - tp, err := otlphttp.Init(serviceName, endpoint, path) + shutdown, err := otlphttp.Init(serviceName, endpoint, path) if err != nil { g.Log().Fatal(ctx, err) } - defer tp.Shutdown(ctx) + defer shutdown() ctx, span := gtrace.NewSpan(ctx, "main") defer span.End() diff --git a/example/trace/otlp/grpc/main.go b/example/trace/otlp/grpc/main.go index 726c1743d71..224ee5fdca2 100644 --- a/example/trace/otlp/grpc/main.go +++ b/example/trace/otlp/grpc/main.go @@ -22,11 +22,11 @@ const ( func main() { var ctx = gctx.New() - tp, err := otlpgrpc.Init(serviceName, endpoint, traceToken) + shutdown, err := otlpgrpc.Init(serviceName, endpoint, traceToken) if err != nil { g.Log().Fatal(ctx, err) } - defer tp.Shutdown(ctx) + defer shutdown() StartRequests() } diff --git a/example/trace/otlp/http/main.go b/example/trace/otlp/http/main.go index 673ebe9d483..b1ad9e5fc11 100644 --- a/example/trace/otlp/http/main.go +++ b/example/trace/otlp/http/main.go @@ -21,11 +21,11 @@ const ( func main() { var ctx = gctx.New() - tp, err := otlphttp.Init(serviceName, endpoint, path) + shutdown, err := otlphttp.Init(serviceName, endpoint, path) if err != nil { g.Log().Fatal(ctx, err) } - defer tp.Shutdown(ctx) + defer shutdown() StartRequests() } From a17849bc39c482480b4db45441251e3e065a80c1 Mon Sep 17 00:00:00 2001 From: John Guo Date: Wed, 8 Nov 2023 21:17:55 +0800 Subject: [PATCH 02/52] improve struct converting in parameter name case sensitive scenario for package `gconv` (#3122) --- net/ghttp/ghttp_request_param.go | 2 + ...ghttp_z_unit_feature_router_strict_test.go | 42 ++++++++ util/gconv/gconv_struct.go | 96 +++++++++++++++++-- 3 files changed, 133 insertions(+), 7 deletions(-) diff --git a/net/ghttp/ghttp_request_param.go b/net/ghttp/ghttp_request_param.go index a3084542bb6..806428ae4e4 100644 --- a/net/ghttp/ghttp_request_param.go +++ b/net/ghttp/ghttp_request_param.go @@ -158,6 +158,8 @@ func (r *Request) GetBody() []byte { return r.bodyContent } +// MakeBodyRepeatableRead marks the request body could be repeatedly readable or not. +// It also returns the current content of the request body. func (r *Request) MakeBodyRepeatableRead(repeatableRead bool) []byte { if r.bodyContent == nil { var err error diff --git a/net/ghttp/ghttp_z_unit_feature_router_strict_test.go b/net/ghttp/ghttp_z_unit_feature_router_strict_test.go index b3f1479ba9a..b528f486368 100644 --- a/net/ghttp/ghttp_z_unit_feature_router_strict_test.go +++ b/net/ghttp/ghttp_z_unit_feature_router_strict_test.go @@ -377,3 +377,45 @@ func Test_Router_Handler_Strict_WithGeneric(t *testing.T) { t.Assert(client.GetContent(ctx, "/test3_slice?age=3"), `{"code":0,"message":"","data":[{"Test":3}]}`) }) } + +type ParameterCaseSensitiveController struct{} + +type ParameterCaseSensitiveControllerPathReq struct { + g.Meta `path:"/api/*path" method:"post"` + Path string +} + +type ParameterCaseSensitiveControllerPathRes struct { + Path string +} + +func (c *ParameterCaseSensitiveController) Path( + ctx context.Context, + req *ParameterCaseSensitiveControllerPathReq, +) (res *ParameterCaseSensitiveControllerPathRes, err error) { + return &ParameterCaseSensitiveControllerPathRes{Path: req.Path}, nil +} + +func Test_Router_Handler_Strict_ParameterCaseSensitive(t *testing.T) { + s := g.Server(guid.S()) + s.Use(ghttp.MiddlewareHandlerResponse) + s.Group("/", func(group *ghttp.RouterGroup) { + group.Bind(&ParameterCaseSensitiveController{}) + }) + s.SetDumpRouterMap(false) + s.Start() + defer s.Shutdown() + + time.Sleep(100 * time.Millisecond) + gtest.C(t, func(t *gtest.T) { + client := g.Client() + client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", s.GetListenedPort())) + + for i := 0; i < 1000; i++ { + t.Assert( + client.PostContent(ctx, "/api/111", `{"Path":"222"}`), + `{"code":0,"message":"","data":{"Path":"222"}}`, + ) + } + }) +} diff --git a/util/gconv/gconv_struct.go b/util/gconv/gconv_struct.go index 2c6433584ce..b3554ba5506 100644 --- a/util/gconv/gconv_struct.go +++ b/util/gconv/gconv_struct.go @@ -228,10 +228,12 @@ func doStruct(params interface{}, pointer interface{}, mapping map[string]string // The key of the attrMap is the attribute name of the struct, // and the value is its replaced name for later comparison to improve performance. var ( - tempName string - elemFieldType reflect.StructField - elemFieldValue reflect.Value - elemType = pointerElemReflectValue.Type() + tempName string + elemFieldType reflect.StructField + elemFieldValue reflect.Value + elemType = pointerElemReflectValue.Type() + // Attribute name to its symbols-removed name, + // in order to quick index and comparison in following logic. attrToCheckNameMap = make(map[string]string) ) for i := 0; i < pointerElemReflectValue.NumField(); i++ { @@ -290,7 +292,84 @@ func doStruct(params interface{}, pointer interface{}, mapping map[string]string paramsMap[attributeName] = paramsMap[tagName] } } + // To convert value base on precise attribute name. + err = doStructBaseOnAttribute( + pointerElemReflectValue, + paramsMap, + mapping, + doneMap, + attrToCheckNameMap, + ) + if err != nil { + return err + } + // Already done all attributes value assignment nothing to do next. + if len(doneMap) == len(attrToCheckNameMap) { + return nil + } + // To convert value base on parameter map. + err = doStructBaseOnParamMap( + pointerElemReflectValue, + paramsMap, + mapping, + doneMap, + attrToCheckNameMap, + attrToTagCheckNameMap, + tagToAttrNameMap, + ) + if err != nil { + return err + } + return nil +} +func doStructBaseOnAttribute( + pointerElemReflectValue reflect.Value, + paramsMap map[string]interface{}, + mapping map[string]string, + doneMap map[string]struct{}, + attrToCheckNameMap map[string]string, +) error { + var customMappingAttrMap = make(map[string]struct{}) + if len(mapping) > 0 { + for paramName := range paramsMap { + if passedAttrKey, ok := mapping[paramName]; ok { + customMappingAttrMap[passedAttrKey] = struct{}{} + } + } + } + for attrName := range attrToCheckNameMap { + // The value by precise attribute name. + paramValue, ok := paramsMap[attrName] + if !ok { + continue + } + // If the attribute name is in custom mapping, it then ignores this converting. + if _, ok = customMappingAttrMap[attrName]; ok { + continue + } + // If the attribute name is already checked converting, then skip it. + if _, ok = doneMap[attrName]; ok { + continue + } + // Mark it done. + doneMap[attrName] = struct{}{} + if err := bindVarToStructAttr(pointerElemReflectValue, attrName, paramValue, mapping); err != nil { + return err + } + } + return nil +} + +func doStructBaseOnParamMap( + pointerElemReflectValue reflect.Value, + paramsMap map[string]interface{}, + mapping map[string]string, + doneMap map[string]struct{}, + attrToCheckNameMap map[string]string, + attrToTagCheckNameMap map[string]string, + tagToAttrNameMap map[string]string, +) error { var ( attrName string checkName string @@ -344,12 +423,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, paramValue, mapping); err != nil { + if err := bindVarToStructAttr(pointerElemReflectValue, attrName, paramValue, mapping); err != nil { return err } } @@ -357,7 +436,10 @@ func doStruct(params interface{}, pointer interface{}, mapping map[string]string } // bindVarToStructAttr sets value to struct object attribute by name. -func bindVarToStructAttr(structReflectValue reflect.Value, attrName string, value interface{}, mapping map[string]string) (err error) { +func bindVarToStructAttr( + structReflectValue reflect.Value, + attrName string, value interface{}, mapping map[string]string, +) (err error) { structFieldValue := structReflectValue.FieldByName(attrName) if !structFieldValue.IsValid() { return nil From 5f5b82188cd7248a6cb2500358009cbb6b7fbae7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B5=B7=E4=BA=AE?= <739476267@qq.com> Date: Wed, 8 Nov 2023 21:23:39 +0800 Subject: [PATCH 03/52] example: log rotate (#3137) --- example/os/log/rotate/config.toml | 8 ++++++++ example/os/log/rotate/main.go | 23 +++++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 example/os/log/rotate/config.toml create mode 100644 example/os/log/rotate/main.go diff --git a/example/os/log/rotate/config.toml b/example/os/log/rotate/config.toml new file mode 100644 index 00000000000..623e47935c5 --- /dev/null +++ b/example/os/log/rotate/config.toml @@ -0,0 +1,8 @@ +[logger] +path = "./log" +file = "{Y-m-d-H-i}.log" +level = "all" +stdout = true +rotateExpire = "1m" +rotateBackupLimit = 4 +rotateCheckInterval = "5s" diff --git a/example/os/log/rotate/main.go b/example/os/log/rotate/main.go new file mode 100644 index 00000000000..5a3fcbf2f4f --- /dev/null +++ b/example/os/log/rotate/main.go @@ -0,0 +1,23 @@ +package main + +import ( + "context" + "time" + + "github.com/gogf/gf/v2/frame/g" +) + +func main() { + ctx := context.Background() + mylog := g.Log() + for { + mylog.Debug(ctx, "debug") + time.Sleep(time.Second) + mylog.Info(ctx, "info") + time.Sleep(time.Second) + mylog.Warning(ctx, "warning") + time.Sleep(time.Second) + mylog.Error(ctx, "error") + time.Sleep(time.Second) + } +} From 0b407c5e6d2dcc9094e26281f265077aa5c3a472 Mon Sep 17 00:00:00 2001 From: Hunk Zhu Date: Wed, 8 Nov 2023 21:26:51 +0800 Subject: [PATCH 04/52] fix "gf gen pb" api and ctrl not working well. (#3076) --- contrib/drivers/clickhouse/clickhouse.go | 2 +- contrib/drivers/mysql/mysql_model_test.go | 2 +- contrib/drivers/sqlite/sqlite_model_test.go | 2 +- contrib/drivers/sqlitecgo/sqlite_model_test.go | 2 +- database/gdb/gdb_core.go | 6 +++--- database/gdb/gdb_core_config.go | 6 +++--- database/gdb/gdb_model_select.go | 2 +- database/gdb/gdb_model_time.go | 12 ++++++------ database/gdb/gdb_type_result_scanlist.go | 6 +++--- os/gcmd/gcmd_command.go | 11 ++++++----- os/gcmd/gcmd_command_object.go | 7 ++++++- os/gcmd/gcmd_command_run.go | 8 +++++--- os/gcmd/gcmd_z_unit_feature_object1_test.go | 15 ++++++++++++++- util/gconv/gconv_scan.go | 6 +++--- 14 files changed, 54 insertions(+), 33 deletions(-) diff --git a/contrib/drivers/clickhouse/clickhouse.go b/contrib/drivers/clickhouse/clickhouse.go index 059e9afff8c..33665c0ebda 100644 --- a/contrib/drivers/clickhouse/clickhouse.go +++ b/contrib/drivers/clickhouse/clickhouse.go @@ -163,7 +163,7 @@ func (d *Driver) TableFields(ctx context.Context, table string, schema ...string isNull = false fieldType = m["type"].String() ) - // in clickhouse , filed type like is Nullable(int) + // in clickhouse , field type like is Nullable(int) fieldsResult, _ := gregex.MatchString(`^Nullable\((.*?)\)`, fieldType) if len(fieldsResult) == 2 { isNull = true diff --git a/contrib/drivers/mysql/mysql_model_test.go b/contrib/drivers/mysql/mysql_model_test.go index 0aa8d494aaa..230100f760b 100644 --- a/contrib/drivers/mysql/mysql_model_test.go +++ b/contrib/drivers/mysql/mysql_model_test.go @@ -4118,7 +4118,7 @@ func Test_Model_Embedded_Filter(t *testing.T) { // Password string // Nickname string // CreateTime string -// NoneExistFiled string +// NoneExistField string // } // data := User{ // Id: 1, diff --git a/contrib/drivers/sqlite/sqlite_model_test.go b/contrib/drivers/sqlite/sqlite_model_test.go index cd260bc5747..f39804f1ef6 100644 --- a/contrib/drivers/sqlite/sqlite_model_test.go +++ b/contrib/drivers/sqlite/sqlite_model_test.go @@ -3726,7 +3726,7 @@ func Test_Model_Insert_KeyFieldNameMapping_Error(t *testing.T) { Password string Nickname string CreateTime string - NoneExistFiled string + NoneExistField string } data := User{ Id: 1, diff --git a/contrib/drivers/sqlitecgo/sqlite_model_test.go b/contrib/drivers/sqlitecgo/sqlite_model_test.go index c47bccd12b9..8aa297e7a2b 100644 --- a/contrib/drivers/sqlitecgo/sqlite_model_test.go +++ b/contrib/drivers/sqlitecgo/sqlite_model_test.go @@ -3765,7 +3765,7 @@ func Test_Model_Insert_KeyFieldNameMapping_Error(t *testing.T) { Password string Nickname string CreateTime string - NoneExistFiled string + NoneExistField string } data := User{ Id: 1, diff --git a/database/gdb/gdb_core.go b/database/gdb/gdb_core.go index 43db34735d5..f4ac5f7817f 100644 --- a/database/gdb/gdb_core.go +++ b/database/gdb/gdb_core.go @@ -785,7 +785,7 @@ func (c *Core) HasTable(name string) (bool, error) { return result.Bool(), nil } -// isSoftCreatedFieldName checks and returns whether given filed name is an automatic-filled created time. +// isSoftCreatedFieldName checks and returns whether given field name is an automatic-filled created time. func (c *Core) isSoftCreatedFieldName(fieldName string) bool { if fieldName == "" { return false @@ -794,9 +794,9 @@ func (c *Core) isSoftCreatedFieldName(fieldName string) bool { if utils.EqualFoldWithoutChars(fieldName, config.CreatedAt) { return true } - return gstr.InArray(append([]string{config.CreatedAt}, createdFiledNames...), fieldName) + return gstr.InArray(append([]string{config.CreatedAt}, createdFieldNames...), fieldName) } - for _, v := range createdFiledNames { + for _, v := range createdFieldNames { if utils.EqualFoldWithoutChars(fieldName, v) { return true } diff --git a/database/gdb/gdb_core_config.go b/database/gdb/gdb_core_config.go index 1b2edca5a8d..149d2afc366 100644 --- a/database/gdb/gdb_core_config.go +++ b/database/gdb/gdb_core_config.go @@ -49,9 +49,9 @@ type ConfigNode struct { ExecTimeout time.Duration `json:"execTimeout"` // (Optional) Max exec time for dml. TranTimeout time.Duration `json:"tranTimeout"` // (Optional) Max exec time for a transaction. PrepareTimeout time.Duration `json:"prepareTimeout"` // (Optional) Max exec time for prepare operation. - CreatedAt string `json:"createdAt"` // (Optional) The filed name of table for automatic-filled created datetime. - UpdatedAt string `json:"updatedAt"` // (Optional) The filed name of table for automatic-filled updated datetime. - DeletedAt string `json:"deletedAt"` // (Optional) The filed name of table for automatic-filled updated datetime. + CreatedAt string `json:"createdAt"` // (Optional) The field name of table for automatic-filled created datetime. + UpdatedAt string `json:"updatedAt"` // (Optional) The field name of table for automatic-filled updated datetime. + DeletedAt string `json:"deletedAt"` // (Optional) The field name of table for automatic-filled updated datetime. TimeMaintainDisabled bool `json:"timeMaintainDisabled"` // (Optional) Disable the automatic time maintaining feature. } diff --git a/database/gdb/gdb_model_select.go b/database/gdb/gdb_model_select.go index c7f7239d3cb..de19b8d623f 100644 --- a/database/gdb/gdb_model_select.go +++ b/database/gdb/gdb_model_select.go @@ -306,7 +306,7 @@ func (m *Model) Scan(pointer interface{}, where ...interface{}) error { // Where("u1.id<2"). // ScanAndCount(&users, &count, false) func (m *Model) ScanAndCount(pointer interface{}, totalCount *int, useFieldForCount bool) (err error) { - // support Fileds with *, example: .Fileds("a.*, b.name"). Count sql is select count(1) from xxx + // support Fields with *, example: .Fields("a.*, b.name"). Count sql is select count(1) from xxx countModel := m.Clone() // If useFieldForCount is false, set the fields to a constant value of 1 for counting if !useFieldForCount { diff --git a/database/gdb/gdb_model_time.go b/database/gdb/gdb_model_time.go index cd3671fcc44..76333ba6556 100644 --- a/database/gdb/gdb_model_time.go +++ b/database/gdb/gdb_model_time.go @@ -17,9 +17,9 @@ import ( ) var ( - createdFiledNames = []string{"created_at", "create_at"} // Default filed names of table for automatic-filled created datetime. - updatedFiledNames = []string{"updated_at", "update_at"} // Default filed names of table for automatic-filled updated datetime. - deletedFiledNames = []string{"deleted_at", "delete_at"} // Default filed names of table for automatic-filled deleted datetime. + createdFieldNames = []string{"created_at", "create_at"} // Default field names of table for automatic-filled created datetime. + updatedFieldNames = []string{"updated_at", "update_at"} // Default field names of table for automatic-filled updated datetime. + deletedFieldNames = []string{"deleted_at", "delete_at"} // Default field names of table for automatic-filled deleted datetime. ) // Unscoped disables the auto-update time feature for insert, update and delete options. @@ -47,7 +47,7 @@ func (m *Model) getSoftFieldNameCreated(schema string, table string) string { if config.CreatedAt != "" { return m.getSoftFieldName(schema, tableName, []string{config.CreatedAt}) } - return m.getSoftFieldName(schema, tableName, createdFiledNames) + return m.getSoftFieldName(schema, tableName, createdFieldNames) } // getSoftFieldNameUpdate checks and returns the field name for record updating time. @@ -68,7 +68,7 @@ func (m *Model) getSoftFieldNameUpdated(schema string, table string) (field stri if config.UpdatedAt != "" { return m.getSoftFieldName(schema, tableName, []string{config.UpdatedAt}) } - return m.getSoftFieldName(schema, tableName, updatedFiledNames) + return m.getSoftFieldName(schema, tableName, updatedFieldNames) } // getSoftFieldNameDelete checks and returns the field name for record deleting time. @@ -89,7 +89,7 @@ func (m *Model) getSoftFieldNameDeleted(schema string, table string) (field stri if config.DeletedAt != "" { return m.getSoftFieldName(schema, tableName, []string{config.DeletedAt}) } - return m.getSoftFieldName(schema, tableName, deletedFiledNames) + return m.getSoftFieldName(schema, tableName, deletedFieldNames) } // getSoftFieldName retrieves and returns the field name of the table for possible key. diff --git a/database/gdb/gdb_type_result_scanlist.go b/database/gdb/gdb_type_result_scanlist.go index 84210c07d74..d2d32284686 100644 --- a/database/gdb/gdb_type_result_scanlist.go +++ b/database/gdb/gdb_type_result_scanlist.go @@ -247,7 +247,7 @@ func doScanList(in doScanListInput) (err error) { relationBindToFieldName string // Eg: relationKV: id:uid -> uid ) if len(in.RelationFields) > 0 { - // The relation key string of table filed name and attribute name + // The relation key string of table field name and attribute name // can be joined with char '=' or ':'. array := gstr.SplitAndTrim(in.RelationFields, "=") if len(array) == 1 { @@ -363,11 +363,11 @@ func doScanList(in doScanListInput) (err error) { if in.RelationFields != "" && !relationBindToFieldNameChecked { relationFromAttrField = relationFromAttrValue.FieldByName(relationBindToFieldName) if !relationFromAttrField.IsValid() { - filedMap, _ := gstructs.FieldMap(gstructs.FieldMapInput{ + fieldMap, _ := gstructs.FieldMap(gstructs.FieldMapInput{ Pointer: relationFromAttrValue, RecursiveOption: gstructs.RecursiveOptionEmbeddedNoTag, }) - if key, _ := gutil.MapPossibleItemByKey(gconv.Map(filedMap), relationBindToFieldName); key == "" { + if key, _ := gutil.MapPossibleItemByKey(gconv.Map(fieldMap), relationBindToFieldName); key == "" { return gerror.NewCodef( gcode.CodeInvalidParameter, `cannot find possible related attribute name "%s" from given relation fields "%s"`, diff --git a/os/gcmd/gcmd_command.go b/os/gcmd/gcmd_command.go index 557a7531c82..d3cfc2b78a9 100644 --- a/os/gcmd/gcmd_command.go +++ b/os/gcmd/gcmd_command.go @@ -42,11 +42,12 @@ type FuncWithValue func(ctx context.Context, parser *Parser) (out interface{}, e // Argument is the command value that are used by certain command. type Argument struct { - Name string // Option name. - Short string // Option short. - Brief string // Brief info about this Option, which is used in help info. - IsArg bool // IsArg marks this argument taking value from command line argument instead of option. - Orphan bool // Whether this Option having or having no value bound to it. + Name string // Option name. + FieldName string // Option field name. + Short string // Option short. + Brief string // Brief info about this Option, which is used in help info. + IsArg bool // IsArg marks this argument taking value from command line argument instead of option. + Orphan bool // Whether this Option having or having no value bound to it. } var ( diff --git a/os/gcmd/gcmd_command_object.go b/os/gcmd/gcmd_command_object.go index e8bd991770d..ab9d3d7cb0c 100644 --- a/os/gcmd/gcmd_command_object.go +++ b/os/gcmd/gcmd_command_object.go @@ -144,7 +144,7 @@ func newCommandFromObjectMeta(object interface{}, name string) (command *Command if err = gconv.Scan(metaData, &command); err != nil { return } - // Name filed is necessary. + // Name field is necessary. if command.Name == "" { if name == "" { err = gerror.Newf( @@ -353,6 +353,9 @@ func newArgumentsFromInput(object interface{}) (args []Argument, err error) { } if arg.Name == "" { arg.Name = field.Name() + } else if arg.Name != field.Name() { + arg.FieldName = field.Name() + nameSet.Add(arg.FieldName) } if arg.Name == helpOptionName { return nil, gerror.Newf( @@ -414,6 +417,8 @@ func mergeDefaultStructValue(data map[string]interface{}, pointer interface{}) e } else { if utils.IsEmpty(foundValue) { data[foundKey] = field.TagValue + } else { + data[field.Name()] = foundValue } } } diff --git a/os/gcmd/gcmd_command_run.go b/os/gcmd/gcmd_command_run.go index c3f6fd53cb6..7aa61f95df4 100644 --- a/os/gcmd/gcmd_command_run.go +++ b/os/gcmd/gcmd_command_run.go @@ -171,10 +171,12 @@ func (c *Command) reParse(ctx context.Context, parser *Parser) (*Parser, error) if arg.IsArg { continue } + optionKey = arg.Name + if arg.FieldName != "" { + optionKey += fmt.Sprintf(`,%s`, arg.FieldName) + } if arg.Short != "" { - optionKey = fmt.Sprintf(`%s,%s`, arg.Name, arg.Short) - } else { - optionKey = arg.Name + optionKey += fmt.Sprintf(`,%s`, arg.Short) } supportedOptions[optionKey] = !arg.Orphan } diff --git a/os/gcmd/gcmd_z_unit_feature_object1_test.go b/os/gcmd/gcmd_z_unit_feature_object1_test.go index a80183ce253..a2845b327d5 100644 --- a/os/gcmd/gcmd_z_unit_feature_object1_test.go +++ b/os/gcmd/gcmd_z_unit_feature_object1_test.go @@ -31,7 +31,7 @@ type TestCmdObjectEnvOutput struct{} type TestCmdObjectTestInput struct { g.Meta `name:"test" usage:"root test" brief:"root test command" dc:"root test command description" ad:"root test command ad"` - Name string `v:"required" short:"n" orphan:"false" brief:"name for test command"` + Name string `name:"yourname" v:"required" short:"n" orphan:"false" brief:"name for test command" d:"tom"` } type TestCmdObjectTestOutput struct { @@ -89,10 +89,23 @@ func Test_Command_NewFromObject_RunWithValue(t *testing.T) { t.AssertNil(err) t.Assert(cmd.Name, "root") + // test short name os.Args = []string{"root", "test", "-n=john"} value, err := cmd.RunWithValueError(ctx) t.AssertNil(err) t.Assert(value, `{"Content":"john"}`) + + // test name tag name + os.Args = []string{"root", "test", "-yourname=hailaz"} + value1, err1 := cmd.RunWithValueError(ctx) + t.AssertNil(err1) + t.Assert(value1, `{"Content":"hailaz"}`) + + // test default tag value + os.Args = []string{"root", "test"} + value2, err2 := cmd.RunWithValueError(ctx) + t.AssertNil(err2) + t.Assert(value2, `{"Content":"tom"}`) }) } diff --git a/util/gconv/gconv_scan.go b/util/gconv/gconv_scan.go index b31c4a3b893..6187d079de2 100644 --- a/util/gconv/gconv_scan.go +++ b/util/gconv/gconv_scan.go @@ -279,7 +279,7 @@ func doScanList( relationBindToFieldName string // Eg: relationKV: id:uid -> uid ) if len(relationFields) > 0 { - // The relation key string of table filed name and attribute name + // The relation key string of table field name and attribute name // can be joined with char '=' or ':'. array := utils.SplitAndTrim(relationFields, "=") if len(array) == 1 { @@ -396,12 +396,12 @@ func doScanList( relationFromAttrField = relationFromAttrValue.FieldByName(relationBindToFieldName) if !relationFromAttrField.IsValid() { var ( - filedMap, _ = gstructs.FieldMap(gstructs.FieldMapInput{ + fieldMap, _ = gstructs.FieldMap(gstructs.FieldMapInput{ Pointer: relationFromAttrValue, RecursiveOption: gstructs.RecursiveOptionEmbeddedNoTag, }) ) - if key, _ := utils.MapPossibleItemByKey(Map(filedMap), relationBindToFieldName); key == "" { + if key, _ := utils.MapPossibleItemByKey(Map(fieldMap), relationBindToFieldName); key == "" { return gerror.NewCodef( gcode.CodeInvalidParameter, `cannot find possible related attribute name "%s" from given relation fields "%s"`, From 0bd15bdab56376ffea45976f2ed07616bf61acaa Mon Sep 17 00:00:00 2001 From: li-caspar Date: Thu, 9 Nov 2023 20:02:47 +0800 Subject: [PATCH 05/52] fix: "gf gen dao" utils.GetModPath Return empty string in windows (#3141) --- cmd/gf/internal/utility/utils/utils.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/gf/internal/utility/utils/utils.go b/cmd/gf/internal/utility/utils/utils.go index 3392e14711f..bd92581f22c 100644 --- a/cmd/gf/internal/utility/utils/utils.go +++ b/cmd/gf/internal/utility/utils/utils.go @@ -118,7 +118,7 @@ func GetImportPath(filePath string) string { func GetModPath() string { var ( oldDir = gfile.Pwd() - newDir = gfile.Dir(oldDir) + newDir = oldDir goModName = "go.mod" goModPath string ) @@ -127,11 +127,11 @@ func GetModPath() string { if gfile.Exists(goModPath) { return goModPath } - oldDir = newDir newDir = gfile.Dir(oldDir) if newDir == oldDir { break } + oldDir = newDir } return "" } From d4b14fd7174eda6aa7d444f3f0c7742260ad4c3d Mon Sep 17 00:00:00 2001 From: oldme <45782393+oldme-git@users.noreply.github.com> Date: Thu, 9 Nov 2023 20:04:05 +0800 Subject: [PATCH 06/52] add gen service unit testing (#3142) --- .../cmd/{cmd__test.go => cmd_z_init_test.go} | 0 ...cmd_fix_test.go => cmd_z_unit_fix_test.go} | 0 ...rl_test.go => cmd_z_unit_gen_ctrl_test.go} | 5 +- ...dao_test.go => cmd_z_unit_gen_dao_test.go} | 0 .../cmd/cmd_z_unit_gen_service_test.go | 72 +++++++++++++++++++ .../genservice/logic/article/article.go | 33 +++++++++ .../testdata/genservice/logic/logic_expect.go | 9 +++ .../testdata/genservice/service/article.go | 38 ++++++++++ 8 files changed, 154 insertions(+), 3 deletions(-) rename cmd/gf/internal/cmd/{cmd__test.go => cmd_z_init_test.go} (100%) rename cmd/gf/internal/cmd/{cmd_fix_test.go => cmd_z_unit_fix_test.go} (100%) rename cmd/gf/internal/cmd/{cmd_gen_ctrl_test.go => cmd_z_unit_gen_ctrl_test.go} (98%) rename cmd/gf/internal/cmd/{cmd_gen_dao_test.go => cmd_z_unit_gen_dao_test.go} (100%) create mode 100644 cmd/gf/internal/cmd/cmd_z_unit_gen_service_test.go create mode 100644 cmd/gf/internal/cmd/testdata/genservice/logic/article/article.go create mode 100644 cmd/gf/internal/cmd/testdata/genservice/logic/logic_expect.go create mode 100644 cmd/gf/internal/cmd/testdata/genservice/service/article.go diff --git a/cmd/gf/internal/cmd/cmd__test.go b/cmd/gf/internal/cmd/cmd_z_init_test.go similarity index 100% rename from cmd/gf/internal/cmd/cmd__test.go rename to cmd/gf/internal/cmd/cmd_z_init_test.go diff --git a/cmd/gf/internal/cmd/cmd_fix_test.go b/cmd/gf/internal/cmd/cmd_z_unit_fix_test.go similarity index 100% rename from cmd/gf/internal/cmd/cmd_fix_test.go rename to cmd/gf/internal/cmd/cmd_z_unit_fix_test.go diff --git a/cmd/gf/internal/cmd/cmd_gen_ctrl_test.go b/cmd/gf/internal/cmd/cmd_z_unit_gen_ctrl_test.go similarity index 98% rename from cmd/gf/internal/cmd/cmd_gen_ctrl_test.go rename to cmd/gf/internal/cmd/cmd_z_unit_gen_ctrl_test.go index 03cdc284c1d..ca4bc06c534 100644 --- a/cmd/gf/internal/cmd/cmd_gen_ctrl_test.go +++ b/cmd/gf/internal/cmd/cmd_z_unit_gen_ctrl_test.go @@ -33,7 +33,6 @@ func Test_Gen_Ctrl_Default(t *testing.T) { } ) err := gutil.FillStructWithDefault(&in) - t.AssertNil(err) err = gfile.Mkdir(path) @@ -45,7 +44,7 @@ func Test_Gen_Ctrl_Default(t *testing.T) { panic(err) } - // apiInterface files + // apiInterface file var ( genApi = apiFolder + filepath.FromSlash("/article/article.go") genApiExpect = apiFolder + filepath.FromSlash("/article/article_expect.go") @@ -79,7 +78,7 @@ func Test_Gen_Ctrl_Default(t *testing.T) { testPath + filepath.FromSlash("/article/article_v2_create.go"), testPath + filepath.FromSlash("/article/article_v2_update.go"), } - for i, _ := range files { + for i := range files { t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i])) } }) diff --git a/cmd/gf/internal/cmd/cmd_gen_dao_test.go b/cmd/gf/internal/cmd/cmd_z_unit_gen_dao_test.go similarity index 100% rename from cmd/gf/internal/cmd/cmd_gen_dao_test.go rename to cmd/gf/internal/cmd/cmd_z_unit_gen_dao_test.go diff --git a/cmd/gf/internal/cmd/cmd_z_unit_gen_service_test.go b/cmd/gf/internal/cmd/cmd_z_unit_gen_service_test.go new file mode 100644 index 00000000000..7f1f9c2fc52 --- /dev/null +++ b/cmd/gf/internal/cmd/cmd_z_unit_gen_service_test.go @@ -0,0 +1,72 @@ +// Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +package cmd + +import ( + "github.com/gogf/gf/cmd/gf/v2/internal/cmd/genservice" + "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/guid" + "github.com/gogf/gf/v2/util/gutil" + "path/filepath" + "testing" +) + +func Test_Gen_Service_Default(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + var ( + path = gfile.Temp(guid.S()) + dstFolder = path + filepath.FromSlash("/service") + apiFolder = gtest.DataPath("genservice", "logic") + in = genservice.CGenServiceInput{ + SrcFolder: apiFolder, + DstFolder: dstFolder, + DstFileNameCase: "Snake", + WatchFile: "", + StPattern: "", + Packages: nil, + ImportPrefix: "", + Clear: false, + } + ) + err := gutil.FillStructWithDefault(&in) + t.AssertNil(err) + + err = gfile.Mkdir(path) + t.AssertNil(err) + defer gfile.Remove(path) + + _, err = genservice.CGenService{}.Service(ctx, in) + if err != nil { + panic(err) + } + + // logic file + var ( + genApi = apiFolder + filepath.FromSlash("/logic.go") + genApiExpect = apiFolder + filepath.FromSlash("/logic_expect.go") + ) + defer gfile.Remove(genApi) + t.Assert(gfile.GetContents(genApi), gfile.GetContents(genApiExpect)) + + // files + files, err := gfile.ScanDir(dstFolder, "*.go", true) + t.AssertNil(err) + t.Assert(files, []string{ + dstFolder + filepath.FromSlash("/article.go"), + }) + + // contents + testPath := gtest.DataPath("genservice", "service") + expectFiles := []string{ + testPath + filepath.FromSlash("/article.go"), + } + for i := range files { + t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i])) + } + }) +} diff --git a/cmd/gf/internal/cmd/testdata/genservice/logic/article/article.go b/cmd/gf/internal/cmd/testdata/genservice/logic/article/article.go new file mode 100644 index 00000000000..01d889a25ae --- /dev/null +++ b/cmd/gf/internal/cmd/testdata/genservice/logic/article/article.go @@ -0,0 +1,33 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +package article + +import ( + "context" + "github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genservice/service" +) + +type sArticle struct { +} + +func init() { + service.RegisterArticle(&sArticle{}) +} + +// Get article details +func (s *sArticle) Get(ctx context.Context, id uint) (info struct{}, err error) { + return struct{}{}, err +} + +// Create +/** + * create an article. + * @author oldme + */ +func (s *sArticle) Create(ctx context.Context, info struct{}) (id uint, err error) { + return id, err +} diff --git a/cmd/gf/internal/cmd/testdata/genservice/logic/logic_expect.go b/cmd/gf/internal/cmd/testdata/genservice/logic/logic_expect.go new file mode 100644 index 00000000000..c7c3f52e9c3 --- /dev/null +++ b/cmd/gf/internal/cmd/testdata/genservice/logic/logic_expect.go @@ -0,0 +1,9 @@ +// ========================================================================== +// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT. +// ========================================================================== + +package logic + +import ( + _ "github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genservice/logic/article" +) diff --git a/cmd/gf/internal/cmd/testdata/genservice/service/article.go b/cmd/gf/internal/cmd/testdata/genservice/service/article.go new file mode 100644 index 00000000000..765a1c8a5af --- /dev/null +++ b/cmd/gf/internal/cmd/testdata/genservice/service/article.go @@ -0,0 +1,38 @@ +// ================================================================================ +// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT. +// You can delete these comments if you wish manually maintain this interface file. +// ================================================================================ + +package service + +import ( + "context" +) + +type ( + IArticle interface { + // Get article details + Get(ctx context.Context, id uint) (info struct{}, err error) + // Create + /** + * create an article. + * @author oldme + */ + Create(ctx context.Context, info struct{}) (id uint, err error) + } +) + +var ( + localArticle IArticle +) + +func Article() IArticle { + if localArticle == nil { + panic("implement not found for interface IArticle, forgot register?") + } + return localArticle +} + +func RegisterArticle(i IArticle) { + localArticle = i +} From 4d7f9552fee9c9fa59726e14a237a69244685107 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B5=B7=E4=BA=AE?= <739476267@qq.com> Date: Mon, 13 Nov 2023 22:05:53 +0800 Subject: [PATCH 07/52] fix: gdb unsupport aliyun hologres link (#3150) --- database/gdb/gdb.go | 2 +- database/gdb/gdb_z_mysql_internal_test.go | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/database/gdb/gdb.go b/database/gdb/gdb.go index c2c50144abb..1c3344149cb 100644 --- a/database/gdb/gdb.go +++ b/database/gdb/gdb.go @@ -378,7 +378,7 @@ const ( ctxKeyInternalProducedSQL gctx.StrKey = `CtxKeyInternalProducedSQL` // type:[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...¶mN=valueN] - linkPattern = `(\w+):([\w\-]*):(.*?)@(\w+?)\((.+?)\)/{0,1}([^\?]*)\?{0,1}(.*)` + linkPattern = `(\w+):([\w\-\$]*):(.*?)@(\w+?)\((.+?)\)/{0,1}([^\?]*)\?{0,1}(.*)` ) type queryType int diff --git a/database/gdb/gdb_z_mysql_internal_test.go b/database/gdb/gdb_z_mysql_internal_test.go index d29589626ad..538ab967d8d 100644 --- a/database/gdb/gdb_z_mysql_internal_test.go +++ b/database/gdb/gdb_z_mysql_internal_test.go @@ -222,6 +222,22 @@ func Test_parseConfigNodeLink_WithType(t *testing.T) { t.Assert(newNode.Charset, defaultCharset) t.Assert(newNode.Protocol, `file`) }) + // #3146 + gtest.C(t, func(t *gtest.T) { + node := &ConfigNode{ + Link: `pgsql:BASIC$xxxx:123456@tcp(xxxx.hologres.aliyuncs.com:80)/xxx`, + } + newNode := parseConfigNodeLink(node) + t.Assert(newNode.Type, `pgsql`) + t.Assert(newNode.User, `BASIC$xxxx`) + t.Assert(newNode.Pass, `123456`) + t.Assert(newNode.Host, `xxxx.hologres.aliyuncs.com`) + t.Assert(newNode.Port, `80`) + t.Assert(newNode.Name, `xxx`) + t.Assert(newNode.Extra, ``) + t.Assert(newNode.Charset, defaultCharset) + t.Assert(newNode.Protocol, `tcp`) + }) } func Test_Func_doQuoteWord(t *testing.T) { From 84ed66018e9434536604a25bec3dc99f5d173f7c Mon Sep 17 00:00:00 2001 From: zhangyuyu <1580074674@qq.com> Date: Tue, 14 Nov 2023 20:00:26 +0800 Subject: [PATCH 08/52] fix issue: Windows Platform did not handle process signal (#3154) --- net/ghttp/ghttp_server_admin_windows.go | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/net/ghttp/ghttp_server_admin_windows.go b/net/ghttp/ghttp_server_admin_windows.go index 135dc56d5f5..7d83e3e0da9 100644 --- a/net/ghttp/ghttp_server_admin_windows.go +++ b/net/ghttp/ghttp_server_admin_windows.go @@ -9,7 +9,19 @@ package ghttp -// registerSignalHandler does nothing on window platform. +import ( + "context" + "os" + + "github.com/gogf/gf/v2/os/gproc" +) + +// handleProcessSignal handles all signals from system in blocking way. func handleProcessSignal() { + var ctx = context.TODO() + gproc.AddSigHandlerShutdown(func(sig os.Signal) { + shutdownWebServersGracefully(ctx, sig) + }) + gproc.Listen() } From 5580ac9475ae34fe6fbc3637634a7f6ce67768c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B5=B7=E4=BA=AE?= <739476267@qq.com> Date: Tue, 14 Nov 2023 20:10:49 +0800 Subject: [PATCH 09/52] fix issue in cross-building failed in windows (#3152) --- cmd/gf/internal/cmd/cmd_build.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/cmd/gf/internal/cmd/cmd_build.go b/cmd/gf/internal/cmd/cmd_build.go index 49e80a27182..2a0564026e4 100644 --- a/cmd/gf/internal/cmd/cmd_build.go +++ b/cmd/gf/internal/cmd/cmd_build.go @@ -289,10 +289,11 @@ func (c cBuild) Index(ctx context.Context, in cBuildInput) (out *cBuildOutput, e ) } cmd = fmt.Sprintf( - `GOOS=%s GOARCH=%s go build %s -ldflags "%s" %s%s`, - system, arch, outputPath, ldFlags, in.Extra, file, + `go build %s -ldflags "%s" %s%s`, + outputPath, ldFlags, in.Extra, file, ) } + mlog.Debug(fmt.Sprintf("build for GOOS=%s GOARCH=%s", system, arch)) mlog.Debug(cmd) // It's not necessary printing the complete command string. cmdShow, _ := gregex.ReplaceString(`\s+(-ldflags ".+?")\s+`, " ", cmd) From 0be8b29e42b0c4cd01dd933858d023c8d3a12d08 Mon Sep 17 00:00:00 2001 From: oldme <45782393+oldme-git@users.noreply.github.com> Date: Tue, 14 Nov 2023 20:53:41 +0800 Subject: [PATCH 10/52] improve gen service code (#3140) --- cmd/gf/internal/cmd/genservice/genservice.go | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/cmd/gf/internal/cmd/genservice/genservice.go b/cmd/gf/internal/cmd/genservice/genservice.go index ceb783a8437..e1ef5dc74ce 100644 --- a/cmd/gf/internal/cmd/genservice/genservice.go +++ b/cmd/gf/internal/cmd/genservice/genservice.go @@ -9,6 +9,7 @@ package genservice import ( "context" "fmt" + "path/filepath" "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/container/gmap" @@ -93,10 +94,10 @@ const ( ) func (c CGenService) Service(ctx context.Context, in CGenServiceInput) (out *CGenServiceOutput, err error) { - in.SrcFolder = gstr.TrimRight(in.SrcFolder, `\/`) - in.SrcFolder = gstr.Replace(in.SrcFolder, "\\", "/") - in.WatchFile = gstr.TrimRight(in.WatchFile, `\/`) - in.WatchFile = gstr.Replace(in.WatchFile, "\\", "/") + in.SrcFolder = filepath.ToSlash(in.SrcFolder) + in.SrcFolder = gstr.TrimRight(in.SrcFolder, `/`) + in.WatchFile = filepath.ToSlash(in.WatchFile) + in.WatchFile = gstr.TrimRight(in.WatchFile, `/`) // Watch file handling. if in.WatchFile != "" { From 9694a682114146471d1d8a5ae72445fbc71561fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B5=B7=E4=BA=AE?= <739476267@qq.com> Date: Thu, 16 Nov 2023 20:10:45 +0800 Subject: [PATCH 11/52] Optimize the information display of gf -v (#3145) --- cmd/gf/internal/cmd/cmd_version.go | 105 +++++++++++++++++++++++------ 1 file changed, 85 insertions(+), 20 deletions(-) diff --git a/cmd/gf/internal/cmd/cmd_version.go b/cmd/gf/internal/cmd/cmd_version.go index 10a31eacf46..89e753cce95 100644 --- a/cmd/gf/internal/cmd/cmd_version.go +++ b/cmd/gf/internal/cmd/cmd_version.go @@ -7,14 +7,19 @@ package cmd import ( + "bytes" "context" "fmt" + "runtime" + "strings" + "time" "github.com/gogf/gf/v2" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gbuild" "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/os/gproc" "github.com/gogf/gf/v2/text/gregex" "github.com/gogf/gf/v2/text/gstr" @@ -25,6 +30,10 @@ var ( Version = cVersion{} ) +const ( + defaultIndent = "{{indent}}" +) + type cVersion struct { g.Meta `name:"version" brief:"show version information of current binary"` } @@ -36,34 +45,90 @@ type cVersionInput struct { type cVersionOutput struct{} func (c cVersion) Index(ctx context.Context, in cVersionInput) (*cVersionOutput, error) { - info := gbuild.Info() - if info.Git == "" { - info.Git = "none" - } - mlog.Printf(`GoFrame CLI Tool %s, https://goframe.org`, gf.VERSION) - gfVersion, err := c.getGFVersionOfCurrentProject() - if err != nil { - gfVersion = err.Error() + detailBuffer := &detailBuffer{} + detailBuffer.WriteString(fmt.Sprintf("%s", gf.VERSION)) + + detailBuffer.appendLine(0, "Welcome to GoFrame!") + + detailBuffer.appendLine(0, "Env Detail:") + goVersion, ok := getGoVersion() + if ok { + detailBuffer.appendLine(1, fmt.Sprintf("Go Version: %s", goVersion)) + detailBuffer.appendLine(1, fmt.Sprintf("GF Version(go.mod): %s", getGoFrameVersion(2))) } else { - gfVersion = gfVersion + " in current go.mod" + v, err := c.getGFVersionOfCurrentProject() + if err == nil { + detailBuffer.appendLine(1, fmt.Sprintf("GF Version(go.mod): %s", v)) + } else { + detailBuffer.appendLine(1, fmt.Sprintf("GF Version(go.mod): %s", err.Error())) + } } - mlog.Printf(`GoFrame Version: %s`, gfVersion) - mlog.Printf(`CLI Installed At: %s`, gfile.SelfPath()) + + detailBuffer.appendLine(0, "CLI Detail:") + detailBuffer.appendLine(1, fmt.Sprintf("Installed At: %s", gfile.SelfPath())) + info := gbuild.Info() if info.GoFrame == "" { - mlog.Print(`Current is a custom installed version, no installation information.`) - return nil, nil + detailBuffer.appendLine(1, fmt.Sprintf("Built Go Version: %s", runtime.Version())) + detailBuffer.appendLine(1, fmt.Sprintf("Built GF Version: %s", gf.VERSION)) + } else { + if info.Git == "" { + info.Git = "none" + } + detailBuffer.appendLine(1, fmt.Sprintf("Built Go Version: %s", info.Golang)) + detailBuffer.appendLine(1, fmt.Sprintf("Built GF Version: %s", info.GoFrame)) + detailBuffer.appendLine(1, fmt.Sprintf("Git Commit: %s", info.Git)) + detailBuffer.appendLine(1, fmt.Sprintf("Built Time: %s", info.Time)) } - mlog.Print(gstr.Trim(fmt.Sprintf(` -CLI Built Detail: - Go Version: %s - GF Version: %s - Git Commit: %s - Build Time: %s -`, info.Golang, info.GoFrame, info.Git, info.Time))) + detailBuffer.appendLine(0, "Others Detail:") + detailBuffer.appendLine(1, "Docs: https://goframe.org") + detailBuffer.appendLine(1, fmt.Sprintf("Now : %s", time.Now().Format(time.RFC3339))) + + mlog.Print(detailBuffer.replaceAllIndent(" ")) return nil, nil } +// detailBuffer is a buffer for detail information. +type detailBuffer struct { + bytes.Buffer +} + +// appendLine appends a line to the buffer with given indent level. +func (d *detailBuffer) appendLine(indentLevel int, line string) { + d.WriteString(fmt.Sprintf("\n%s%s", strings.Repeat(defaultIndent, indentLevel), line)) +} + +// replaceAllIndent replaces the tab with given indent string and prints the buffer content. +func (d *detailBuffer) replaceAllIndent(indentStr string) string { + return strings.ReplaceAll(d.String(), defaultIndent, indentStr) +} + +// getGoFrameVersion returns the goframe version of current project using. +func getGoFrameVersion(indentLevel int) (gfVersion string) { + pkgInfo, err := gproc.ShellExec(context.Background(), `go list -f "{{if (not .Main)}}{{.Path}}@{{.Version}}{{end}}" -m all`) + if err != nil { + return "cannot find go.mod" + } + pkgList := gstr.Split(pkgInfo, "\n") + for _, v := range pkgList { + if strings.HasPrefix(v, "github.com/gogf/gf") { + gfVersion += fmt.Sprintf("\n%s%s", strings.Repeat(defaultIndent, indentLevel), v) + } + } + return +} + +// getGoVersion returns the go version +func getGoVersion() (goVersion string, ok bool) { + goVersion, err := gproc.ShellExec(context.Background(), "go version") + if err != nil { + return "", false + } + goVersion = gstr.TrimLeftStr(goVersion, "go version ") + goVersion = gstr.TrimRightStr(goVersion, "\n") + return goVersion, true +} + // getGFVersionOfCurrentProject checks and returns the GoFrame version current project using. func (c cVersion) getGFVersionOfCurrentProject() (string, error) { goModPath := gfile.Join(gfile.Pwd(), "go.mod") From 85acd3d31d764a6e7c9f0d08749839b3805d3bfa Mon Sep 17 00:00:00 2001 From: wlqe Date: Thu, 16 Nov 2023 20:15:48 +0800 Subject: [PATCH 12/52] Fix the bug that ScanAndCount and AllAndCount report errors in sqlserver (#3155) --- contrib/drivers/mssql/mssql_z_model_test.go | 37 +++++++++++++++++++++ database/gdb/gdb_model_select.go | 6 ++-- 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/contrib/drivers/mssql/mssql_z_model_test.go b/contrib/drivers/mssql/mssql_z_model_test.go index 4e155068416..2310493a320 100644 --- a/contrib/drivers/mssql/mssql_z_model_test.go +++ b/contrib/drivers/mssql/mssql_z_model_test.go @@ -2548,3 +2548,40 @@ func Test_Model_WherePrefixLike(t *testing.T) { t.Assert(r[0]["ID"], "3") }) } + +func Test_Model_AllAndCount(t *testing.T) { + table := createInitTable() + defer dropTable(table) + + gtest.C(t, func(t *gtest.T) { + result, total, err := db.Model(table).Order("id").Limit(0, 3).AllAndCount(false) + t.Assert(err, nil) + + t.Assert(len(result), 3) + t.Assert(total, TableSize) + }) +} + +func Test_Model_ScanAndCount(t *testing.T) { + table := createInitTable() + defer dropTable(table) + + gtest.C(t, func(t *gtest.T) { + type User struct { + Id int + Passport string + Password string + NickName string + CreateTime gtime.Time + } + + users := make([]User, 0) + total := 0 + + err := db.Model(table).Order("id").Limit(0, 3).ScanAndCount(&users, &total, false) + t.Assert(err, nil) + + t.Assert(len(users), 3) + t.Assert(total, TableSize) + }) +} diff --git a/database/gdb/gdb_model_select.go b/database/gdb/gdb_model_select.go index de19b8d623f..5a37968f7c1 100644 --- a/database/gdb/gdb_model_select.go +++ b/database/gdb/gdb_model_select.go @@ -768,8 +768,10 @@ func (m *Model) formatCondition( } } // ORDER BY. - if m.orderBy != "" { - conditionExtra += " ORDER BY " + m.orderBy + if !isCountStatement { // The count statement of sqlserver cannot contain the order by statement + if m.orderBy != "" { + conditionExtra += " ORDER BY " + m.orderBy + } } // LIMIT. if !isCountStatement { From fc8572e8dd3532f754b2140559dd21338f118e0a Mon Sep 17 00:00:00 2001 From: John Guo Date: Mon, 20 Nov 2023 10:01:54 +0800 Subject: [PATCH 13/52] version v2.5.7 (#3162) --- cmd/gf/go.mod | 18 +++++++++--------- cmd/gf/go.sum | 9 ++++----- contrib/config/apollo/go.mod | 2 +- contrib/config/consul/go.mod | 2 +- contrib/config/kubecm/go.mod | 6 +++--- contrib/config/kubecm/go.sum | 9 ++++----- contrib/config/nacos/go.mod | 2 +- contrib/config/polaris/go.mod | 2 +- contrib/drivers/clickhouse/go.mod | 6 +++--- contrib/drivers/clickhouse/go.sum | 9 ++++----- contrib/drivers/dm/go.mod | 6 +++--- contrib/drivers/dm/go.sum | 13 ++++++------- contrib/drivers/mssql/go.mod | 6 +++--- contrib/drivers/mssql/go.sum | 9 ++++----- contrib/drivers/mysql/go.mod | 6 +++--- contrib/drivers/mysql/go.sum | 9 ++++----- contrib/drivers/oracle/go.mod | 6 +++--- contrib/drivers/oracle/go.sum | 9 ++++----- contrib/drivers/pgsql/go.mod | 6 +++--- contrib/drivers/pgsql/go.sum | 9 ++++----- contrib/drivers/sqlite/go.mod | 6 +++--- contrib/drivers/sqlite/go.sum | 9 ++++----- contrib/drivers/sqlitecgo/go.mod | 6 +++--- contrib/drivers/sqlitecgo/go.sum | 9 ++++----- contrib/nosql/redis/go.mod | 2 +- contrib/registry/etcd/go.mod | 2 +- contrib/registry/file/go.mod | 2 +- contrib/registry/nacos/go.mod | 2 +- contrib/registry/polaris/go.mod | 2 +- contrib/registry/zookeeper/go.mod | 2 +- contrib/rpc/grpcx/go.mod | 4 ++-- contrib/sdk/httpclient/go.mod | 6 +++--- contrib/sdk/httpclient/go.sum | 9 ++++----- contrib/trace/jaeger/go.mod | 2 +- contrib/trace/jaeger/go.sum | 4 ++-- contrib/trace/otlpgrpc/go.mod | 15 ++++++++++++++- contrib/trace/otlpgrpc/go.sum | 23 +++++++++++++++++++++++ contrib/trace/otlphttp/go.mod | 15 ++++++++++++++- contrib/trace/otlphttp/go.sum | 23 +++++++++++++++++++++++ example/go.mod | 28 ++++++++++++++-------------- version.go | 2 +- 41 files changed, 189 insertions(+), 128 deletions(-) diff --git a/cmd/gf/go.mod b/cmd/gf/go.mod index 96bce9a1ffb..48579f385b2 100644 --- a/cmd/gf/go.mod +++ b/cmd/gf/go.mod @@ -3,13 +3,13 @@ module github.com/gogf/gf/cmd/gf/v2 go 1.18 require ( - github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.5.6 - github.com/gogf/gf/contrib/drivers/mssql/v2 v2.5.6 - github.com/gogf/gf/contrib/drivers/mysql/v2 v2.5.6 - github.com/gogf/gf/contrib/drivers/oracle/v2 v2.5.6 - github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.5.6 - github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.5.6 - github.com/gogf/gf/v2 v2.5.6 + github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.5.7 + github.com/gogf/gf/contrib/drivers/mssql/v2 v2.5.7 + github.com/gogf/gf/contrib/drivers/mysql/v2 v2.5.7 + github.com/gogf/gf/contrib/drivers/oracle/v2 v2.5.7 + github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.5.7 + github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.5.7 + github.com/gogf/gf/v2 v2.5.7 github.com/minio/selfupdate v0.6.0 github.com/olekukonko/tablewriter v0.0.5 golang.org/x/mod v0.9.0 @@ -24,7 +24,7 @@ require ( github.com/denisenkom/go-mssqldb v0.12.3 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/fatih/color v1.15.0 // indirect - github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/glebarez/go-sqlite v1.21.2 // indirect github.com/go-logr/logr v1.2.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect @@ -37,7 +37,7 @@ require ( github.com/lib/pq v1.10.9 // indirect github.com/magiconair/properties v1.8.6 // indirect github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.19 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-runewidth v0.0.15 // indirect github.com/paulmach/orb v0.7.1 // indirect github.com/pierrec/lz4/v4 v4.1.14 // indirect diff --git a/cmd/gf/go.sum b/cmd/gf/go.sum index a97c48290f1..bb5f8a4a868 100644 --- a/cmd/gf/go.sum +++ b/cmd/gf/go.sum @@ -23,8 +23,8 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= -github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= -github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/glebarez/go-sqlite v1.21.2 h1:3a6LFC4sKahUunAmynQKLZceZCOzUthkRkEAl9gAXWo= github.com/glebarez/go-sqlite v1.21.2/go.mod h1:sfxdZyhQjTM2Wry3gVYWaW072Ri1WMdWJi0k6+3382k= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -67,8 +67,8 @@ github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPK github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= -github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= @@ -159,7 +159,6 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220429233432-b5fbb4746d32/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/contrib/config/apollo/go.mod b/contrib/config/apollo/go.mod index da2f2705952..660c4782018 100644 --- a/contrib/config/apollo/go.mod +++ b/contrib/config/apollo/go.mod @@ -4,7 +4,7 @@ go 1.18 require ( github.com/apolloconfig/agollo/v4 v4.3.1 - github.com/gogf/gf/v2 v2.5.6 + github.com/gogf/gf/v2 v2.5.7 ) require ( diff --git a/contrib/config/consul/go.mod b/contrib/config/consul/go.mod index bf072933d43..bf1c2fcb46d 100644 --- a/contrib/config/consul/go.mod +++ b/contrib/config/consul/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/consul/v2 go 1.19 require ( - github.com/gogf/gf/v2 v2.5.6 + github.com/gogf/gf/v2 v2.5.7 github.com/hashicorp/consul/api v1.24.0 github.com/hashicorp/go-cleanhttp v0.5.2 ) diff --git a/contrib/config/kubecm/go.mod b/contrib/config/kubecm/go.mod index 448dc155b5d..3f9770b1bc4 100644 --- a/contrib/config/kubecm/go.mod +++ b/contrib/config/kubecm/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/kubecm/v2 go 1.19 require ( - github.com/gogf/gf/v2 v2.5.6 + github.com/gogf/gf/v2 v2.5.7 k8s.io/api v0.27.4 k8s.io/apimachinery v0.27.4 k8s.io/client-go v0.27.4 @@ -15,7 +15,7 @@ require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/emicklei/go-restful/v3 v3.9.0 // indirect github.com/fatih/color v1.15.0 // indirect - github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/go-logr/logr v1.2.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-openapi/jsonpointer v0.19.6 // indirect @@ -35,7 +35,7 @@ require ( github.com/magiconair/properties v1.8.6 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.19 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-runewidth v0.0.15 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect diff --git a/contrib/config/kubecm/go.sum b/contrib/config/kubecm/go.sum index d09797a7081..dfcb587c569 100644 --- a/contrib/config/kubecm/go.sum +++ b/contrib/config/kubecm/go.sum @@ -56,8 +56,8 @@ github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1m github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= -github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= -github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= @@ -168,8 +168,8 @@ github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJ github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= -github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= @@ -330,7 +330,6 @@ golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/contrib/config/nacos/go.mod b/contrib/config/nacos/go.mod index 2f510f5382f..48b6c46f481 100644 --- a/contrib/config/nacos/go.mod +++ b/contrib/config/nacos/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/nacos/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.5.6 + github.com/gogf/gf/v2 v2.5.7 github.com/nacos-group/nacos-sdk-go v1.1.4 ) diff --git a/contrib/config/polaris/go.mod b/contrib/config/polaris/go.mod index 9ef83bb8a69..51ae7e0c964 100644 --- a/contrib/config/polaris/go.mod +++ b/contrib/config/polaris/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/polaris/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.5.6 + github.com/gogf/gf/v2 v2.5.7 github.com/polarismesh/polaris-go v1.5.5 ) diff --git a/contrib/drivers/clickhouse/go.mod b/contrib/drivers/clickhouse/go.mod index 24fbd02e4be..b9a902dbdf0 100644 --- a/contrib/drivers/clickhouse/go.mod +++ b/contrib/drivers/clickhouse/go.mod @@ -4,7 +4,7 @@ go 1.18 require ( github.com/ClickHouse/clickhouse-go/v2 v2.0.15 - github.com/gogf/gf/v2 v2.5.6 + github.com/gogf/gf/v2 v2.5.7 github.com/google/uuid v1.3.0 github.com/shopspring/decimal v1.3.1 ) @@ -13,14 +13,14 @@ require ( github.com/BurntSushi/toml v1.2.0 // indirect github.com/clbanning/mxj/v2 v2.7.0 // indirect github.com/fatih/color v1.15.0 // indirect - github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/go-logr/logr v1.2.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/grokify/html-strip-tags-go v0.0.1 // indirect github.com/magiconair/properties v1.8.6 // indirect github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.19 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-runewidth v0.0.15 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/paulmach/orb v0.7.1 // indirect diff --git a/contrib/drivers/clickhouse/go.sum b/contrib/drivers/clickhouse/go.sum index d951a1ceb71..a20052e8369 100644 --- a/contrib/drivers/clickhouse/go.sum +++ b/contrib/drivers/clickhouse/go.sum @@ -10,8 +10,8 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= -github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= -github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= @@ -45,8 +45,8 @@ github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPK github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= -github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= @@ -111,7 +111,6 @@ golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220429233432-b5fbb4746d32/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/contrib/drivers/dm/go.mod b/contrib/drivers/dm/go.mod index 510e0c6bdef..2f187647a19 100644 --- a/contrib/drivers/dm/go.mod +++ b/contrib/drivers/dm/go.mod @@ -6,14 +6,14 @@ replace github.com/gogf/gf/v2 => ../../../ require ( gitee.com/chunanyong/dm v1.8.12 - github.com/gogf/gf/v2 v2.5.6 + github.com/gogf/gf/v2 v2.5.7 ) require ( github.com/BurntSushi/toml v1.2.0 // indirect github.com/clbanning/mxj/v2 v2.7.0 // indirect github.com/fatih/color v1.15.0 // indirect - github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/go-logr/logr v1.2.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/golang/snappy v0.0.1 // indirect @@ -21,7 +21,7 @@ require ( github.com/grokify/html-strip-tags-go v0.0.1 // indirect github.com/magiconair/properties v1.8.6 // indirect github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.19 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-runewidth v0.0.15 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/rivo/uniseg v0.4.4 // indirect diff --git a/contrib/drivers/dm/go.sum b/contrib/drivers/dm/go.sum index 314d41db47a..eb74f6ab3ca 100644 --- a/contrib/drivers/dm/go.sum +++ b/contrib/drivers/dm/go.sum @@ -1,5 +1,5 @@ -gitee.com/chunanyong/dm v1.8.10 h1:9S1CKUggWHIea/GI7nr7S/DNMaxIilNFgfzdzKDx2+I= -gitee.com/chunanyong/dm v1.8.10/go.mod h1:EPRJnuPFgbyOFgJ0TRYCTGzhq+ZT4wdyaj/GW/LLcNg= +gitee.com/chunanyong/dm v1.8.12 h1:WupbFZL0MRNIIiCPaLDHgFi5jkdkjzjPReuWPaInGwk= +gitee.com/chunanyong/dm v1.8.12/go.mod h1:EPRJnuPFgbyOFgJ0TRYCTGzhq+ZT4wdyaj/GW/LLcNg= github.com/BurntSushi/toml v1.2.0 h1:Rt8g24XnyGTyglgET/PRUNlrUeu9F5L+7FilkXfZgs0= github.com/BurntSushi/toml v1.2.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/clbanning/mxj/v2 v2.7.0 h1:WA/La7UGCanFe5NpHF0Q3DNtnCsVoxbPKuyBNHWRyME= @@ -7,8 +7,8 @@ github.com/clbanning/mxj/v2 v2.7.0/go.mod h1:hNiWqW14h+kc+MdF9C6/YoRfjEJoR3ou6tn github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= -github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= -github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -26,8 +26,8 @@ github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPK github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= -github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= @@ -47,7 +47,6 @@ go.opentelemetry.io/otel/trace v1.14.0/go.mod h1:8avnQLK+CG77yNLUae4ea2JDQ6iT+go golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/contrib/drivers/mssql/go.mod b/contrib/drivers/mssql/go.mod index 571f9bda39c..24b42a513ea 100644 --- a/contrib/drivers/mssql/go.mod +++ b/contrib/drivers/mssql/go.mod @@ -4,14 +4,14 @@ go 1.18 require ( github.com/denisenkom/go-mssqldb v0.12.3 - github.com/gogf/gf/v2 v2.5.6 + github.com/gogf/gf/v2 v2.5.7 ) require ( github.com/BurntSushi/toml v1.2.0 // indirect github.com/clbanning/mxj/v2 v2.7.0 // indirect github.com/fatih/color v1.15.0 // indirect - github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/go-logr/logr v1.2.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe // indirect @@ -20,7 +20,7 @@ require ( github.com/grokify/html-strip-tags-go v0.0.1 // indirect github.com/magiconair/properties v1.8.6 // indirect github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.19 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-runewidth v0.0.15 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/rivo/uniseg v0.4.4 // indirect diff --git a/contrib/drivers/mssql/go.sum b/contrib/drivers/mssql/go.sum index cb9da0016a2..1c24aa09922 100644 --- a/contrib/drivers/mssql/go.sum +++ b/contrib/drivers/mssql/go.sum @@ -13,8 +13,8 @@ github.com/denisenkom/go-mssqldb v0.12.3/go.mod h1:k0mtMFOnU+AihqFxPMiF05rtiDror github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= -github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= -github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -34,8 +34,8 @@ github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPK github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= -github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= @@ -73,7 +73,6 @@ golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/contrib/drivers/mysql/go.mod b/contrib/drivers/mysql/go.mod index 31596e88daa..21db76fdd75 100644 --- a/contrib/drivers/mysql/go.mod +++ b/contrib/drivers/mysql/go.mod @@ -4,21 +4,21 @@ go 1.18 require ( github.com/go-sql-driver/mysql v1.7.1 - github.com/gogf/gf/v2 v2.5.6 + github.com/gogf/gf/v2 v2.5.7 ) require ( github.com/BurntSushi/toml v1.2.0 // indirect github.com/clbanning/mxj/v2 v2.7.0 // indirect github.com/fatih/color v1.15.0 // indirect - github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/go-logr/logr v1.2.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/grokify/html-strip-tags-go v0.0.1 // indirect github.com/magiconair/properties v1.8.6 // indirect github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.19 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-runewidth v0.0.15 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/rivo/uniseg v0.4.4 // indirect diff --git a/contrib/drivers/mysql/go.sum b/contrib/drivers/mysql/go.sum index b21c5d6bc88..ee6480831b0 100644 --- a/contrib/drivers/mysql/go.sum +++ b/contrib/drivers/mysql/go.sum @@ -5,8 +5,8 @@ github.com/clbanning/mxj/v2 v2.7.0/go.mod h1:hNiWqW14h+kc+MdF9C6/YoRfjEJoR3ou6tn github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= -github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= -github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -24,8 +24,8 @@ github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPK github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= -github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= @@ -45,7 +45,6 @@ go.opentelemetry.io/otel/trace v1.14.0/go.mod h1:8avnQLK+CG77yNLUae4ea2JDQ6iT+go golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/contrib/drivers/oracle/go.mod b/contrib/drivers/oracle/go.mod index cdacdf79a05..d71523e1097 100644 --- a/contrib/drivers/oracle/go.mod +++ b/contrib/drivers/oracle/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/drivers/oracle/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.5.6 + github.com/gogf/gf/v2 v2.5.7 github.com/sijms/go-ora/v2 v2.7.10 ) @@ -11,14 +11,14 @@ require ( github.com/BurntSushi/toml v1.2.0 // indirect github.com/clbanning/mxj/v2 v2.7.0 // indirect github.com/fatih/color v1.15.0 // indirect - github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/go-logr/logr v1.2.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/grokify/html-strip-tags-go v0.0.1 // indirect github.com/magiconair/properties v1.8.6 // indirect github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.19 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-runewidth v0.0.15 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/rivo/uniseg v0.4.4 // indirect diff --git a/contrib/drivers/oracle/go.sum b/contrib/drivers/oracle/go.sum index 7aed5e437c9..2ecb867130a 100644 --- a/contrib/drivers/oracle/go.sum +++ b/contrib/drivers/oracle/go.sum @@ -5,8 +5,8 @@ github.com/clbanning/mxj/v2 v2.7.0/go.mod h1:hNiWqW14h+kc+MdF9C6/YoRfjEJoR3ou6tn github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= -github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= -github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -22,8 +22,8 @@ github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPK github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= -github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= @@ -45,7 +45,6 @@ go.opentelemetry.io/otel/trace v1.14.0/go.mod h1:8avnQLK+CG77yNLUae4ea2JDQ6iT+go golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/contrib/drivers/pgsql/go.mod b/contrib/drivers/pgsql/go.mod index f2700127e35..5da1ae1ef52 100644 --- a/contrib/drivers/pgsql/go.mod +++ b/contrib/drivers/pgsql/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/drivers/pgsql/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.5.6 + github.com/gogf/gf/v2 v2.5.7 github.com/lib/pq v1.10.9 ) @@ -11,14 +11,14 @@ require ( github.com/BurntSushi/toml v1.2.0 // indirect github.com/clbanning/mxj/v2 v2.7.0 // indirect github.com/fatih/color v1.15.0 // indirect - github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/go-logr/logr v1.2.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/grokify/html-strip-tags-go v0.0.1 // indirect github.com/magiconair/properties v1.8.6 // indirect github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.19 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-runewidth v0.0.15 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/rivo/uniseg v0.4.4 // indirect diff --git a/contrib/drivers/pgsql/go.sum b/contrib/drivers/pgsql/go.sum index fb5e6b7717c..07e9653587b 100644 --- a/contrib/drivers/pgsql/go.sum +++ b/contrib/drivers/pgsql/go.sum @@ -5,8 +5,8 @@ github.com/clbanning/mxj/v2 v2.7.0/go.mod h1:hNiWqW14h+kc+MdF9C6/YoRfjEJoR3ou6tn github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= -github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= -github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -24,8 +24,8 @@ github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPK github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= -github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= @@ -45,7 +45,6 @@ go.opentelemetry.io/otel/trace v1.14.0/go.mod h1:8avnQLK+CG77yNLUae4ea2JDQ6iT+go golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/contrib/drivers/sqlite/go.mod b/contrib/drivers/sqlite/go.mod index 2d2460503be..acf2067b522 100644 --- a/contrib/drivers/sqlite/go.mod +++ b/contrib/drivers/sqlite/go.mod @@ -4,7 +4,7 @@ go 1.18 require ( github.com/glebarez/go-sqlite v1.21.2 - github.com/gogf/gf/v2 v2.5.6 + github.com/gogf/gf/v2 v2.5.7 ) require ( @@ -12,7 +12,7 @@ require ( github.com/clbanning/mxj/v2 v2.7.0 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/fatih/color v1.15.0 // indirect - github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/go-logr/logr v1.2.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/google/uuid v1.3.0 // indirect @@ -20,7 +20,7 @@ require ( github.com/grokify/html-strip-tags-go v0.0.1 // indirect github.com/magiconair/properties v1.8.6 // indirect github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.19 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-runewidth v0.0.15 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect diff --git a/contrib/drivers/sqlite/go.sum b/contrib/drivers/sqlite/go.sum index 6813208d6a3..ba3cbf0417b 100644 --- a/contrib/drivers/sqlite/go.sum +++ b/contrib/drivers/sqlite/go.sum @@ -7,8 +7,8 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= -github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= -github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/glebarez/go-sqlite v1.21.2 h1:3a6LFC4sKahUunAmynQKLZceZCOzUthkRkEAl9gAXWo= github.com/glebarez/go-sqlite v1.21.2/go.mod h1:sfxdZyhQjTM2Wry3gVYWaW072Ri1WMdWJi0k6+3382k= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -29,8 +29,8 @@ github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPK github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= -github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= @@ -53,7 +53,6 @@ go.opentelemetry.io/otel/trace v1.14.0/go.mod h1:8avnQLK+CG77yNLUae4ea2JDQ6iT+go golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/contrib/drivers/sqlitecgo/go.mod b/contrib/drivers/sqlitecgo/go.mod index cfc29f3534b..ee53a450d44 100644 --- a/contrib/drivers/sqlitecgo/go.mod +++ b/contrib/drivers/sqlitecgo/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/drivers/sqlitecgo/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.5.6 + github.com/gogf/gf/v2 v2.5.7 github.com/mattn/go-sqlite3 v1.14.17 ) @@ -11,14 +11,14 @@ require ( github.com/BurntSushi/toml v1.2.0 // indirect github.com/clbanning/mxj/v2 v2.7.0 // indirect github.com/fatih/color v1.15.0 // indirect - github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/go-logr/logr v1.2.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/grokify/html-strip-tags-go v0.0.1 // indirect github.com/magiconair/properties v1.8.6 // indirect github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.19 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-runewidth v0.0.15 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/rivo/uniseg v0.4.4 // indirect diff --git a/contrib/drivers/sqlitecgo/go.sum b/contrib/drivers/sqlitecgo/go.sum index 785f16d6cbe..22f425241f8 100644 --- a/contrib/drivers/sqlitecgo/go.sum +++ b/contrib/drivers/sqlitecgo/go.sum @@ -5,8 +5,8 @@ github.com/clbanning/mxj/v2 v2.7.0/go.mod h1:hNiWqW14h+kc+MdF9C6/YoRfjEJoR3ou6tn github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= -github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= -github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -22,8 +22,8 @@ github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPK github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= -github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= @@ -45,7 +45,6 @@ go.opentelemetry.io/otel/trace v1.14.0/go.mod h1:8avnQLK+CG77yNLUae4ea2JDQ6iT+go golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/contrib/nosql/redis/go.mod b/contrib/nosql/redis/go.mod index e7f4657fd0a..0284ad9f7d6 100644 --- a/contrib/nosql/redis/go.mod +++ b/contrib/nosql/redis/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/nosql/redis/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.5.6 + github.com/gogf/gf/v2 v2.5.7 github.com/redis/go-redis/v9 v9.2.1 go.opentelemetry.io/otel v1.14.0 go.opentelemetry.io/otel/trace v1.14.0 diff --git a/contrib/registry/etcd/go.mod b/contrib/registry/etcd/go.mod index 141a792a785..159a9c2100f 100644 --- a/contrib/registry/etcd/go.mod +++ b/contrib/registry/etcd/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/registry/etcd/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.5.6 + github.com/gogf/gf/v2 v2.5.7 go.etcd.io/etcd/client/v3 v3.5.7 ) diff --git a/contrib/registry/file/go.mod b/contrib/registry/file/go.mod index ff8f0f3c472..83b0ca1c506 100644 --- a/contrib/registry/file/go.mod +++ b/contrib/registry/file/go.mod @@ -2,7 +2,7 @@ module github.com/gogf/gf/contrib/registry/file/v2 go 1.18 -require github.com/gogf/gf/v2 v2.5.6 +require github.com/gogf/gf/v2 v2.5.7 require ( github.com/BurntSushi/toml v1.2.0 // indirect diff --git a/contrib/registry/nacos/go.mod b/contrib/registry/nacos/go.mod index 73535a600e9..d8830683ef6 100644 --- a/contrib/registry/nacos/go.mod +++ b/contrib/registry/nacos/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/registry/nacos/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.5.6 + github.com/gogf/gf/v2 v2.5.7 github.com/joy999/nacos-sdk-go v0.0.0-20231008093845-7f2f84bc6faa ) diff --git a/contrib/registry/polaris/go.mod b/contrib/registry/polaris/go.mod index 568dbaad55a..92c0663d2f0 100644 --- a/contrib/registry/polaris/go.mod +++ b/contrib/registry/polaris/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/registry/polaris/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.5.6 + github.com/gogf/gf/v2 v2.5.7 github.com/polarismesh/polaris-go v1.5.5 ) diff --git a/contrib/registry/zookeeper/go.mod b/contrib/registry/zookeeper/go.mod index 78054411246..61ebd46a1b9 100644 --- a/contrib/registry/zookeeper/go.mod +++ b/contrib/registry/zookeeper/go.mod @@ -4,7 +4,7 @@ go 1.18 require ( github.com/go-zookeeper/zk v1.0.3 - github.com/gogf/gf/v2 v2.5.6 + github.com/gogf/gf/v2 v2.5.7 golang.org/x/sync v0.4.0 ) diff --git a/contrib/rpc/grpcx/go.mod b/contrib/rpc/grpcx/go.mod index f287c8b0876..eb893110e5a 100644 --- a/contrib/rpc/grpcx/go.mod +++ b/contrib/rpc/grpcx/go.mod @@ -3,8 +3,8 @@ module github.com/gogf/gf/contrib/rpc/grpcx/v2 go 1.18 require ( - github.com/gogf/gf/contrib/registry/file/v2 v2.5.6 - github.com/gogf/gf/v2 v2.5.6 + github.com/gogf/gf/contrib/registry/file/v2 v2.5.7 + github.com/gogf/gf/v2 v2.5.7 go.opentelemetry.io/otel v1.14.0 go.opentelemetry.io/otel/trace v1.14.0 google.golang.org/grpc v1.57.2 diff --git a/contrib/sdk/httpclient/go.mod b/contrib/sdk/httpclient/go.mod index 091aaa9b81c..f848861ae92 100644 --- a/contrib/sdk/httpclient/go.mod +++ b/contrib/sdk/httpclient/go.mod @@ -2,20 +2,20 @@ module github.com/gogf/gf/contrib/sdk/httpclient/v2 go 1.18 -require github.com/gogf/gf/v2 v2.5.6 +require github.com/gogf/gf/v2 v2.5.7 require ( github.com/BurntSushi/toml v1.2.0 // indirect github.com/clbanning/mxj/v2 v2.7.0 // indirect github.com/fatih/color v1.15.0 // indirect - github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/go-logr/logr v1.2.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/grokify/html-strip-tags-go v0.0.1 // indirect github.com/magiconair/properties v1.8.6 // indirect github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.19 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-runewidth v0.0.15 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/rivo/uniseg v0.4.4 // indirect diff --git a/contrib/sdk/httpclient/go.sum b/contrib/sdk/httpclient/go.sum index 5eda040b679..f083621d94d 100644 --- a/contrib/sdk/httpclient/go.sum +++ b/contrib/sdk/httpclient/go.sum @@ -5,8 +5,8 @@ github.com/clbanning/mxj/v2 v2.7.0/go.mod h1:hNiWqW14h+kc+MdF9C6/YoRfjEJoR3ou6tn github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= -github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= -github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -22,8 +22,8 @@ github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPK github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= -github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= @@ -43,7 +43,6 @@ go.opentelemetry.io/otel/trace v1.14.0/go.mod h1:8avnQLK+CG77yNLUae4ea2JDQ6iT+go golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/contrib/trace/jaeger/go.mod b/contrib/trace/jaeger/go.mod index 15a3ae254ed..dd1ad15fc9c 100644 --- a/contrib/trace/jaeger/go.mod +++ b/contrib/trace/jaeger/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/trace/jaeger/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.5.6 + github.com/gogf/gf/v2 v2.5.7 go.opentelemetry.io/otel v1.14.0 go.opentelemetry.io/otel/exporters/jaeger v1.14.0 go.opentelemetry.io/otel/sdk v1.14.0 diff --git a/contrib/trace/jaeger/go.sum b/contrib/trace/jaeger/go.sum index 40f0d0e8d9f..96f073451d6 100644 --- a/contrib/trace/jaeger/go.sum +++ b/contrib/trace/jaeger/go.sum @@ -2,7 +2,7 @@ github.com/BurntSushi/toml v1.2.0 h1:Rt8g24XnyGTyglgET/PRUNlrUeu9F5L+7FilkXfZgs0 github.com/clbanning/mxj/v2 v2.7.0 h1:WA/La7UGCanFe5NpHF0Q3DNtnCsVoxbPKuyBNHWRyME= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= -github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -13,7 +13,7 @@ github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWm github.com/grokify/html-strip-tags-go v0.0.1 h1:0fThFwLbW7P/kOiTBs03FsJSV9RM2M/Q/MOnCQxKMo0= github.com/magiconair/properties v1.8.6 h1:5ibWZ6iY0NctNGWo87LalDlEZ6R41TqbbDamhfG/Qzo= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= -github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= diff --git a/contrib/trace/otlpgrpc/go.mod b/contrib/trace/otlpgrpc/go.mod index 7b08a175c91..867c1e99823 100644 --- a/contrib/trace/otlpgrpc/go.mod +++ b/contrib/trace/otlpgrpc/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/trace/otlpgrpc/v2 go 1.20 require ( - github.com/gogf/gf/v2 v2.5.6 + github.com/gogf/gf/v2 v2.5.7 go.opentelemetry.io/otel v1.19.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.19.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.19.0 @@ -12,11 +12,23 @@ require ( ) require ( + github.com/BurntSushi/toml v1.2.0 // indirect github.com/cenkalti/backoff/v4 v4.2.1 // indirect + github.com/clbanning/mxj/v2 v2.7.0 // indirect + github.com/fatih/color v1.15.0 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/go-logr/logr v1.2.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/golang/protobuf v1.5.3 // indirect + github.com/gorilla/websocket v1.5.0 // indirect + github.com/grokify/html-strip-tags-go v0.0.1 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.18.0 // indirect + github.com/magiconair/properties v1.8.6 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-runewidth v0.0.15 // indirect + github.com/olekukonko/tablewriter v0.0.5 // indirect + github.com/rivo/uniseg v0.4.4 // indirect go.opentelemetry.io/otel/metric v1.19.0 // indirect go.opentelemetry.io/otel/trace v1.19.0 // indirect go.opentelemetry.io/proto/otlp v1.0.0 // indirect @@ -26,6 +38,7 @@ require ( google.golang.org/genproto/googleapis/api v0.0.0-20231016165738-49dd2c1f3d0b // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20231016165738-49dd2c1f3d0b // indirect google.golang.org/protobuf v1.31.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect ) replace github.com/gogf/gf/v2 => ../../../ diff --git a/contrib/trace/otlpgrpc/go.sum b/contrib/trace/otlpgrpc/go.sum index 3c6af600b85..979a8865c22 100644 --- a/contrib/trace/otlpgrpc/go.sum +++ b/contrib/trace/otlpgrpc/go.sum @@ -1,10 +1,14 @@ github.com/BurntSushi/toml v1.2.0 h1:Rt8g24XnyGTyglgET/PRUNlrUeu9F5L+7FilkXfZgs0= +github.com/BurntSushi/toml v1.2.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/cenkalti/backoff/v4 v4.2.1 h1:y4OZtCnogmCPw98Zjyt5a6+QwPLGkiQsYW5oUqylYbM= github.com/cenkalti/backoff/v4 v4.2.1/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/clbanning/mxj/v2 v2.7.0 h1:WA/La7UGCanFe5NpHF0Q3DNtnCsVoxbPKuyBNHWRyME= +github.com/clbanning/mxj/v2 v2.7.0/go.mod h1:hNiWqW14h+kc+MdF9C6/YoRfjEJoR3ou6tn/Qo+ve2s= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= +github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -17,16 +21,30 @@ github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiu github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= +github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/grokify/html-strip-tags-go v0.0.1 h1:0fThFwLbW7P/kOiTBs03FsJSV9RM2M/Q/MOnCQxKMo0= +github.com/grokify/html-strip-tags-go v0.0.1/go.mod h1:2Su6romC5/1VXOQMaWL2yb618ARB8iVo6/DR99A6d78= github.com/grpc-ecosystem/grpc-gateway/v2 v2.18.0 h1:RtRsiaGvWxcwd8y3BiRZxsylPT8hLWZ5SPcfI+3IDNk= github.com/grpc-ecosystem/grpc-gateway/v2 v2.18.0/go.mod h1:TzP6duP4Py2pHLVPPQp42aoYI92+PCrVotyR5e8Vqlk= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/magiconair/properties v1.8.6 h1:5ibWZ6iY0NctNGWo87LalDlEZ6R41TqbbDamhfG/Qzo= +github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= +github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= +github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.4.4 h1:8TfxU8dW6PdqD27gjM8MVNuicgxIjxpm4K7x4jp8sis= +github.com/rivo/uniseg v0.4.4/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= go.opentelemetry.io/otel v1.19.0 h1:MuS/TNf4/j4IXsZuJegVzI1cwut7Qc00344rgH7p8bs= go.opentelemetry.io/otel v1.19.0/go.mod h1:i0QyjOq3UPoTzff0PJB2N66fb4S0+rSbSB15/oyH9fY= @@ -45,6 +63,8 @@ go.opentelemetry.io/proto/otlp v1.0.0/go.mod h1:Sy6pihPLfYHkr3NkUbEhGHFhINUSI/v8 go.uber.org/goleak v1.2.1 h1:NBol2c7O1ZokfZ0LEU9K6Whx/KnwvepVetCUhtKja4A= golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= @@ -61,4 +81,7 @@ google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp0 google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/contrib/trace/otlphttp/go.mod b/contrib/trace/otlphttp/go.mod index 0a070227e3b..83d998684ef 100644 --- a/contrib/trace/otlphttp/go.mod +++ b/contrib/trace/otlphttp/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/trace/otlphttp/v2 go 1.20 require ( - github.com/gogf/gf/v2 v2.5.6 + github.com/gogf/gf/v2 v2.5.7 go.opentelemetry.io/otel v1.19.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.19.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.19.0 @@ -11,11 +11,23 @@ require ( ) require ( + github.com/BurntSushi/toml v1.2.0 // indirect github.com/cenkalti/backoff/v4 v4.2.1 // indirect + github.com/clbanning/mxj/v2 v2.7.0 // indirect + github.com/fatih/color v1.15.0 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/go-logr/logr v1.2.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/golang/protobuf v1.5.3 // indirect + github.com/gorilla/websocket v1.5.0 // indirect + github.com/grokify/html-strip-tags-go v0.0.1 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.18.0 // indirect + github.com/magiconair/properties v1.8.6 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-runewidth v0.0.15 // indirect + github.com/olekukonko/tablewriter v0.0.5 // indirect + github.com/rivo/uniseg v0.4.4 // indirect go.opentelemetry.io/otel/metric v1.19.0 // indirect go.opentelemetry.io/otel/trace v1.19.0 // indirect go.opentelemetry.io/proto/otlp v1.0.0 // indirect @@ -27,6 +39,7 @@ require ( google.golang.org/genproto/googleapis/rpc v0.0.0-20231016165738-49dd2c1f3d0b // indirect google.golang.org/grpc v1.59.0 // indirect google.golang.org/protobuf v1.31.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect ) replace github.com/gogf/gf/v2 => ../../../ diff --git a/contrib/trace/otlphttp/go.sum b/contrib/trace/otlphttp/go.sum index 480f17db3bf..98fc4525241 100644 --- a/contrib/trace/otlphttp/go.sum +++ b/contrib/trace/otlphttp/go.sum @@ -1,10 +1,14 @@ github.com/BurntSushi/toml v1.2.0 h1:Rt8g24XnyGTyglgET/PRUNlrUeu9F5L+7FilkXfZgs0= +github.com/BurntSushi/toml v1.2.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/cenkalti/backoff/v4 v4.2.1 h1:y4OZtCnogmCPw98Zjyt5a6+QwPLGkiQsYW5oUqylYbM= github.com/cenkalti/backoff/v4 v4.2.1/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/clbanning/mxj/v2 v2.7.0 h1:WA/La7UGCanFe5NpHF0Q3DNtnCsVoxbPKuyBNHWRyME= +github.com/clbanning/mxj/v2 v2.7.0/go.mod h1:hNiWqW14h+kc+MdF9C6/YoRfjEJoR3ou6tn/Qo+ve2s= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= +github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -17,16 +21,30 @@ github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiu github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= +github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/grokify/html-strip-tags-go v0.0.1 h1:0fThFwLbW7P/kOiTBs03FsJSV9RM2M/Q/MOnCQxKMo0= +github.com/grokify/html-strip-tags-go v0.0.1/go.mod h1:2Su6romC5/1VXOQMaWL2yb618ARB8iVo6/DR99A6d78= github.com/grpc-ecosystem/grpc-gateway/v2 v2.18.0 h1:RtRsiaGvWxcwd8y3BiRZxsylPT8hLWZ5SPcfI+3IDNk= github.com/grpc-ecosystem/grpc-gateway/v2 v2.18.0/go.mod h1:TzP6duP4Py2pHLVPPQp42aoYI92+PCrVotyR5e8Vqlk= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/magiconair/properties v1.8.6 h1:5ibWZ6iY0NctNGWo87LalDlEZ6R41TqbbDamhfG/Qzo= +github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= +github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= +github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.4.4 h1:8TfxU8dW6PdqD27gjM8MVNuicgxIjxpm4K7x4jp8sis= +github.com/rivo/uniseg v0.4.4/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= go.opentelemetry.io/otel v1.19.0 h1:MuS/TNf4/j4IXsZuJegVzI1cwut7Qc00344rgH7p8bs= go.opentelemetry.io/otel v1.19.0/go.mod h1:i0QyjOq3UPoTzff0PJB2N66fb4S0+rSbSB15/oyH9fY= @@ -44,6 +62,8 @@ go.opentelemetry.io/proto/otlp v1.0.0 h1:T0TX0tmXU8a3CbNXzEKGeU5mIVOdf0oykP+u2lI go.opentelemetry.io/proto/otlp v1.0.0/go.mod h1:Sy6pihPLfYHkr3NkUbEhGHFhINUSI/v80hjKIs5JXpM= golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= @@ -61,4 +81,7 @@ google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp0 google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/example/go.mod b/example/go.mod index 5566a66169e..c95a2700d82 100644 --- a/example/go.mod +++ b/example/go.mod @@ -3,21 +3,21 @@ module github.com/gogf/gf/example go 1.20 require ( - github.com/gogf/gf/contrib/config/apollo/v2 v2.5.6 - github.com/gogf/gf/contrib/config/consul/v2 v2.5.6 - github.com/gogf/gf/contrib/config/kubecm/v2 v2.5.6 - github.com/gogf/gf/contrib/config/nacos/v2 v2.5.6 - github.com/gogf/gf/contrib/config/polaris/v2 v2.5.6 - github.com/gogf/gf/contrib/drivers/mysql/v2 v2.5.6 - github.com/gogf/gf/contrib/nosql/redis/v2 v2.5.6 - github.com/gogf/gf/contrib/registry/etcd/v2 v2.5.6 - github.com/gogf/gf/contrib/registry/file/v2 v2.5.6 + github.com/gogf/gf/contrib/config/apollo/v2 v2.5.7 + github.com/gogf/gf/contrib/config/consul/v2 v2.5.7 + github.com/gogf/gf/contrib/config/kubecm/v2 v2.5.7 + github.com/gogf/gf/contrib/config/nacos/v2 v2.5.7 + github.com/gogf/gf/contrib/config/polaris/v2 v2.5.7 + github.com/gogf/gf/contrib/drivers/mysql/v2 v2.5.7 + github.com/gogf/gf/contrib/nosql/redis/v2 v2.5.7 + github.com/gogf/gf/contrib/registry/etcd/v2 v2.5.7 + github.com/gogf/gf/contrib/registry/file/v2 v2.5.7 github.com/gogf/gf/contrib/registry/nacos/v2 v2.5.6 - github.com/gogf/gf/contrib/registry/polaris/v2 v2.5.6 - github.com/gogf/gf/contrib/rpc/grpcx/v2 v2.5.6 - github.com/gogf/gf/contrib/trace/otlpgrpc/v2 v2.5.6 - github.com/gogf/gf/contrib/trace/otlphttp/v2 v2.5.6 - github.com/gogf/gf/v2 v2.5.6 + github.com/gogf/gf/contrib/registry/polaris/v2 v2.5.7 + github.com/gogf/gf/contrib/rpc/grpcx/v2 v2.5.7 + github.com/gogf/gf/contrib/trace/otlpgrpc/v2 v2.5.7 + github.com/gogf/gf/contrib/trace/otlphttp/v2 v2.5.7 + github.com/gogf/gf/v2 v2.5.7 github.com/hashicorp/consul/api v1.24.0 github.com/hashicorp/go-cleanhttp v0.5.2 github.com/nacos-group/nacos-sdk-go v1.1.4 diff --git a/version.go b/version.go index 0526e4fa532..2cd4a2f6ea7 100644 --- a/version.go +++ b/version.go @@ -2,5 +2,5 @@ package gf const ( // VERSION is the current GoFrame version. - VERSION = "v2.5.6" + VERSION = "v2.5.7" ) From d3d1f94e403e808a239fd4367a1bce4901ce7808 Mon Sep 17 00:00:00 2001 From: Hunk Zhu Date: Mon, 20 Nov 2023 20:47:00 +0800 Subject: [PATCH 14/52] Upgrade nacos sdk to latest version (#3166) --- contrib/registry/nacos/go.mod | 10 ++++++++-- contrib/registry/nacos/go.sum | 23 +++++++++++++++++++---- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/contrib/registry/nacos/go.mod b/contrib/registry/nacos/go.mod index d8830683ef6..bddf9aaa5be 100644 --- a/contrib/registry/nacos/go.mod +++ b/contrib/registry/nacos/go.mod @@ -4,12 +4,17 @@ go 1.18 require ( github.com/gogf/gf/v2 v2.5.7 - github.com/joy999/nacos-sdk-go v0.0.0-20231008093845-7f2f84bc6faa + github.com/joy999/nacos-sdk-go v0.0.0-20231120071639-10a34b3e7288 ) require ( github.com/BurntSushi/toml v1.2.0 // indirect - github.com/aliyun/alibaba-cloud-sdk-go v1.61.1704 // indirect + github.com/alibabacloud-go/debug v0.0.0-20190504072949-9472017b5c68 // indirect + github.com/alibabacloud-go/tea v1.1.17 // indirect + github.com/alibabacloud-go/tea-utils v1.4.4 // indirect + github.com/aliyun/alibaba-cloud-sdk-go v1.61.1800 // indirect + github.com/aliyun/alibabacloud-dkms-gcs-go-sdk v0.2.2 // indirect + github.com/aliyun/alibabacloud-dkms-transfer-go-sdk v0.1.7 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/buger/jsonparser v1.1.1 // indirect github.com/cespare/xxhash/v2 v2.2.0 // indirect @@ -44,6 +49,7 @@ require ( go.uber.org/atomic v1.7.0 // indirect go.uber.org/multierr v1.6.0 // indirect go.uber.org/zap v1.21.0 // indirect + golang.org/x/crypto v0.14.0 // indirect golang.org/x/net v0.17.0 // indirect golang.org/x/sync v0.1.0 // indirect golang.org/x/sys v0.13.0 // indirect diff --git a/contrib/registry/nacos/go.sum b/contrib/registry/nacos/go.sum index bddc41df796..34d01709186 100644 --- a/contrib/registry/nacos/go.sum +++ b/contrib/registry/nacos/go.sum @@ -40,8 +40,19 @@ github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuy github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= -github.com/aliyun/alibaba-cloud-sdk-go v1.61.1704 h1:PpfENOj/vPfhhy9N2OFRjpue0hjM5XqAp2thFmkXXIk= -github.com/aliyun/alibaba-cloud-sdk-go v1.61.1704/go.mod h1:RcDobYh8k5VP6TNybz9m++gL3ijVI5wueVr0EM10VsU= +github.com/alibabacloud-go/debug v0.0.0-20190504072949-9472017b5c68 h1:NqugFkGxx1TXSh/pBcU00Y6bljgDPaFdh5MUSeJ7e50= +github.com/alibabacloud-go/debug v0.0.0-20190504072949-9472017b5c68/go.mod h1:6pb/Qy8c+lqua8cFpEy7g39NRRqOWc3rOwAy8m5Y2BY= +github.com/alibabacloud-go/tea v1.1.0/go.mod h1:IkGyUSX4Ba1V+k4pCtJUc6jDpZLFph9QMy2VUPTwukg= +github.com/alibabacloud-go/tea v1.1.17 h1:05R5DnaJXe9sCNIe8KUgWHC/z6w/VZIwczgUwzRnul8= +github.com/alibabacloud-go/tea v1.1.17/go.mod h1:nXxjm6CIFkBhwW4FQkNrolwbfon8Svy6cujmKFUq98A= +github.com/alibabacloud-go/tea-utils v1.4.4 h1:lxCDvNCdTo9FaXKKq45+4vGETQUKNOW/qKTcX9Sk53o= +github.com/alibabacloud-go/tea-utils v1.4.4/go.mod h1:KNcT0oXlZZxOXINnZBs6YvgOd5aYp9U67G+E3R8fcQw= +github.com/aliyun/alibaba-cloud-sdk-go v1.61.1800 h1:ie/8RxBOfKZWcrbYSJi2Z8uX8TcOlSMwPlEJh83OeOw= +github.com/aliyun/alibaba-cloud-sdk-go v1.61.1800/go.mod h1:RcDobYh8k5VP6TNybz9m++gL3ijVI5wueVr0EM10VsU= +github.com/aliyun/alibabacloud-dkms-gcs-go-sdk v0.2.2 h1:rWkH6D2XlXb/Y+tNAQROxBzp3a0p92ni+pXcaHBe/WI= +github.com/aliyun/alibabacloud-dkms-gcs-go-sdk v0.2.2/go.mod h1:GDtq+Kw+v0fO+j5BrrWiUHbBq7L+hfpzpPfXKOZMFE0= +github.com/aliyun/alibabacloud-dkms-transfer-go-sdk v0.1.7 h1:olLiPI2iM8Hqq6vKnSxpM3awCrm9/BeOgHpzQkOYnI4= +github.com/aliyun/alibabacloud-dkms-transfer-go-sdk v0.1.7/go.mod h1:oDg1j4kFxnhgftaiLJABkGeSvuEvSF5Lo6UmRAMruX4= github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= @@ -155,8 +166,8 @@ github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= -github.com/joy999/nacos-sdk-go v0.0.0-20231008093845-7f2f84bc6faa h1:FPzhsWW/aZQKw9tWOTvLc8lpKLGnPVBMaF0B+DIvKlc= -github.com/joy999/nacos-sdk-go v0.0.0-20231008093845-7f2f84bc6faa/go.mod h1:vks3UUh7Hp+e5qbvDySGnvVCD0RYqjyDy/RpVMSf3xc= +github.com/joy999/nacos-sdk-go v0.0.0-20231120071639-10a34b3e7288 h1:GuL6co0J2oMb2Rd/hbxZfJz1QlZr+DpIsz3Wcvok65o= +github.com/joy999/nacos-sdk-go v0.0.0-20231120071639-10a34b3e7288/go.mod h1:xF3RcNkFUEIik3RCihkvgORtZXZXlp+OeGK0aUALVYU= github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= github.com/json-iterator/go v1.1.5/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= @@ -241,6 +252,7 @@ github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXf github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= @@ -270,7 +282,10 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc= +golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= From 83f08b31355e5e8c85355ed1a01223938d47696c Mon Sep 17 00:00:00 2001 From: John Guo Date: Mon, 20 Nov 2023 20:47:26 +0800 Subject: [PATCH 15/52] fix issue in Join stements with prefix specified for package gdb (#3151) --- cmd/gf/go.sum | 14 ++ contrib/drivers/mssql/mssql_z_model_test.go | 5 +- contrib/drivers/mysql/mysql_model_test.go | 43 +++++ .../drivers/mysql/testdata/fix_gdb_join.sql | 151 ++++++++++++++++++ .../mysql/testdata/fix_gdb_join_expect.sql | 1 + contrib/drivers/oracle/oracle_z_model_test.go | 2 + contrib/drivers/sqlite/sqlite_model_test.go | 2 + .../drivers/sqlitecgo/sqlite_model_test.go | 2 + database/gdb/gdb.go | 2 +- database/gdb/gdb_core.go | 38 +++-- database/gdb/gdb_func.go | 2 +- database/gdb/gdb_model.go | 86 +++++----- database/gdb/gdb_model_fields.go | 32 ++-- database/gdb/gdb_model_join.go | 21 ++- database/gdb/gdb_model_utility.go | 15 +- 15 files changed, 340 insertions(+), 76 deletions(-) create mode 100644 contrib/drivers/mysql/testdata/fix_gdb_join.sql create mode 100644 contrib/drivers/mysql/testdata/fix_gdb_join_expect.sql diff --git a/cmd/gf/go.sum b/cmd/gf/go.sum index bb5f8a4a868..533674fa5aa 100644 --- a/cmd/gf/go.sum +++ b/cmd/gf/go.sum @@ -38,6 +38,20 @@ github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiU github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI= github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= +github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.5.6 h1:yziPSf9AycEWphv9WiNjcRAVPOJtUauMMvP6pHQB4jY= +github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.5.6/go.mod h1:yOlpwhFXgW+P2sf4goA20PUtxdVLliBx4dJRyJeOtto= +github.com/gogf/gf/contrib/drivers/mssql/v2 v2.5.6 h1:LGQIe5IvYVr4hZ/vUAFiqWssxE7QeILyVPJ9swo1Cmk= +github.com/gogf/gf/contrib/drivers/mssql/v2 v2.5.6/go.mod h1:EcF8v8jqCV61/YqN6DXxdo3kh8waGmEj6WpFqbLkkrM= +github.com/gogf/gf/contrib/drivers/mysql/v2 v2.5.6 h1:oR9F4LVoKa/fjf/o6Y/CQRNiYy35Bszo07WwvMWYMxo= +github.com/gogf/gf/contrib/drivers/mysql/v2 v2.5.6/go.mod h1:gvHSRqCpv2c+N0gDHsEldHgU/yM9tcCBdIEKZ32/TaE= +github.com/gogf/gf/contrib/drivers/oracle/v2 v2.5.6 h1:3Y3lEoO9SoG1AmfaKjgTsDt93+T2q/qTMog8wBvIIGM= +github.com/gogf/gf/contrib/drivers/oracle/v2 v2.5.6/go.mod h1:cR3lFoU6ZtSaMQ3DpCJwWnYW6EvHPYGGeqv/kzgH4gw= +github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.5.6 h1:0WHVzqITqIBu/NNPXt3tN2eiWAGiNjs9sg6wh+WbUvY= +github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.5.6/go.mod h1:qZCTNQ0n2gHcuBwM9wUl3pelync3xK0gTnChJZD6f0I= +github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.5.6 h1:6clfLvFoHXHdw+skmXg4yxw+cLwgAG8gRiS/6f9Y9Xc= +github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.5.6/go.mod h1:QV6Rrj+4G4OaJVkP9XXRZ1LWL+ls6qH7ebeMcxsulqA= +github.com/gogf/gf/v2 v2.5.6 h1:a1UK1yUP3s+l+vPxmV91+8gTarAP9b1IEOw0W7LNl6E= +github.com/gogf/gf/v2 v2.5.6/go.mod h1:17K/gBYrp0bHGC3XYC7bSPoywmZ6MrZHrZakTfh4eIQ= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY= github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= diff --git a/contrib/drivers/mssql/mssql_z_model_test.go b/contrib/drivers/mssql/mssql_z_model_test.go index 2310493a320..7a809039fc7 100644 --- a/contrib/drivers/mssql/mssql_z_model_test.go +++ b/contrib/drivers/mssql/mssql_z_model_test.go @@ -9,10 +9,11 @@ package mssql_test import ( "database/sql" "fmt" - "github.com/gogf/gf/v2/util/gconv" "testing" "time" + "github.com/gogf/gf/v2/util/gconv" + "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/database/gdb" @@ -1906,12 +1907,14 @@ func Test_Model_HasTable(t *testing.T) { defer dropTable(table) gtest.C(t, func(t *gtest.T) { + t.AssertNil(db.GetCore().ClearCacheAll(ctx)) result, err := db.GetCore().HasTable(table) t.Assert(result, true) t.AssertNil(err) }) gtest.C(t, func(t *gtest.T) { + t.AssertNil(db.GetCore().ClearCacheAll(ctx)) result, err := db.GetCore().HasTable("table12321") t.Assert(result, false) t.AssertNil(err) diff --git a/contrib/drivers/mysql/mysql_model_test.go b/contrib/drivers/mysql/mysql_model_test.go index 230100f760b..1a2c7e1f152 100644 --- a/contrib/drivers/mysql/mysql_model_test.go +++ b/contrib/drivers/mysql/mysql_model_test.go @@ -3097,12 +3097,14 @@ func Test_Model_HasTable(t *testing.T) { defer dropTable(table) gtest.C(t, func(t *gtest.T) { + t.AssertNil(db.GetCore().ClearCacheAll(ctx)) result, err := db.GetCore().HasTable(table) t.Assert(result, true) t.AssertNil(err) }) gtest.C(t, func(t *gtest.T) { + t.AssertNil(db.GetCore().ClearCacheAll(ctx)) result, err := db.GetCore().HasTable("table12321") t.Assert(result, false) t.AssertNil(err) @@ -4706,3 +4708,44 @@ func Test_Scan_Nil_Result_Error(t *testing.T) { t.Assert(err, sql.ErrNoRows) }) } + +func Test_Model_FixGdbJoin(t *testing.T) { + array := gstr.SplitAndTrim(gtest.DataContent(`fix_gdb_join.sql`), ";") + for _, v := range array { + if _, err := db.Exec(ctx, v); err != nil { + gtest.Error(err) + } + } + defer dropTable(`common_resource`) + defer dropTable(`managed_resource`) + defer dropTable(`rules_template`) + defer dropTable(`resource_mark`) + gtest.C(t, func(t *gtest.T) { + t.AssertNil(db.GetCore().ClearCacheAll(ctx)) + sqlSlice, err := gdb.CatchSQL(ctx, func(ctx context.Context) error { + orm := db.Model(`managed_resource`).Ctx(ctx). + LeftJoinOnField(`common_resource`, `resource_id`). + LeftJoinOnFields(`resource_mark`, `resource_mark_id`, `=`, `id`). + LeftJoinOnFields(`rules_template`, `rule_template_id`, `=`, `template_id`). + FieldsPrefix( + `managed_resource`, + "resource_id", "user", "status", "status_message", "safe_publication", "rule_template_id", + "created_at", "comments", "expired_at", "resource_mark_id", "instance_id", "resource_name", + "pay_mode"). + FieldsPrefix(`resource_mark`, "mark_name", "color"). + FieldsPrefix(`rules_template`, "name"). + FieldsPrefix(`common_resource`, `src_instance_id`, "database_kind", "source_type", "ip", "port") + all, err := orm.OrderAsc("src_instance_id").All() + t.Assert(len(all), 4) + t.Assert(all[0]["pay_mode"], 1) + t.Assert(all[0]["src_instance_id"], 2) + t.Assert(all[3]["instance_id"], "dmcins-jxy0x75m") + t.Assert(all[3]["src_instance_id"], "vdb-6b6m3u1u") + t.Assert(all[3]["resource_mark_id"], "11") + return err + }) + t.AssertNil(err) + + t.Assert(gtest.DataContent(`fix_gdb_join_expect.sql`), sqlSlice[len(sqlSlice)-1]) + }) +} diff --git a/contrib/drivers/mysql/testdata/fix_gdb_join.sql b/contrib/drivers/mysql/testdata/fix_gdb_join.sql new file mode 100644 index 00000000000..48cf1efb315 --- /dev/null +++ b/contrib/drivers/mysql/testdata/fix_gdb_join.sql @@ -0,0 +1,151 @@ + + +DROP TABLE IF EXISTS `common_resource`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `common_resource` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, + `app_id` bigint(20) NOT NULL, + `resource_id` varchar(64) NOT NULL, + `src_instance_id` varchar(64) DEFAULT NULL, + `region` varchar(36) DEFAULT NULL, + `zone` varchar(36) DEFAULT NULL, + `database_kind` varchar(20) NOT NULL, + `source_type` varchar(64) NOT NULL, + `ip` varchar(64) DEFAULT NULL, + `port` int(10) DEFAULT NULL, + `vpc_id` varchar(20) DEFAULT NULL, + `subnet_id` varchar(20) DEFAULT NULL, + `proxy_ip` varchar(64) DEFAULT NULL, + `proxy_port` int(10) DEFAULT NULL, + `proxy_id` bigint(20) DEFAULT NULL, + `proxy_snat_ip` varchar(64) DEFAULT NULL, + `lease_at` timestamp NULL DEFAULT NULL, + `uin` varchar(32) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `unique_resource` (`app_id`,`src_instance_id`,`vpc_id`,`subnet_id`,`ip`,`port`), + KEY `resource_id` (`resource_id`) +) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8mb4 COMMENT='资源公共信息表'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `common_resource` +-- + +LOCK TABLES `common_resource` WRITE; +/*!40000 ALTER TABLE `common_resource` DISABLE KEYS */; +INSERT INTO `common_resource` VALUES (1,1,'2','2','2','3','1','1','1',1,'1','1','1',1,1,'1',NULL,''),(3,2,'3','3','3','3','3','3','3',3,'3','3','3',3,3,'3',NULL,''),(18,1303697168,'dmc-rgnh9qre','vdb-6b6m3u1u','ap-guangzhou','','vdb','cloud','10.0.1.16',80,'vpc-m3dchft7','subnet-9as3a3z2','9.27.72.189',11131,228476,'169.254.128.5, ','2023-11-08 08:13:04',''),(20,1303697168,'dmc-4grzi4jg','tdsqlshard-313spncx','ap-guangzhou','','tdsql','cloud','10.255.0.27',3306,'vpc-407k0e8x','subnet-qhkkk3bo','30.86.239.200',24087,0,'',NULL,''); +/*!40000 ALTER TABLE `common_resource` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `managed_resource` +-- + +DROP TABLE IF EXISTS `managed_resource`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `managed_resource` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, + `instance_id` varchar(64) NOT NULL, + `resource_id` varchar(64) NOT NULL, + `resource_name` varchar(64) DEFAULT NULL, + `status` varchar(36) NOT NULL DEFAULT 'valid', + `status_message` varchar(64) DEFAULT NULL, + `user` varchar(64) NOT NULL, + `password` varchar(1024) NOT NULL, + `pay_mode` tinyint(1) DEFAULT '0', + `safe_publication` bit(1) DEFAULT b'0', + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `expired_at` timestamp NULL DEFAULT NULL, + `deleted` tinyint(1) NOT NULL DEFAULT '0', + `resource_mark_id` int(11) DEFAULT NULL, + `comments` varchar(64) DEFAULT NULL, + `rule_template_id` varchar(64) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `resource_id` (`resource_id`), + KEY `instance_id` (`instance_id`) +) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COMMENT='管控实例表'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `managed_resource` +-- + +LOCK TABLES `managed_resource` WRITE; +/*!40000 ALTER TABLE `managed_resource` DISABLE KEYS */; +INSERT INTO `managed_resource` VALUES (1,'2','3','1','1','1','1','1',1,_binary '','2023-11-06 12:14:21','2023-11-06 12:14:21',NULL,1,1,'1',''),(2,'3','2','1','1','1','1','1',1,_binary '\0','2023-11-06 12:15:07','2023-11-06 12:15:07',NULL,1,2,'1',''),(5,'dmcins-jxy0x75m','dmc-rgnh9qre','erichmao-vdb-test','invalid','The Ip field is required','root','2e39af3dd1d447e2b1437b40c62c35995fa22b370c7455ff7815dace3a6e8891ccadcfc893fe1342a4102d742bd7a3e603cd0ac1fcdc072d7c0b5be5836ec87306981b629f9b59aedf0316e9504ab172fa1c95756d5b260114e4feaa0b19223fb61cb268cc4818307ed193dbab830cf556b91cde182686eb70f70ea77f69eff66230dec2ce92bd3352cad31abf47597a5cc6a0d638381dc3bae7aa1b142730790a6d4cefdef1bd460061c966ad5008c2b5fc971b7f4d7dddffa5b1456c45e2917763dd8fffb1fa7fc4783feca95dafc9a9f4edf21b0579f76b0a3154f087e3b9a7fc49af8ff92b12e7b03caa865e72e777dd9d35a11910df0d55ead90e47d5f8',1,_binary '','2023-11-08 08:13:20','2023-11-09 05:31:07',NULL,0,11,NULL,'12345'),(6,'dmcins-erxms6ya','dmc-4grzi4jg','erichmao-vdb-test','invalid','The Ip field is required','leotaowang','641d846cf75bc7944202251d97dca8335f7f149dd4fd911ca5b87c71ef1dc5d0a66c4e5021ef7ad53136cda2fb2567d34e3dd1a7666e3f64ebf532eb2a55d84952aac86b4211f563f7b9da7dd0f88ec288d6680d3513cea0c1b7ad7babb474717f77ebbc9d63bb458adaf982887da9e63df957ffda572c1c3ed187471b99fdc640b45fed76a6d50dc1090eee79b4d94d056c4d43416133481f55bd040759398680104a84d801e6475dcfe919a00859908296747430b728a00c8d54256ae220235a138e0bbf08fe8b6fc8589971436b55bff966154721a91adbdc9c2b6f50ef5849ed77e5b028116abac51584b8d401cd3a88d18df127006358ed33fc3fa6f480',1,_binary '','2023-11-08 22:15:17','2023-11-09 05:31:07',NULL,0,11,NULL,'12345'); +/*!40000 ALTER TABLE `managed_resource` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `rules_template` +-- + +DROP TABLE IF EXISTS `rules_template`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `rules_template` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `app_id` bigint(20) DEFAULT NULL, + `name` varchar(255) NOT NULL, + `database_kind` varchar(64) DEFAULT NULL, + `is_default` tinyint(1) NOT NULL DEFAULT '0', + `win_rules` varchar(2048) DEFAULT NULL, + `inception_rules` varchar(2048) DEFAULT NULL, + `auto_exec_rules` varchar(2048) DEFAULT NULL, + `order_check_step` varchar(2048) DEFAULT NULL, + `template_id` varchar(64) NOT NULL DEFAULT '', + `version` int(11) NOT NULL DEFAULT '1', + `deleted` tinyint(1) NOT NULL DEFAULT '0', + `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `update_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `is_system` tinyint(1) NOT NULL DEFAULT '0', + `uin` varchar(64) DEFAULT NULL, + `subAccountUin` varchar(64) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uniq_template_id` (`template_id`), + UNIQUE KEY `uniq_name` (`name`,`app_id`,`deleted`,`uin`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8mb4; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `rules_template` +-- + +LOCK TABLES `rules_template` WRITE; +/*!40000 ALTER TABLE `rules_template` DISABLE KEYS */; +/*!40000 ALTER TABLE `rules_template` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `resource_mark` +-- + +DROP TABLE IF EXISTS `resource_mark`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `resource_mark` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, + `app_id` bigint(20) NOT NULL, + `mark_name` varchar(64) NOT NULL, + `color` varchar(11) NOT NULL, + `creator` varchar(32) NOT NULL, + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `app_id_name` (`app_id`,`mark_name`) +) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8 COMMENT='标签信息表'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `resource_mark` +-- + +LOCK TABLES `resource_mark` WRITE; +/*!40000 ALTER TABLE `resource_mark` DISABLE KEYS */; +INSERT INTO `resource_mark` VALUES (10,1,'test','red','1','2023-11-06 02:45:46','2023-11-06 02:45:46'); +/*!40000 ALTER TABLE `resource_mark` ENABLE KEYS */; +UNLOCK TABLES; + diff --git a/contrib/drivers/mysql/testdata/fix_gdb_join_expect.sql b/contrib/drivers/mysql/testdata/fix_gdb_join_expect.sql new file mode 100644 index 00000000000..c391675cbb6 --- /dev/null +++ b/contrib/drivers/mysql/testdata/fix_gdb_join_expect.sql @@ -0,0 +1 @@ +SELECT managed_resource.resource_id,managed_resource.user,managed_resource.status,managed_resource.status_message,managed_resource.safe_publication,managed_resource.rule_template_id,managed_resource.created_at,managed_resource.comments,managed_resource.expired_at,managed_resource.resource_mark_id,managed_resource.instance_id,managed_resource.resource_name,managed_resource.pay_mode,resource_mark.mark_name,resource_mark.color,rules_template.name,common_resource.src_instance_id,common_resource.database_kind,common_resource.source_type,common_resource.ip,common_resource.port FROM `managed_resource` LEFT JOIN `common_resource` ON (`managed_resource`.`resource_id`=`common_resource`.`resource_id`) LEFT JOIN `resource_mark` ON (`managed_resource`.`resource_mark_id` = `resource_mark`.`id`) LEFT JOIN `rules_template` ON (`managed_resource`.`rule_template_id` = `rules_template`.`template_id`) ORDER BY `src_instance_id` ASC \ No newline at end of file diff --git a/contrib/drivers/oracle/oracle_z_model_test.go b/contrib/drivers/oracle/oracle_z_model_test.go index 1ab58ddd3a1..d50d46cfee5 100644 --- a/contrib/drivers/oracle/oracle_z_model_test.go +++ b/contrib/drivers/oracle/oracle_z_model_test.go @@ -950,12 +950,14 @@ func Test_Model_HasTable(t *testing.T) { defer dropTable(table) // db.SetDebug(true) gtest.C(t, func(t *gtest.T) { + t.AssertNil(db.GetCore().ClearCacheAll(ctx)) result, err := db.GetCore().HasTable(strings.ToUpper(table)) t.Assert(result, true) t.AssertNil(err) }) gtest.C(t, func(t *gtest.T) { + t.AssertNil(db.GetCore().ClearCacheAll(ctx)) result, err := db.GetCore().HasTable("table12321") t.Assert(result, false) t.AssertNil(err) diff --git a/contrib/drivers/sqlite/sqlite_model_test.go b/contrib/drivers/sqlite/sqlite_model_test.go index f39804f1ef6..a6d6f61a57e 100644 --- a/contrib/drivers/sqlite/sqlite_model_test.go +++ b/contrib/drivers/sqlite/sqlite_model_test.go @@ -2807,12 +2807,14 @@ func Test_Model_HasTable(t *testing.T) { defer dropTable(table) gtest.C(t, func(t *gtest.T) { + t.AssertNil(db.GetCore().ClearCacheAll(ctx)) result, err := db.GetCore().HasTable(table) t.Assert(result, true) t.AssertNil(err) }) gtest.C(t, func(t *gtest.T) { + t.AssertNil(db.GetCore().ClearCacheAll(ctx)) result, err := db.GetCore().HasTable("table12321") t.Assert(result, false) t.AssertNil(err) diff --git a/contrib/drivers/sqlitecgo/sqlite_model_test.go b/contrib/drivers/sqlitecgo/sqlite_model_test.go index 8aa297e7a2b..b9f1760d184 100644 --- a/contrib/drivers/sqlitecgo/sqlite_model_test.go +++ b/contrib/drivers/sqlitecgo/sqlite_model_test.go @@ -2835,12 +2835,14 @@ func Test_Model_HasTable(t *testing.T) { defer dropTable(table) gtest.C(t, func(t *gtest.T) { + t.AssertNil(db.GetCore().ClearCacheAll(ctx)) result, err := db.GetCore().HasTable(table) t.Assert(result, true) t.AssertNil(err) }) gtest.C(t, func(t *gtest.T) { + t.AssertNil(db.GetCore().ClearCacheAll(ctx)) result, err := db.GetCore().HasTable("table12321") t.Assert(result, false) t.AssertNil(err) diff --git a/database/gdb/gdb.go b/database/gdb/gdb.go index 1c3344149cb..e0ddc0329bc 100644 --- a/database/gdb/gdb.go +++ b/database/gdb/gdb.go @@ -353,7 +353,7 @@ type ( type CatchSQLManager struct { SQLArray *garray.StrArray - DoCommit bool + DoCommit bool // DoCommit marks it will be committed to underlying driver or not. } const ( diff --git a/database/gdb/gdb_core.go b/database/gdb/gdb_core.go index f4ac5f7817f..482caf80b47 100644 --- a/database/gdb/gdb_core.go +++ b/database/gdb/gdb_core.go @@ -762,27 +762,37 @@ func (c *Core) writeSqlToLogger(ctx context.Context, sql *Sql) { // HasTable determine whether the table name exists in the database. func (c *Core) HasTable(name string) (bool, error) { + tables, err := c.GetTablesWithCache() + if err != nil { + return false, err + } + for _, table := range tables { + if table == name { + return true, nil + } + } + return false, nil +} + +// GetTablesWithCache retrieves and returns the table names of current database with cache. +func (c *Core) GetTablesWithCache() ([]string, error) { var ( ctx = c.db.GetCtx() - cacheKey = fmt.Sprintf(`HasTable: %s`, name) + cacheKey = fmt.Sprintf(`Tables: %s`, c.db.GetGroup()) ) - result, err := c.GetCache().GetOrSetFuncLock(ctx, cacheKey, func(ctx context.Context) (interface{}, error) { - tableList, err := c.db.Tables(ctx) - if err != nil { - return false, err - } - for _, table := range tableList { - if table == name { - return true, nil + result, err := c.GetCache().GetOrSetFuncLock( + ctx, cacheKey, func(ctx context.Context) (interface{}, error) { + tableList, err := c.db.Tables(ctx) + if err != nil { + return false, err } - } - return false, nil - }, 0, + return tableList, nil + }, 0, ) if err != nil { - return false, err + return nil, err } - return result.Bool(), nil + return result.Strings(), nil } // isSoftCreatedFieldName checks and returns whether given field name is an automatic-filled created time. diff --git a/database/gdb/gdb_func.go b/database/gdb/gdb_func.go index 7df37ce3a6c..28710a203c3 100644 --- a/database/gdb/gdb_func.go +++ b/database/gdb/gdb_func.go @@ -96,7 +96,7 @@ func DBFromCtx(ctx context.Context) DB { return nil } -// ToSQL formats and returns the last one of sql statements in given closure function. +// ToSQL formats and returns the last one of sql statements in given closure function without truly executing it. func ToSQL(ctx context.Context, f func(ctx context.Context) error) (sql string, err error) { var manager = &CatchSQLManager{ SQLArray: garray.NewStrArray(), diff --git a/database/gdb/gdb_model.go b/database/gdb/gdb_model.go index 5e70154b989..dc8f596bac7 100644 --- a/database/gdb/gdb_model.go +++ b/database/gdb/gdb_model.go @@ -17,39 +17,40 @@ import ( // Model is core struct implementing the DAO for ORM. type Model struct { - db DB // Underlying DB interface. - tx TX // Underlying TX interface. - rawSql string // rawSql is the raw SQL string which marks a raw SQL based Model not a table based Model. - schema string // Custom database schema. - linkType int // Mark for operation on master or slave. - tablesInit string // Table names when model initialization. - tables string // Operation table names, which can be more than one table names and aliases, like: "user", "user u", "user u, user_detail ud". - fields string // Operation fields, multiple fields joined using char ','. - fieldsEx string // Excluded operation fields, multiple fields joined using char ','. - withArray []interface{} // Arguments for With feature. - withAll bool // Enable model association operations on all objects that have "with" tag in the struct. - extraArgs []interface{} // Extra custom arguments for sql, which are prepended to the arguments before sql committed to underlying driver. - whereBuilder *WhereBuilder // Condition builder for where operation. - groupBy string // Used for "group by" statement. - orderBy string // Used for "order by" statement. - having []interface{} // Used for "having..." statement. - start int // Used for "select ... start, limit ..." statement. - limit int // Used for "select ... start, limit ..." statement. - option int // Option for extra operation features. - offset int // Offset statement for some databases grammar. - partition string // Partition table partition name. - data interface{} // Data for operation, which can be type of map/[]map/struct/*struct/string, etc. - batch int // Batch number for batch Insert/Replace/Save operations. - 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, which is mainly for indicating cache duration(especially 0) usage. - cacheOption CacheOption // Cache option for query statement. - hookHandler HookHandler // Hook functions for model hook feature. - 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. - onDuplicate interface{} // onDuplicate is used for ON "DUPLICATE KEY UPDATE" statement. - onDuplicateEx interface{} // onDuplicateEx is used for excluding some columns ON "DUPLICATE KEY UPDATE" statement. + db DB // Underlying DB interface. + tx TX // Underlying TX interface. + rawSql string // rawSql is the raw SQL string which marks a raw SQL based Model not a table based Model. + schema string // Custom database schema. + linkType int // Mark for operation on master or slave. + tablesInit string // Table names when model initialization. + tables string // Operation table names, which can be more than one table names and aliases, like: "user", "user u", "user u, user_detail ud". + fields string // Operation fields, multiple fields joined using char ','. + fieldsEx string // Excluded operation fields, multiple fields joined using char ','. + withArray []interface{} // Arguments for With feature. + withAll bool // Enable model association operations on all objects that have "with" tag in the struct. + extraArgs []interface{} // Extra custom arguments for sql, which are prepended to the arguments before sql committed to underlying driver. + whereBuilder *WhereBuilder // Condition builder for where operation. + groupBy string // Used for "group by" statement. + orderBy string // Used for "order by" statement. + having []interface{} // Used for "having..." statement. + start int // Used for "select ... start, limit ..." statement. + limit int // Used for "select ... start, limit ..." statement. + option int // Option for extra operation features. + offset int // Offset statement for some databases grammar. + partition string // Partition table partition name. + data interface{} // Data for operation, which can be type of map/[]map/struct/*struct/string, etc. + batch int // Batch number for batch Insert/Replace/Save operations. + 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, which is mainly for indicating cache duration(especially 0) usage. + cacheOption CacheOption // Cache option for query statement. + hookHandler HookHandler // Hook functions for model hook feature. + 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. + onDuplicate interface{} // onDuplicate is used for ON "DUPLICATE KEY UPDATE" statement. + onDuplicateEx interface{} // onDuplicateEx is used for excluding some columns ON "DUPLICATE KEY UPDATE" statement. + tableAliasMap map[string]string // Table alias to true table name, usually used in join statements. } // ModelHandler is a function that handles given Model and returns a new Model that is custom modified. @@ -125,15 +126,16 @@ func (c *Core) Model(tableNameQueryOrStruct ...interface{}) *Model { } } m := &Model{ - db: c.db, - schema: c.schema, - tablesInit: tableStr, - tables: tableStr, - fields: defaultFields, - start: -1, - offset: -1, - filter: true, - extraArgs: extraArgs, + db: c.db, + schema: c.schema, + tablesInit: tableStr, + tables: tableStr, + fields: defaultFields, + start: -1, + offset: -1, + filter: true, + extraArgs: extraArgs, + tableAliasMap: make(map[string]string), } m.whereBuilder = m.Builder() if defaultModelSafe { diff --git a/database/gdb/gdb_model_fields.go b/database/gdb/gdb_model_fields.go index a9a54711c67..c9e29a3f89d 100644 --- a/database/gdb/gdb_model_fields.go +++ b/database/gdb/gdb_model_fields.go @@ -27,7 +27,7 @@ func (m *Model) Fields(fieldNamesOrMapStruct ...interface{}) *Model { if length == 0 { return m } - fields := m.getFieldsFrom(fieldNamesOrMapStruct...) + fields := m.getFieldsFrom(m.tablesInit, fieldNamesOrMapStruct...) if len(fields) == 0 { return m } @@ -35,12 +35,12 @@ func (m *Model) Fields(fieldNamesOrMapStruct ...interface{}) *Model { } // FieldsPrefix performs as function Fields but add extra prefix for each field. -func (m *Model) FieldsPrefix(prefix string, fieldNamesOrMapStruct ...interface{}) *Model { - fields := m.getFieldsFrom(fieldNamesOrMapStruct...) +func (m *Model) FieldsPrefix(prefixOrAlias string, fieldNamesOrMapStruct ...interface{}) *Model { + fields := m.getFieldsFrom(m.getTableNameByPrefixOrAlias(prefixOrAlias), fieldNamesOrMapStruct...) if len(fields) == 0 { return m } - gstr.PrefixArray(fields, prefix+".") + gstr.PrefixArray(fields, prefixOrAlias+".") return m.appendFieldsByStr(gstr.Join(fields, ",")) } @@ -51,11 +51,14 @@ func (m *Model) FieldsPrefix(prefix string, fieldNamesOrMapStruct ...interface{} // // Also see Fields. func (m *Model) FieldsEx(fieldNamesOrMapStruct ...interface{}) *Model { + return m.doFieldsEx(m.tablesInit, fieldNamesOrMapStruct...) +} +func (m *Model) doFieldsEx(table string, fieldNamesOrMapStruct ...interface{}) *Model { length := len(fieldNamesOrMapStruct) if length == 0 { return m } - fields := m.getFieldsFrom(fieldNamesOrMapStruct...) + fields := m.getFieldsFrom(table, fieldNamesOrMapStruct...) if len(fields) == 0 { return m } @@ -63,10 +66,10 @@ func (m *Model) FieldsEx(fieldNamesOrMapStruct ...interface{}) *Model { } // FieldsExPrefix performs as function FieldsEx but add extra prefix for each field. -func (m *Model) FieldsExPrefix(prefix string, fieldNamesOrMapStruct ...interface{}) *Model { - model := m.FieldsEx(fieldNamesOrMapStruct...) +func (m *Model) FieldsExPrefix(prefixOrAlias string, fieldNamesOrMapStruct ...interface{}) *Model { + model := m.doFieldsEx(m.getTableNameByPrefixOrAlias(prefixOrAlias), fieldNamesOrMapStruct...) array := gstr.SplitAndTrim(model.fieldsEx, ",") - gstr.PrefixArray(array, prefix+".") + gstr.PrefixArray(array, prefixOrAlias+".") model.fieldsEx = gstr.Join(array, ",") return model } @@ -185,7 +188,8 @@ func (m *Model) HasField(field string) (bool, error) { return m.db.GetCore().HasField(m.GetCtx(), m.tablesInit, field) } -func (m *Model) getFieldsFrom(fieldNamesOrMapStruct ...interface{}) []string { +// getFieldsFrom retrieves, filters and returns fields name from table `table`. +func (m *Model) getFieldsFrom(table string, fieldNamesOrMapStruct ...interface{}) []string { length := len(fieldNamesOrMapStruct) if length == 0 { return nil @@ -193,23 +197,25 @@ func (m *Model) getFieldsFrom(fieldNamesOrMapStruct ...interface{}) []string { switch { // String slice. case length >= 2: - return m.mappingAndFilterToTableFields(gconv.Strings(fieldNamesOrMapStruct), true) + return m.mappingAndFilterToTableFields( + table, gconv.Strings(fieldNamesOrMapStruct), true, + ) // It needs type asserting. case length == 1: structOrMap := fieldNamesOrMapStruct[0] switch r := structOrMap.(type) { case string: - return m.mappingAndFilterToTableFields([]string{r}, false) + return m.mappingAndFilterToTableFields(table, []string{r}, false) case []string: - return m.mappingAndFilterToTableFields(r, true) + return m.mappingAndFilterToTableFields(table, r, true) case Raw, *Raw: return []string{gconv.String(structOrMap)} default: - return m.mappingAndFilterToTableFields(getFieldsFromStructOrMap(structOrMap), true) + return m.mappingAndFilterToTableFields(table, getFieldsFromStructOrMap(structOrMap), true) } default: diff --git a/database/gdb/gdb_model_join.go b/database/gdb/gdb_model_join.go index eacb0d5a8b2..2ebc2436ddd 100644 --- a/database/gdb/gdb_model_join.go +++ b/database/gdb/gdb_model_join.go @@ -159,6 +159,8 @@ func (m *Model) doJoin(operator joinOperator, tableOrSubQueryAndJoinConditions . var ( model = m.getModel() joinStr = "" + table string + alias string ) // Check the first parameter table or sub-query. if len(tableOrSubQueryAndJoinConditions) > 0 { @@ -168,24 +170,29 @@ func (m *Model) doJoin(operator joinOperator, tableOrSubQueryAndJoinConditions . joinStr = "(" + joinStr + ")" } } else { - joinStr = m.db.GetCore().QuotePrefixTableName(tableOrSubQueryAndJoinConditions[0]) + table = tableOrSubQueryAndJoinConditions[0] + joinStr = m.db.GetCore().QuotePrefixTableName(table) } } // Generate join condition statement string. conditionLength := len(tableOrSubQueryAndJoinConditions) switch { case conditionLength > 2: + alias = tableOrSubQueryAndJoinConditions[1] model.tables += fmt.Sprintf( " %s JOIN %s AS %s ON (%s)", operator, joinStr, - m.db.GetCore().QuoteWord(tableOrSubQueryAndJoinConditions[1]), + m.db.GetCore().QuoteWord(alias), tableOrSubQueryAndJoinConditions[2], ) + m.tableAliasMap[alias] = table + case conditionLength == 2: model.tables += fmt.Sprintf( " %s JOIN %s ON (%s)", operator, joinStr, tableOrSubQueryAndJoinConditions[1], ) + case conditionLength == 1: model.tables += fmt.Sprintf( " %s JOIN %s", operator, joinStr, @@ -194,6 +201,16 @@ func (m *Model) doJoin(operator joinOperator, tableOrSubQueryAndJoinConditions . return model } +// getTableNameByPrefixOrAlias checks and returns the table name if `prefixOrAlias` is an alias of a table, +// it or else returns the `prefixOrAlias` directly. +func (m *Model) getTableNameByPrefixOrAlias(prefixOrAlias string) string { + value, ok := m.tableAliasMap[prefixOrAlias] + if ok { + return value + } + return prefixOrAlias +} + // isSubQuery checks and returns whether given string a sub-query sql string. func isSubQuery(s string) bool { s = gstr.TrimLeft(s, "()") diff --git a/database/gdb/gdb_model_utility.go b/database/gdb/gdb_model_utility.go index fbf51f7c982..0873af25f2c 100644 --- a/database/gdb/gdb_model_utility.go +++ b/database/gdb/gdb_model_utility.go @@ -52,8 +52,19 @@ func (m *Model) getModel() *Model { // Eg: // ID -> id // NICK_Name -> nickname. -func (m *Model) mappingAndFilterToTableFields(fields []string, filter bool) []string { - fieldsMap, _ := m.TableFields(m.tablesInit) +func (m *Model) mappingAndFilterToTableFields(table string, fields []string, filter bool) []string { + var fieldsTable = table + if fieldsTable != "" { + hasTable, _ := m.db.GetCore().HasTable(fieldsTable) + if !hasTable { + fieldsTable = m.tablesInit + } + } + if fieldsTable == "" { + fieldsTable = m.tablesInit + } + + fieldsMap, _ := m.TableFields(fieldsTable) if len(fieldsMap) == 0 { return fields } From b1754f8254b90e23de5f6995c9507e22b9e481e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B5=B7=E4=BA=AE?= <739476267@qq.com> Date: Wed, 22 Nov 2023 20:49:07 +0800 Subject: [PATCH 16/52] script updates for version upgrading (#3169) --- .set_version.sh | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.set_version.sh b/.set_version.sh index 27f4f426065..5789cab7f6b 100755 --- a/.set_version.sh +++ b/.set_version.sh @@ -1,5 +1,4 @@ #!/usr/bin/env bash - if [ $# -ne 2 ]; then echo "Parameter exception, please execute in the format of $0 [directory] [version number]" echo "PS:$0 ./ v2.4.0" @@ -20,6 +19,13 @@ workdir=. newVersion=$2 echo "Prepare to replace the GF library version numbers in all go.mod files in the ${workdir} directory with ${newVersion}" +# check find command support or not +output=$(find "${workdir}" -name go.mod 2>&1) +if [[ $? -ne 0 ]]; then + echo "Error: please use bash or zsh to run!" + exit 1 +fi + if [[ true ]]; then echo "package gf" > version.go echo "" >> version.go From ea5d52cb2f0b8484ed2c3a84f1621ccf374c8477 Mon Sep 17 00:00:00 2001 From: John Guo Date: Wed, 22 Nov 2023 21:05:39 +0800 Subject: [PATCH 17/52] fix issue #3147 (#3161) --- cmd/gf/internal/cmd/cmd.go | 2 + os/gcmd/gcmd.go | 2 + os/gcmd/gcmd_command.go | 11 +- os/gcmd/gcmd_command_object.go | 18 ++- os/gcmd/gcmd_command_run.go | 8 +- os/gcmd/gcmd_z_unit_feature_object1_test.go | 25 ++- util/gconv/gconv_maptomaps.go | 6 +- util/gconv/gconv_scan.go | 10 +- util/gconv/gconv_struct.go | 165 ++++++++++++-------- util/gconv/gconv_structs.go | 12 +- util/gconv/gconv_z_unit_scan_test.go | 27 ++++ 11 files changed, 188 insertions(+), 98 deletions(-) diff --git a/cmd/gf/internal/cmd/cmd.go b/cmd/gf/internal/cmd/cmd.go index 7d20aedda3d..bd5e8922e07 100644 --- a/cmd/gf/internal/cmd/cmd.go +++ b/cmd/gf/internal/cmd/cmd.go @@ -55,6 +55,7 @@ func (c cGF) Index(ctx context.Context, in cGFInput) (out *cGFOutput, err error) _, err = Version.Index(ctx, cVersionInput{}) return } + answer := "n" // No argument or option, do installation checks. if data, isInstalled := service.Install.IsInstalled(); !isInstalled { @@ -71,6 +72,7 @@ func (c cGF) Index(ctx context.Context, in cGFInput) (out *cGFOutput, err error) gcmd.Scan("press `Enter` to exit...") return } + // Print help content. gcmd.CommandFromCtx(ctx).Print() return diff --git a/os/gcmd/gcmd.go b/os/gcmd/gcmd.go index 139b60c828e..41b7eff03a2 100644 --- a/os/gcmd/gcmd.go +++ b/os/gcmd/gcmd.go @@ -28,6 +28,8 @@ const ( helpOptionNameShort = "h" maxLineChars = 120 tracingInstrumentName = "github.com/gogf/gf/v2/os/gcmd.Command" + tagNameName = "name" + tagNameShort = "short" ) // Init does custom initialization. diff --git a/os/gcmd/gcmd_command.go b/os/gcmd/gcmd_command.go index d3cfc2b78a9..557a7531c82 100644 --- a/os/gcmd/gcmd_command.go +++ b/os/gcmd/gcmd_command.go @@ -42,12 +42,11 @@ type FuncWithValue func(ctx context.Context, parser *Parser) (out interface{}, e // Argument is the command value that are used by certain command. type Argument struct { - Name string // Option name. - FieldName string // Option field name. - Short string // Option short. - Brief string // Brief info about this Option, which is used in help info. - IsArg bool // IsArg marks this argument taking value from command line argument instead of option. - Orphan bool // Whether this Option having or having no value bound to it. + Name string // Option name. + Short string // Option short. + Brief string // Brief info about this Option, which is used in help info. + IsArg bool // IsArg marks this argument taking value from command line argument instead of option. + Orphan bool // Whether this Option having or having no value bound to it. } var ( diff --git a/os/gcmd/gcmd_command_object.go b/os/gcmd/gcmd_command_object.go index ab9d3d7cb0c..68c8610ad11 100644 --- a/os/gcmd/gcmd_command_object.go +++ b/os/gcmd/gcmd_command_object.go @@ -353,9 +353,6 @@ func newArgumentsFromInput(object interface{}) (args []Argument, err error) { } if arg.Name == "" { arg.Name = field.Name() - } else if arg.Name != field.Name() { - arg.FieldName = field.Name() - nameSet.Add(arg.FieldName) } if arg.Name == helpOptionName { return nil, gerror.Newf( @@ -411,14 +408,25 @@ func mergeDefaultStructValue(data map[string]interface{}, pointer interface{}) e foundValue interface{} ) for _, field := range tagFields { + var ( + nameValue = field.Tag(tagNameName) + shortValue = field.Tag(tagNameShort) + ) + // If it already has value, it then ignores the default value. + if value, ok := data[nameValue]; ok { + data[field.Name()] = value + continue + } + if value, ok := data[shortValue]; ok { + data[field.Name()] = value + continue + } foundKey, foundValue = gutil.MapPossibleItemByKey(data, field.Name()) if foundKey == "" { data[field.Name()] = field.TagValue } else { if utils.IsEmpty(foundValue) { data[foundKey] = field.TagValue - } else { - data[field.Name()] = foundValue } } } diff --git a/os/gcmd/gcmd_command_run.go b/os/gcmd/gcmd_command_run.go index 7aa61f95df4..c3f6fd53cb6 100644 --- a/os/gcmd/gcmd_command_run.go +++ b/os/gcmd/gcmd_command_run.go @@ -171,12 +171,10 @@ func (c *Command) reParse(ctx context.Context, parser *Parser) (*Parser, error) if arg.IsArg { continue } - optionKey = arg.Name - if arg.FieldName != "" { - optionKey += fmt.Sprintf(`,%s`, arg.FieldName) - } if arg.Short != "" { - optionKey += fmt.Sprintf(`,%s`, arg.Short) + optionKey = fmt.Sprintf(`%s,%s`, arg.Name, arg.Short) + } else { + optionKey = arg.Name } supportedOptions[optionKey] = !arg.Orphan } diff --git a/os/gcmd/gcmd_z_unit_feature_object1_test.go b/os/gcmd/gcmd_z_unit_feature_object1_test.go index a2845b327d5..c804e7c68cc 100644 --- a/os/gcmd/gcmd_z_unit_feature_object1_test.go +++ b/os/gcmd/gcmd_z_unit_feature_object1_test.go @@ -30,12 +30,14 @@ type TestCmdObjectEnvInput struct { type TestCmdObjectEnvOutput struct{} type TestCmdObjectTestInput struct { - g.Meta `name:"test" usage:"root test" brief:"root test command" dc:"root test command description" ad:"root test command ad"` - Name string `name:"yourname" v:"required" short:"n" orphan:"false" brief:"name for test command" d:"tom"` + g.Meta `name:"test" usage:"root test" brief:"root test command" dc:"root test command description" ad:"root test command ad"` + Name string `name:"yourname" v:"required" short:"n" orphan:"false" brief:"name for test command" d:"tom"` + Version bool `name:"version" short:"v" orphan:"true" brief:"show version"` } type TestCmdObjectTestOutput struct { - Content string + Name string + Version bool } func (TestCmdObject) Env(ctx context.Context, in TestCmdObjectEnvInput) (out *TestCmdObjectEnvOutput, err error) { @@ -44,7 +46,8 @@ func (TestCmdObject) Env(ctx context.Context, in TestCmdObjectEnvInput) (out *Te func (TestCmdObject) Test(ctx context.Context, in TestCmdObjectTestInput) (out *TestCmdObjectTestOutput, err error) { out = &TestCmdObjectTestOutput{ - Content: in.Name, + Name: in.Name, + Version: in.Version, } return } @@ -93,19 +96,25 @@ func Test_Command_NewFromObject_RunWithValue(t *testing.T) { os.Args = []string{"root", "test", "-n=john"} value, err := cmd.RunWithValueError(ctx) t.AssertNil(err) - t.Assert(value, `{"Content":"john"}`) + t.Assert(value, `{"Name":"john","Version":false}`) // test name tag name os.Args = []string{"root", "test", "-yourname=hailaz"} value1, err1 := cmd.RunWithValueError(ctx) t.AssertNil(err1) - t.Assert(value1, `{"Content":"hailaz"}`) + t.Assert(value1, `{"Name":"hailaz","Version":false}`) // test default tag value os.Args = []string{"root", "test"} value2, err2 := cmd.RunWithValueError(ctx) t.AssertNil(err2) - t.Assert(value2, `{"Content":"tom"}`) + t.Assert(value2, `{"Name":"tom","Version":false}`) + + // test name tag and orphan tag true + os.Args = []string{"root", "test", "-v"} + value3, err3 := cmd.RunWithValueError(ctx) + t.AssertNil(err3) + t.Assert(value3, `{"Name":"tom","Version":true}`) }) } @@ -123,7 +132,7 @@ func Test_Command_AddObject(t *testing.T) { os.Args = []string{"start", "root", "test", "-n=john"} value, err := command.RunWithValueError(ctx) t.AssertNil(err) - t.Assert(value, `{"Content":"john"}`) + t.Assert(value, `{"Name":"john","Version":false}`) }) } diff --git a/util/gconv/gconv_maptomaps.go b/util/gconv/gconv_maptomaps.go index 4a474ef8c61..63d19759d57 100644 --- a/util/gconv/gconv_maptomaps.go +++ b/util/gconv/gconv_maptomaps.go @@ -28,7 +28,7 @@ func MapToMaps(params interface{}, pointer interface{}, mapping ...map[string]st // // The optional parameter `mapping` is used for struct attribute to map key mapping, which makes // sense only if the item of `params` is type struct. -func doMapToMaps(params interface{}, pointer interface{}, mapping ...map[string]string) (err error) { +func doMapToMaps(params interface{}, pointer interface{}, paramKeyToAttrMap ...map[string]string) (err error) { // If given `params` is JSON, it then uses json.Unmarshal doing the converting. switch r := params.(type) { case []byte: @@ -124,13 +124,13 @@ func doMapToMaps(params interface{}, pointer interface{}, mapping ...map[string] var item reflect.Value if pointerElemType.Kind() == reflect.Ptr { item = reflect.New(pointerElemType.Elem()) - if err = MapToMap(paramsRv.Index(i).Interface(), item, mapping...); err != nil { + if err = MapToMap(paramsRv.Index(i).Interface(), item, paramKeyToAttrMap...); err != nil { return err } pointerSlice.Index(i).Set(item) } else { item = reflect.New(pointerElemType) - if err = MapToMap(paramsRv.Index(i).Interface(), item, mapping...); err != nil { + if err = MapToMap(paramsRv.Index(i).Interface(), item, paramKeyToAttrMap...); err != nil { return err } pointerSlice.Index(i).Set(item.Elem()) diff --git a/util/gconv/gconv_scan.go b/util/gconv/gconv_scan.go index 6187d079de2..4f286ad8963 100644 --- a/util/gconv/gconv_scan.go +++ b/util/gconv/gconv_scan.go @@ -23,7 +23,7 @@ import ( // It calls function `doMapToMaps` internally if `pointer` is type of *[]map/*[]*map for converting. // It calls function `doStruct` internally if `pointer` is type of *struct/**struct for converting. // It calls function `doStructs` internally if `pointer` is type of *[]struct/*[]*struct for converting. -func Scan(params interface{}, pointer interface{}, mapping ...map[string]string) (err error) { +func Scan(params interface{}, pointer interface{}, paramKeyToAttrMap ...map[string]string) (err error) { var ( pointerType reflect.Type pointerKind reflect.Kind @@ -82,12 +82,12 @@ func Scan(params interface{}, pointer interface{}, mapping ...map[string]string) pointerElemKind = pointerElem.Kind() keyToAttributeNameMapping map[string]string ) - if len(mapping) > 0 { - keyToAttributeNameMapping = mapping[0] + if len(paramKeyToAttrMap) > 0 { + keyToAttributeNameMapping = paramKeyToAttrMap[0] } switch pointerElemKind { case reflect.Map: - return doMapToMap(params, pointer, mapping...) + return doMapToMap(params, pointer, paramKeyToAttrMap...) case reflect.Array, reflect.Slice: var ( @@ -99,7 +99,7 @@ func Scan(params interface{}, pointer interface{}, mapping ...map[string]string) sliceElemKind = sliceElem.Kind() } if sliceElemKind == reflect.Map { - return doMapToMaps(params, pointer, mapping...) + return doMapToMaps(params, pointer, paramKeyToAttrMap...) } return doStructs(params, pointer, keyToAttributeNameMapping, "") diff --git a/util/gconv/gconv_struct.go b/util/gconv/gconv_struct.go index b3554ba5506..44b26851594 100644 --- a/util/gconv/gconv_struct.go +++ b/util/gconv/gconv_struct.go @@ -31,8 +31,8 @@ import ( // It will automatically convert the first letter of the key to uppercase // in mapping procedure to do the matching. // It ignores the map key, if it does not match. -func Struct(params interface{}, pointer interface{}, mapping ...map[string]string) (err error) { - return Scan(params, pointer, mapping...) +func Struct(params interface{}, pointer interface{}, paramKeyToAttrMap ...map[string]string) (err error) { + return Scan(params, pointer, paramKeyToAttrMap...) } // StructTag acts as Struct but also with support for priority tag feature, which retrieves the @@ -85,7 +85,7 @@ func doStructWithJsonCheck(params interface{}, pointer interface{}) (err error, } // doStruct is the core internal converting function for any data to struct. -func doStruct(params interface{}, pointer interface{}, mapping map[string]string, priorityTag string) (err error) { +func doStruct(params interface{}, pointer interface{}, paramKeyToAttrMap map[string]string, priorityTag string) (err error) { if params == nil { // If `params` is nil, no conversion. return nil @@ -252,7 +252,7 @@ func doStruct(params interface{}, pointer interface{}, mapping map[string]string continue } } - if err = doStruct(paramsMap, elemFieldValue, mapping, priorityTag); err != nil { + if err = doStruct(paramsMap, elemFieldValue, paramKeyToAttrMap, priorityTag); err != nil { return err } } else { @@ -264,7 +264,7 @@ func doStruct(params interface{}, pointer interface{}, mapping map[string]string return nil } - // The key of the tagMap is the attribute name of the struct, + // The key of the `attrToTagCheckNameMap` is the attribute name of the struct, // and the value is its replaced tag name for later comparison to improve performance. var ( attrToTagCheckNameMap = make(map[string]string) @@ -292,11 +292,27 @@ func doStruct(params interface{}, pointer interface{}, mapping map[string]string paramsMap[attributeName] = paramsMap[tagName] } } + + // To convert value base on custom parameter key to attribute name map. + err = doStructBaseOnParamKeyToAttrMap( + pointerElemReflectValue, + paramsMap, + paramKeyToAttrMap, + doneMap, + ) + if err != nil { + return err + } + // Already done all attributes value assignment nothing to do next. + if len(doneMap) == len(attrToCheckNameMap) { + return nil + } + // To convert value base on precise attribute name. err = doStructBaseOnAttribute( pointerElemReflectValue, paramsMap, - mapping, + paramKeyToAttrMap, doneMap, attrToCheckNameMap, ) @@ -307,11 +323,12 @@ func doStruct(params interface{}, pointer interface{}, mapping map[string]string if len(doneMap) == len(attrToCheckNameMap) { return nil } + // To convert value base on parameter map. err = doStructBaseOnParamMap( pointerElemReflectValue, paramsMap, - mapping, + paramKeyToAttrMap, doneMap, attrToCheckNameMap, attrToTagCheckNameMap, @@ -323,17 +340,47 @@ func doStruct(params interface{}, pointer interface{}, mapping map[string]string return nil } +func doStructBaseOnParamKeyToAttrMap( + pointerElemReflectValue reflect.Value, + paramsMap map[string]interface{}, + paramKeyToAttrMap map[string]string, + doneAttrMap map[string]struct{}, +) error { + if len(paramKeyToAttrMap) == 0 { + return nil + } + for paramKey, attrName := range paramKeyToAttrMap { + paramValue, ok := paramsMap[paramKey] + if !ok { + continue + } + // If the attribute name is already checked converting, then skip it. + if _, ok = doneAttrMap[attrName]; ok { + continue + } + // Mark it done. + doneAttrMap[attrName] = struct{}{} + if err := bindVarToStructAttr( + pointerElemReflectValue, attrName, paramValue, paramKeyToAttrMap, + ); err != nil { + return err + } + } + return nil +} + func doStructBaseOnAttribute( pointerElemReflectValue reflect.Value, paramsMap map[string]interface{}, - mapping map[string]string, - doneMap map[string]struct{}, + paramKeyToAttrMap map[string]string, + doneAttrMap map[string]struct{}, attrToCheckNameMap map[string]string, ) error { var customMappingAttrMap = make(map[string]struct{}) - if len(mapping) > 0 { + if len(paramKeyToAttrMap) > 0 { + // It ignores the attribute names if it is specified in the `paramKeyToAttrMap`. for paramName := range paramsMap { - if passedAttrKey, ok := mapping[paramName]; ok { + if passedAttrKey, ok := paramKeyToAttrMap[paramName]; ok { customMappingAttrMap[passedAttrKey] = struct{}{} } } @@ -344,17 +391,19 @@ func doStructBaseOnAttribute( if !ok { continue } - // If the attribute name is in custom mapping, it then ignores this converting. + // If the attribute name is in custom paramKeyToAttrMap, it then ignores this converting. if _, ok = customMappingAttrMap[attrName]; ok { continue } // If the attribute name is already checked converting, then skip it. - if _, ok = doneMap[attrName]; ok { + if _, ok = doneAttrMap[attrName]; ok { continue } // Mark it done. - doneMap[attrName] = struct{}{} - if err := bindVarToStructAttr(pointerElemReflectValue, attrName, paramValue, mapping); err != nil { + doneAttrMap[attrName] = struct{}{} + if err := bindVarToStructAttr( + pointerElemReflectValue, attrName, paramValue, paramKeyToAttrMap, + ); err != nil { return err } } @@ -364,8 +413,8 @@ func doStructBaseOnAttribute( func doStructBaseOnParamMap( pointerElemReflectValue reflect.Value, paramsMap map[string]interface{}, - mapping map[string]string, - doneMap map[string]struct{}, + paramKeyToAttrMap map[string]string, + doneAttrMap map[string]struct{}, attrToCheckNameMap map[string]string, attrToTagCheckNameMap map[string]string, tagToAttrNameMap map[string]string, @@ -375,45 +424,35 @@ func doStructBaseOnParamMap( checkName string ) for paramName, paramValue := range paramsMap { - attrName = "" - // It firstly checks the passed mapping rules. - if len(mapping) > 0 { - if passedAttrKey, ok := mapping[paramName]; ok { - attrName = passedAttrKey - } - } - // It secondly checks the predefined tags and matching rules. + // It firstly considers `paramName` as accurate tag name, + // and retrieve attribute name from `tagToAttrNameMap` . + attrName = tagToAttrNameMap[paramName] if attrName == "" { - // It firstly considers `paramName` as accurate tag name, - // and retrieve attribute name from `tagToAttrNameMap` . - attrName = tagToAttrNameMap[paramName] - if attrName == "" { - checkName = utils.RemoveSymbols(paramName) - // Loop to find the matched attribute name with or without - // string cases and chars like '-'/'_'/'.'/' '. - - // Matching the parameters to struct tag names. - // The `attrKey` is the attribute name of the struct. - for attrKey, cmpKey := range attrToTagCheckNameMap { - if strings.EqualFold(checkName, cmpKey) { - attrName = attrKey - break - } + checkName = utils.RemoveSymbols(paramName) + // Loop to find the matched attribute name with or without + // string cases and chars like '-'/'_'/'.'/' '. + + // Matching the parameters to struct tag names. + // The `attrKey` is the attribute name of the struct. + for attrKey, cmpKey := range attrToTagCheckNameMap { + if strings.EqualFold(checkName, cmpKey) { + attrName = attrKey + break } } + } - // Matching the parameters to struct attributes. - if attrName == "" { - for attrKey, cmpKey := range attrToCheckNameMap { - // Eg: - // UserName eq user_name - // User-Name eq username - // username eq userName - // etc. - if strings.EqualFold(checkName, cmpKey) { - attrName = attrKey - break - } + // Matching the parameters to struct attributes. + if attrName == "" { + for attrKey, cmpKey := range attrToCheckNameMap { + // Eg: + // UserName eq user_name + // User-Name eq username + // username eq userName + // etc. + if strings.EqualFold(checkName, cmpKey) { + attrName = attrKey + break } } } @@ -423,12 +462,14 @@ func doStructBaseOnParamMap( continue } // If the attribute name is already checked converting, then skip it. - if _, ok := doneMap[attrName]; ok { + if _, ok := doneAttrMap[attrName]; ok { continue } // Mark it done. - doneMap[attrName] = struct{}{} - if err := bindVarToStructAttr(pointerElemReflectValue, attrName, paramValue, mapping); err != nil { + doneAttrMap[attrName] = struct{}{} + if err := bindVarToStructAttr( + pointerElemReflectValue, attrName, paramValue, paramKeyToAttrMap, + ); err != nil { return err } } @@ -438,7 +479,7 @@ func doStructBaseOnParamMap( // bindVarToStructAttr sets value to struct object attribute by name. func bindVarToStructAttr( structReflectValue reflect.Value, - attrName string, value interface{}, mapping map[string]string, + attrName string, value interface{}, paramKeyToAttrMap map[string]string, ) (err error) { structFieldValue := structReflectValue.FieldByName(attrName) if !structFieldValue.IsValid() { @@ -450,7 +491,7 @@ func bindVarToStructAttr( } defer func() { if exception := recover(); exception != nil { - if err = bindVarToReflectValue(structFieldValue, value, mapping); err != nil { + if err = bindVarToReflectValue(structFieldValue, value, paramKeyToAttrMap); err != nil { err = gerror.Wrapf(err, `error binding value to attribute "%s"`, attrName) } } @@ -575,7 +616,9 @@ func bindVarToReflectValueWithInterfaceCheck(reflectValue reflect.Value, value i } // bindVarToReflectValue sets `value` to reflect value object `structFieldValue`. -func bindVarToReflectValue(structFieldValue reflect.Value, value interface{}, mapping map[string]string) (err error) { +func bindVarToReflectValue( + structFieldValue reflect.Value, value interface{}, paramKeyToAttrMap map[string]string, +) (err error) { // JSON content converting. err, ok := doStructWithJsonCheck(value, structFieldValue) if err != nil { @@ -600,7 +643,7 @@ func bindVarToReflectValue(structFieldValue reflect.Value, value interface{}, ma // Converting using reflection by kind. switch kind { case reflect.Map: - return doMapToMap(value, structFieldValue, mapping) + return doMapToMap(value, structFieldValue, paramKeyToAttrMap) case reflect.Struct: // Recursively converting for struct attribute. @@ -716,12 +759,12 @@ func bindVarToReflectValue(structFieldValue reflect.Value, value interface{}, ma return err } elem := item.Elem() - if err = bindVarToReflectValue(elem, value, mapping); err == nil { + if err = bindVarToReflectValue(elem, value, paramKeyToAttrMap); err == nil { structFieldValue.Set(elem.Addr()) } } else { // Not empty pointer, it assigns values to it. - return bindVarToReflectValue(structFieldValue.Elem(), value, mapping) + return bindVarToReflectValue(structFieldValue.Elem(), value, paramKeyToAttrMap) } // It mainly and specially handles the interface of nil value. diff --git a/util/gconv/gconv_structs.go b/util/gconv/gconv_structs.go index b8c04ff663c..42ec26c3fd9 100644 --- a/util/gconv/gconv_structs.go +++ b/util/gconv/gconv_structs.go @@ -16,8 +16,8 @@ import ( // Structs converts any slice to given struct slice. // Also see Scan, Struct. -func Structs(params interface{}, pointer interface{}, mapping ...map[string]string) (err error) { - return Scan(params, pointer, mapping...) +func Structs(params interface{}, pointer interface{}, paramKeyToAttrMap ...map[string]string) (err error) { + return Scan(params, pointer, paramKeyToAttrMap...) } // StructsTag acts as Structs but also with support for priority tag feature, which retrieves the @@ -34,7 +34,9 @@ func StructsTag(params interface{}, pointer interface{}, priorityTag string) (er // The parameter `pointer` should be type of pointer to slice of struct. // Note that if `pointer` is a pointer to another pointer of type of slice of struct, // it will create the struct/pointer internally. -func doStructs(params interface{}, pointer interface{}, mapping map[string]string, priorityTag string) (err error) { +func doStructs( + params interface{}, pointer interface{}, paramKeyToAttrMap map[string]string, priorityTag string, +) (err error) { if params == nil { // If `params` is nil, no conversion. return nil @@ -133,7 +135,7 @@ func doStructs(params interface{}, pointer interface{}, mapping map[string]strin if !tempReflectValue.IsValid() { tempReflectValue = reflect.New(itemType.Elem()).Elem() } - if err = doStruct(paramsList[i], tempReflectValue, mapping, priorityTag); err != nil { + if err = doStruct(paramsList[i], tempReflectValue, paramKeyToAttrMap, priorityTag); err != nil { return err } reflectElemArray.Index(i).Set(tempReflectValue.Addr()) @@ -147,7 +149,7 @@ func doStructs(params interface{}, pointer interface{}, mapping map[string]strin } else { tempReflectValue = reflect.New(itemType).Elem() } - if err = doStruct(paramsList[i], tempReflectValue, mapping, priorityTag); err != nil { + if err = doStruct(paramsList[i], tempReflectValue, paramKeyToAttrMap, priorityTag); err != nil { return err } reflectElemArray.Index(i).Set(tempReflectValue) diff --git a/util/gconv/gconv_z_unit_scan_test.go b/util/gconv/gconv_z_unit_scan_test.go index f94bf3e1aa5..560d39461d6 100644 --- a/util/gconv/gconv_z_unit_scan_test.go +++ b/util/gconv/gconv_z_unit_scan_test.go @@ -17,6 +17,33 @@ import ( "github.com/gogf/gf/v2/util/gconv" ) +func Test_Scan_WithMapParameter(t *testing.T) { + type User struct { + Uid int + Name string + } + gtest.C(t, func(t *gtest.T) { + for i := 0; i < 100; i++ { + var ( + user = new(User) + params = g.Map{ + "uid": 1, + "myname": "john", + "name": "smith", + } + ) + err := gconv.Scan(params, user, g.MapStrStr{ + "myname": "Name", + }) + t.AssertNil(err) + t.Assert(user, &User{ + Uid: 1, + Name: "john", + }) + } + }) +} + func Test_Scan_StructStructs(t *testing.T) { type User struct { Uid int From 9aa872e7058999eec025883fe5939bccc9235b3c Mon Sep 17 00:00:00 2001 From: John Guo Date: Thu, 23 Nov 2023 18:59:04 +0800 Subject: [PATCH 18/52] improve map converting feature using `MapOption` for package `gconv` (#3170) --- container/gvar/gvar_map.go | 28 ++++++---- database/gdb/gdb_func.go | 4 +- util/gconv/gconv_map.go | 84 ++++++++++++++++++++--------- util/gconv/gconv_maps.go | 15 +++--- util/gconv/gconv_structs.go | 5 ++ util/gconv/gconv_z_unit_all_test.go | 4 +- util/gconv/gconv_z_unit_map_test.go | 49 ++++++++++++++++- 7 files changed, 139 insertions(+), 50 deletions(-) diff --git a/container/gvar/gvar_map.go b/container/gvar/gvar_map.go index 268d9f14042..f56874d171e 100644 --- a/container/gvar/gvar_map.go +++ b/container/gvar/gvar_map.go @@ -8,24 +8,27 @@ package gvar import "github.com/gogf/gf/v2/util/gconv" +// MapOption specifies the option for map converting. +type MapOption = gconv.MapOption + // Map converts and returns `v` as map[string]interface{}. -func (v *Var) Map(tags ...string) map[string]interface{} { - return gconv.Map(v.Val(), tags...) +func (v *Var) Map(option ...MapOption) map[string]interface{} { + return gconv.Map(v.Val(), option...) } // MapStrAny is like function Map, but implements the interface of MapStrAny. -func (v *Var) MapStrAny() map[string]interface{} { - return v.Map() +func (v *Var) MapStrAny(option ...MapOption) map[string]interface{} { + return v.Map(option...) } // MapStrStr converts and returns `v` as map[string]string. -func (v *Var) MapStrStr(tags ...string) map[string]string { - return gconv.MapStrStr(v.Val(), tags...) +func (v *Var) MapStrStr(option ...MapOption) map[string]string { + return gconv.MapStrStr(v.Val(), option...) } // MapStrVar converts and returns `v` as map[string]Var. -func (v *Var) MapStrVar(tags ...string) map[string]*Var { - m := v.Map(tags...) +func (v *Var) MapStrVar(option ...MapOption) map[string]*Var { + m := v.Map(option...) if len(m) > 0 { vMap := make(map[string]*Var, len(m)) for k, v := range m { @@ -37,16 +40,19 @@ func (v *Var) MapStrVar(tags ...string) map[string]*Var { } // MapDeep converts and returns `v` as map[string]interface{} recursively. +// Deprecated: used Map instead. func (v *Var) MapDeep(tags ...string) map[string]interface{} { return gconv.MapDeep(v.Val(), tags...) } // MapStrStrDeep converts and returns `v` as map[string]string recursively. +// Deprecated: used MapStrStr instead. func (v *Var) MapStrStrDeep(tags ...string) map[string]string { return gconv.MapStrStrDeep(v.Val(), tags...) } // MapStrVarDeep converts and returns `v` as map[string]*Var recursively. +// Deprecated: used MapStrVar instead. func (v *Var) MapStrVarDeep(tags ...string) map[string]*Var { m := v.MapDeep(tags...) if len(m) > 0 { @@ -61,12 +67,12 @@ func (v *Var) MapStrVarDeep(tags ...string) map[string]*Var { // Maps converts and returns `v` as map[string]string. // See gconv.Maps. -func (v *Var) Maps(tags ...string) []map[string]interface{} { - return gconv.Maps(v.Val(), tags...) +func (v *Var) Maps(option ...MapOption) []map[string]interface{} { + return gconv.Maps(v.Val(), option...) } // MapsDeep converts `value` to []map[string]interface{} recursively. -// See gconv.MapsDeep. +// Deprecated: used Maps instead. func (v *Var) MapsDeep(tags ...string) []map[string]interface{} { return gconv.MapsDeep(v.Val(), tags...) } diff --git a/database/gdb/gdb_func.go b/database/gdb/gdb_func.go index 28710a203c3..ec5850902a5 100644 --- a/database/gdb/gdb_func.go +++ b/database/gdb/gdb_func.go @@ -210,14 +210,14 @@ func GetInsertOperationByOption(option InsertOption) string { } func anyValueToMapBeforeToRecord(value interface{}) map[string]interface{} { - return gconv.Map(value, structTagPriority...) + return gconv.Map(value, gconv.MapOption{Tags: structTagPriority}) } // DataToMapDeep converts `value` to map type recursively(if attribute struct is embedded). // The parameter `value` should be type of *map/map/*struct/struct. // It supports embedded struct definition for struct. func DataToMapDeep(value interface{}) map[string]interface{} { - m := gconv.Map(value, structTagPriority...) + m := gconv.Map(value, gconv.MapOption{Tags: structTagPriority}) for k, v := range m { switch v.(type) { case time.Time, *time.Time, gtime.Time, *gtime.Time, gjson.Json, *gjson.Json: diff --git a/util/gconv/gconv_map.go b/util/gconv/gconv_map.go index f9a510eeca3..7627d684077 100644 --- a/util/gconv/gconv_map.go +++ b/util/gconv/gconv_map.go @@ -22,40 +22,57 @@ const ( recursiveTypeTrue recursiveType = "true" ) +// MapOption specifies the option for map converting. +type MapOption struct { + // Deep marks doing Map function recursively, which means if the attribute of given converting value + // is also a struct/*struct, it automatically calls Map function on this attribute converting it to + // a map[string]interface{} type variable. + Deep bool + + // OmitEmpty ignores the attributes that has json omitempty tag. + OmitEmpty bool + + // Tags specifies the converted map key name by struct tag name. + Tags []string +} + // Map converts any variable `value` to map[string]interface{}. If the parameter `value` is not a // map/struct/*struct type, then the conversion will fail and returns nil. // // If `value` is a struct/*struct object, the second parameter `tags` specifies the most priority // tags that will be detected, otherwise it detects the tags in order of: // gconv, json, field name. -func Map(value interface{}, tags ...string) map[string]interface{} { - return doMapConvert(value, recursiveTypeAuto, false, tags...) +func Map(value interface{}, option ...MapOption) map[string]interface{} { + return doMapConvert(value, recursiveTypeAuto, false, option...) } // MapDeep does Map function recursively, which means if the attribute of `value` // is also a struct/*struct, calls Map function on this attribute converting it to // a map[string]interface{} type variable. -// Also see Map. +// Deprecated: used Map instead. func MapDeep(value interface{}, tags ...string) map[string]interface{} { - return doMapConvert(value, recursiveTypeTrue, false, tags...) + return doMapConvert(value, recursiveTypeTrue, false, MapOption{ + Tags: tags, + }) } // doMapConvert implements the map converting. // It automatically checks and converts json string to map if `value` is string/[]byte. // // TODO completely implement the recursive converting for all types, especially the map. -func doMapConvert(value interface{}, recursive recursiveType, mustMapReturn bool, tags ...string) map[string]interface{} { +func doMapConvert(value interface{}, recursive recursiveType, mustMapReturn bool, option ...MapOption) map[string]interface{} { if value == nil { return nil } + var usedOption = getUsedMapOption(option...) newTags := StructTagPriority - switch len(tags) { + switch len(usedOption.Tags) { case 0: // No need handling. case 1: - newTags = append(strings.Split(tags[0], ","), StructTagPriority...) + newTags = append(strings.Split(usedOption.Tags[0], ","), StructTagPriority...) default: - newTags = append(tags, StructTagPriority...) + newTags = append(usedOption.Tags, StructTagPriority...) } // Assert the common combination of types, and finally it uses reflection. dataMap := make(map[string]interface{}) @@ -79,6 +96,8 @@ func doMapConvert(value interface{}, recursive recursiveType, mustMapReturn bool return nil } case map[interface{}]interface{}: + recursiveOption := usedOption + recursiveOption.Tags = newTags for k, v := range r { dataMap[String(k)] = doMapConvertForMapOrStructValue( doMapConvertForMapOrStructValueInput{ @@ -86,7 +105,7 @@ func doMapConvert(value interface{}, recursive recursiveType, mustMapReturn bool Value: v, RecursiveType: recursive, RecursiveOption: recursive == recursiveTypeTrue, - Tags: newTags, + Option: recursiveOption, }, ) } @@ -136,6 +155,8 @@ func doMapConvert(value interface{}, recursive recursiveType, mustMapReturn bool } case map[string]interface{}: if recursive == recursiveTypeTrue { + recursiveOption := usedOption + recursiveOption.Tags = newTags // A copy of current map. for k, v := range r { dataMap[k] = doMapConvertForMapOrStructValue( @@ -144,7 +165,7 @@ func doMapConvert(value interface{}, recursive recursiveType, mustMapReturn bool Value: v, RecursiveType: recursive, RecursiveOption: recursive == recursiveTypeTrue, - Tags: newTags, + Option: recursiveOption, }, ) } @@ -153,6 +174,8 @@ func doMapConvert(value interface{}, recursive recursiveType, mustMapReturn bool return r } case map[int]interface{}: + recursiveOption := usedOption + recursiveOption.Tags = newTags for k, v := range r { dataMap[String(k)] = doMapConvertForMapOrStructValue( doMapConvertForMapOrStructValueInput{ @@ -160,7 +183,7 @@ func doMapConvert(value interface{}, recursive recursiveType, mustMapReturn bool Value: v, RecursiveType: recursive, RecursiveOption: recursive == recursiveTypeTrue, - Tags: newTags, + Option: recursiveOption, }, ) } @@ -202,13 +225,15 @@ func doMapConvert(value interface{}, recursive recursiveType, mustMapReturn bool } } case reflect.Map, reflect.Struct, reflect.Interface: + recursiveOption := usedOption + recursiveOption.Tags = newTags convertedValue := doMapConvertForMapOrStructValue( doMapConvertForMapOrStructValueInput{ IsRoot: true, Value: value, RecursiveType: recursive, RecursiveOption: recursive == recursiveTypeTrue, - Tags: newTags, + Option: recursiveOption, MustMapReturn: mustMapReturn, }, ) @@ -223,12 +248,20 @@ func doMapConvert(value interface{}, recursive recursiveType, mustMapReturn bool return dataMap } +func getUsedMapOption(option ...MapOption) MapOption { + var usedOption MapOption + if len(option) > 0 { + usedOption = option[0] + } + return usedOption +} + type doMapConvertForMapOrStructValueInput struct { IsRoot bool // It returns directly if it is not root and with no recursive converting. Value interface{} // Current operation value. RecursiveType recursiveType // The type from top function entry. RecursiveOption bool // Whether convert recursively for `current` operation. - Tags []string // Map key mapping. + Option MapOption // Map converting option. MustMapReturn bool // Must return map instead of Value when empty. } @@ -280,7 +313,7 @@ func doMapConvertForMapOrStructValue(in doMapConvertForMapOrStructValueInput) in Value: mapValue, RecursiveType: in.RecursiveType, RecursiveOption: in.RecursiveType == recursiveTypeTrue, - Tags: in.Tags, + Option: in.Option, }, ) } @@ -299,7 +332,7 @@ func doMapConvertForMapOrStructValue(in doMapConvertForMapOrStructValueInput) in Value: mapV, RecursiveType: in.RecursiveType, RecursiveOption: in.RecursiveType == recursiveTypeTrue, - Tags: in.Tags, + Option: in.Option, }, ) } else { @@ -327,7 +360,7 @@ func doMapConvertForMapOrStructValue(in doMapConvertForMapOrStructValueInput) in } mapKey = "" fieldTag := rtField.Tag - for _, tag := range in.Tags { + for _, tag := range in.Option.Tags { if mapKey = fieldTag.Get(tag); mapKey != "" { break } @@ -344,7 +377,7 @@ func doMapConvertForMapOrStructValue(in doMapConvertForMapOrStructValueInput) in if len(array) > 1 { switch strings.TrimSpace(array[1]) { case "omitempty": - if empty.IsEmpty(rvField.Interface()) { + if in.Option.OmitEmpty && empty.IsEmpty(rvField.Interface()) { continue } else { mapKey = strings.TrimSpace(array[0]) @@ -389,7 +422,7 @@ func doMapConvertForMapOrStructValue(in doMapConvertForMapOrStructValueInput) in Value: rvInterface, RecursiveType: in.RecursiveType, RecursiveOption: true, - Tags: in.Tags, + Option: in.Option, }) if m, ok := anonymousValue.(map[string]interface{}); ok { for k, v := range m { @@ -406,7 +439,7 @@ func doMapConvertForMapOrStructValue(in doMapConvertForMapOrStructValueInput) in Value: rvInterface, RecursiveType: in.RecursiveType, RecursiveOption: true, - Tags: in.Tags, + Option: in.Option, }) default: @@ -415,7 +448,7 @@ func doMapConvertForMapOrStructValue(in doMapConvertForMapOrStructValueInput) in Value: rvInterface, RecursiveType: in.RecursiveType, RecursiveOption: in.RecursiveType == recursiveTypeTrue, - Tags: in.Tags, + Option: in.Option, }) } @@ -434,7 +467,7 @@ func doMapConvertForMapOrStructValue(in doMapConvertForMapOrStructValueInput) in Value: rvAttrField.Index(arrayIndex).Interface(), RecursiveType: in.RecursiveType, RecursiveOption: in.RecursiveType == recursiveTypeTrue, - Tags: in.Tags, + Option: in.Option, }, ) } @@ -451,7 +484,7 @@ func doMapConvertForMapOrStructValue(in doMapConvertForMapOrStructValueInput) in Value: rvAttrField.MapIndex(k).Interface(), RecursiveType: in.RecursiveType, RecursiveOption: in.RecursiveType == recursiveTypeTrue, - Tags: in.Tags, + Option: in.Option, }, ) } @@ -490,7 +523,7 @@ func doMapConvertForMapOrStructValue(in doMapConvertForMapOrStructValueInput) in Value: reflectValue.Index(i).Interface(), RecursiveType: in.RecursiveType, RecursiveOption: in.RecursiveType == recursiveTypeTrue, - Tags: in.Tags, + Option: in.Option, }) } return array @@ -500,11 +533,11 @@ func doMapConvertForMapOrStructValue(in doMapConvertForMapOrStructValueInput) in // MapStrStr converts `value` to map[string]string. // Note that there might be data copy for this map type converting. -func MapStrStr(value interface{}, tags ...string) map[string]string { +func MapStrStr(value interface{}, option ...MapOption) map[string]string { if r, ok := value.(map[string]string); ok { return r } - m := Map(value, tags...) + m := Map(value, option...) if len(m) > 0 { vMap := make(map[string]string, len(m)) for k, v := range m { @@ -517,6 +550,7 @@ func MapStrStr(value interface{}, tags ...string) map[string]string { // MapStrStrDeep converts `value` to map[string]string recursively. // Note that there might be data copy for this map type converting. +// Deprecated: used MapStrStr instead. func MapStrStrDeep(value interface{}, tags ...string) map[string]string { if r, ok := value.(map[string]string); ok { return r diff --git a/util/gconv/gconv_maps.go b/util/gconv/gconv_maps.go index 3efe2386f90..a68bb4e1046 100644 --- a/util/gconv/gconv_maps.go +++ b/util/gconv/gconv_maps.go @@ -9,23 +9,19 @@ package gconv import "github.com/gogf/gf/v2/internal/json" // SliceMap is alias of Maps. -func SliceMap(any interface{}) []map[string]interface{} { - return Maps(any) +func SliceMap(any interface{}, option ...MapOption) []map[string]interface{} { + return Maps(any, option...) } // SliceMapDeep is alias of MapsDeep. +// Deprecated: used SliceMap instead. func SliceMapDeep(any interface{}) []map[string]interface{} { return MapsDeep(any) } -// SliceStruct is alias of Structs. -func SliceStruct(params interface{}, pointer interface{}, mapping ...map[string]string) (err error) { - return Structs(params, pointer, mapping...) -} - // Maps converts `value` to []map[string]interface{}. // Note that it automatically checks and converts json string to []map if `value` is string/[]byte. -func Maps(value interface{}, tags ...string) []map[string]interface{} { +func Maps(value interface{}, option ...MapOption) []map[string]interface{} { if value == nil { return nil } @@ -62,7 +58,7 @@ func Maps(value interface{}, tags ...string) []map[string]interface{} { } list := make([]map[string]interface{}, len(array)) for k, v := range array { - list[k] = Map(v, tags...) + list[k] = Map(v, option...) } return list } @@ -71,6 +67,7 @@ func Maps(value interface{}, tags ...string) []map[string]interface{} { // MapsDeep converts `value` to []map[string]interface{} recursively. // // TODO completely implement the recursive converting for all types. +// Deprecated: used Maps instead. func MapsDeep(value interface{}, tags ...string) []map[string]interface{} { if value == nil { return nil diff --git a/util/gconv/gconv_structs.go b/util/gconv/gconv_structs.go index 42ec26c3fd9..f8e93656ce4 100644 --- a/util/gconv/gconv_structs.go +++ b/util/gconv/gconv_structs.go @@ -20,6 +20,11 @@ func Structs(params interface{}, pointer interface{}, paramKeyToAttrMap ...map[s return Scan(params, pointer, paramKeyToAttrMap...) } +// SliceStruct is alias of Structs. +func SliceStruct(params interface{}, pointer interface{}, mapping ...map[string]string) (err error) { + return Structs(params, pointer, mapping...) +} + // StructsTag acts as Structs but also with support for priority tag feature, which retrieves the // specified tags for `params` key-value items to struct attribute names mapping. // The parameter `priorityTag` supports multiple tags that can be joined with char ','. diff --git a/util/gconv/gconv_z_unit_all_test.go b/util/gconv/gconv_z_unit_all_test.go index d6bc83e0ff4..78d62c05476 100644 --- a/util/gconv/gconv_z_unit_all_test.go +++ b/util/gconv/gconv_z_unit_all_test.go @@ -946,8 +946,8 @@ func Test_Map_StructWithJsonTag_All(t *testing.T) { ssa: "222", } user2 := &user1 - _ = gconv.Map(user1, "Ss") - map1 := gconv.Map(user1, "json", "json2") + _ = gconv.Map(user1, gconv.MapOption{Tags: []string{"Ss"}}) + map1 := gconv.Map(user1, gconv.MapOption{Tags: []string{"json", "json2"}}) map2 := gconv.Map(user2) map3 := gconv.Map(user3) t.Assert(map1["Uid"], 100) diff --git a/util/gconv/gconv_z_unit_map_test.go b/util/gconv/gconv_z_unit_map_test.go index 9dca4ce39bd..b72a2eac4fb 100644 --- a/util/gconv/gconv_z_unit_map_test.go +++ b/util/gconv/gconv_z_unit_map_test.go @@ -617,6 +617,53 @@ func TestMapWithJsonOmitEmpty(t *testing.T) { Key: "", Value: 1, } - t.Assert(gconv.Map(s), g.Map{"Value": 1}) + m1 := gconv.Map(s) + t.Assert(m1, g.Map{ + "Key": "", + "Value": 1, + }) + + m2 := gconv.Map(s, gconv.MapOption{ + Deep: false, + OmitEmpty: true, + Tags: nil, + }) + t.Assert(m2, g.Map{ + "Value": 1, + }) + }) + + gtest.C(t, func(t *gtest.T) { + type ProductConfig struct { + Pid int `v:"required" json:"pid,omitempty"` + TimeSpan int `v:"required" json:"timeSpan,omitempty"` + } + type CreateGoodsDetail struct { + ProductConfig + AutoRenewFlag int `v:"required" json:"autoRenewFlag"` + } + s := &CreateGoodsDetail{ + ProductConfig: ProductConfig{ + Pid: 1, + TimeSpan: 0, + }, + AutoRenewFlag: 0, + } + m1 := gconv.Map(s) + t.Assert(m1, g.Map{ + "pid": 1, + "timeSpan": 0, + "autoRenewFlag": 0, + }) + + m2 := gconv.Map(s, gconv.MapOption{ + Deep: false, + OmitEmpty: true, + Tags: nil, + }) + t.Assert(m2, g.Map{ + "pid": 1, + "autoRenewFlag": 0, + }) }) } From c7c9f0011a33b75294ba4ae40f775bdb929da35d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B5=B7=E4=BA=AE?= <739476267@qq.com> Date: Wed, 29 Nov 2023 19:05:21 +0800 Subject: [PATCH 19/52] fix: #2967 (#3175) --- contrib/drivers/pgsql/pgsql.go | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/contrib/drivers/pgsql/pgsql.go b/contrib/drivers/pgsql/pgsql.go index fe84a440171..28a80651d30 100644 --- a/contrib/drivers/pgsql/pgsql.go +++ b/contrib/drivers/pgsql/pgsql.go @@ -15,6 +15,7 @@ import ( "context" "database/sql" "fmt" + "regexp" "strings" _ "github.com/lib/pq" @@ -237,6 +238,12 @@ func (d *Driver) Tables(ctx context.Context, schema ...string) (tables []string, if err != nil { return nil, err } + + useRelpartbound := "" + if gstr.CompareVersion(d.version(ctx, link), "10") >= 0 { + useRelpartbound = "AND c.relpartbound IS NULL" + } + var query = fmt.Sprintf(` SELECT c.relname @@ -247,10 +254,11 @@ INNER JOIN pg_namespace n ON WHERE n.nspname = '%s' AND c.relkind IN ('r', 'p') - AND c.relpartbound IS NULL + %s ORDER BY c.relname`, usedSchema, + useRelpartbound, ) query, _ = gregex.ReplaceString(`[\n\r\s]+`, " ", gstr.Trim(query)) @@ -266,6 +274,23 @@ ORDER BY return } +// version checks and returns the database version. +func (d *Driver) version(ctx context.Context, link gdb.Link) string { + result, err := d.DoSelect(ctx, link, "SELECT version();") + if err != nil { + return "" + } + if len(result) > 0 { + if v, ok := result[0]["version"]; ok { + matches := regexp.MustCompile(`PostgreSQL (\d+\.\d+)`).FindStringSubmatch(v.String()) + if len(matches) >= 2 { + return matches[1] + } + } + } + return "" +} + // TableFields retrieves and returns the fields' information of specified table of current schema. func (d *Driver) TableFields(ctx context.Context, table string, schema ...string) (fields map[string]*gdb.TableField, err error) { var ( From 993467bb3cb13d1cd3b276b5e571ea2fecdb86f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B5=B7=E4=BA=AE?= <739476267@qq.com> Date: Wed, 29 Nov 2023 19:12:21 +0800 Subject: [PATCH 20/52] test: add date-format test for RFC3339 (#3181) --- .../gvalid/gvalid_z_unit_feature_rule_test.go | 40 ++++++++++--------- 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/util/gvalid/gvalid_z_unit_feature_rule_test.go b/util/gvalid/gvalid_z_unit_feature_rule_test.go index 71b104453a1..a653dab824a 100755 --- a/util/gvalid/gvalid_z_unit_feature_rule_test.go +++ b/util/gvalid/gvalid_z_unit_feature_rule_test.go @@ -311,24 +311,28 @@ func Test_Datetime(t *testing.T) { func Test_DateFormat(t *testing.T) { gtest.C(t, func(t *gtest.T) { - val1 := "2010" - val2 := "201011" - val3 := "2010.11" - val4 := "201011-01" - val5 := "2010~11~01" - val6 := "2010-11~01" - err1 := g.Validator().Data(val1).Rules("date-format:Y").Run(ctx) - err2 := g.Validator().Data(val2).Rules("date-format:Ym").Run(ctx) - err3 := g.Validator().Data(val3).Rules("date-format:Y.m").Run(ctx) - err4 := g.Validator().Data(val4).Rules("date-format:Ym-d").Run(ctx) - err5 := g.Validator().Data(val5).Rules("date-format:Y~m~d").Run(ctx) - err6 := g.Validator().Data(val6).Rules("date-format:Y~m~d").Run(ctx) - t.Assert(err1, nil) - t.Assert(err2, nil) - t.Assert(err3, nil) - t.Assert(err4, nil) - t.Assert(err5, nil) - t.AssertNE(err6, nil) + m := g.MapStrStr{ + "2010": "date-format:Y", + "201011": "date-format:Ym", + "2010.11": "date-format:Y.m", + "201011-01": "date-format:Ym-d", + "2010~11~01": "date-format:Y~m~d", + "2010-11~01": "date-format:Y-m~d", + "2023-09-10T19:46:31Z": "date-format:2006-01-02\\T15:04:05Z07:00", // RFC3339 + } + for k, v := range m { + err := g.Validator().Data(k).Rules(v).Run(ctx) + t.AssertNil(err) + } + }) + gtest.C(t, func(t *gtest.T) { + errM := g.MapStrStr{ + "2010-11~01": "date-format:Y~m~d", + } + for k, v := range errM { + err := g.Validator().Data(k).Rules(v).Run(ctx) + t.AssertNE(err, nil) + } }) gtest.C(t, func(t *gtest.T) { t1 := gtime.Now() From 0b6dd6fb13436f6c7eb1268efbc173e8f6a405a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B5=B7=E4=BA=AE?= <739476267@qq.com> Date: Thu, 30 Nov 2023 18:59:49 +0800 Subject: [PATCH 21/52] improve initialization performance and logging content for cmd gf (#3174) --- cmd/gf/gfcmd/gfcmd.go | 18 +++++++++++------- cmd/gf/internal/utility/mlog/mlog.go | 6 +++++- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/cmd/gf/gfcmd/gfcmd.go b/cmd/gf/gfcmd/gfcmd.go index 6f3ff277e4d..00ce287bc24 100644 --- a/cmd/gf/gfcmd/gfcmd.go +++ b/cmd/gf/gfcmd/gfcmd.go @@ -7,20 +7,21 @@ package gfcmd import ( - _ "github.com/gogf/gf/cmd/gf/v2/internal/packed" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "context" + "runtime" - "github.com/gogf/gf/cmd/gf/v2/internal/cmd" - "github.com/gogf/gf/cmd/gf/v2/internal/utility/allyes" - "github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gcfg" "github.com/gogf/gf/v2/os/gcmd" "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/text/gstr" + + "github.com/gogf/gf/cmd/gf/v2/internal/cmd" + _ "github.com/gogf/gf/cmd/gf/v2/internal/packed" + "github.com/gogf/gf/cmd/gf/v2/internal/utility/allyes" + "github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog" ) const ( @@ -99,6 +100,9 @@ func GetCommand(ctx context.Context) (*Command, error) { // zsh alias "git fetch" conflicts checks. func handleZshAlias() { + if runtime.GOOS == "windows" { + return + } if home, err := gfile.Home(); err == nil { zshPath := gfile.Join(home, ".zshrc") if gfile.Exists(zshPath) { diff --git a/cmd/gf/internal/utility/mlog/mlog.go b/cmd/gf/internal/utility/mlog/mlog.go index d7af6553f76..7cbaa7699c7 100644 --- a/cmd/gf/internal/utility/mlog/mlog.go +++ b/cmd/gf/internal/utility/mlog/mlog.go @@ -24,15 +24,19 @@ var ( ) func init() { - logger.SetStack(false) if genv.Get(headerPrintEnvName).String() == "1" { logger.SetHeaderPrint(true) } else { logger.SetHeaderPrint(false) } + if gcmd.GetOpt("debug") != nil || gcmd.GetOpt("gf.debug") != nil { + logger.SetHeaderPrint(true) + logger.SetStackSkip(4) + logger.SetFlags(logger.GetFlags() | glog.F_FILE_LONG) logger.SetDebug(true) } else { + logger.SetStack(false) logger.SetDebug(false) } } From ee2cf92479a0575e07d3812d18b7eaea4fe10bbe Mon Sep 17 00:00:00 2001 From: John Guo Date: Mon, 4 Dec 2023 19:34:48 +0800 Subject: [PATCH 22/52] Version/v2.6.0 beta (#3183) --- cmd/gf/go.mod | 14 +++--- cmd/gf/go.sum | 14 ------ cmd/gf/internal/cmd/cmd_run.go | 16 +++--- cmd/gf/internal/cmd/genctrl/genctrl.go | 2 +- contrib/config/apollo/go.mod | 2 +- contrib/config/consul/go.mod | 2 +- contrib/config/kubecm/go.mod | 2 +- contrib/config/nacos/go.mod | 2 +- contrib/config/polaris/go.mod | 2 +- contrib/drivers/clickhouse/go.mod | 2 +- contrib/drivers/dm/go.mod | 2 +- contrib/drivers/mssql/go.mod | 2 +- contrib/drivers/mysql/go.mod | 2 +- contrib/drivers/oracle/go.mod | 2 +- contrib/drivers/pgsql/go.mod | 2 +- contrib/drivers/sqlite/go.mod | 2 +- contrib/drivers/sqlitecgo/go.mod | 2 +- contrib/nosql/redis/go.mod | 2 +- contrib/registry/etcd/go.mod | 2 +- contrib/registry/file/go.mod | 2 +- contrib/registry/nacos/go.mod | 2 +- contrib/registry/polaris/go.mod | 2 +- contrib/registry/zookeeper/go.mod | 2 +- contrib/rpc/grpcx/go.mod | 4 +- contrib/rpc/grpcx/grpcx_grpc_server_config.go | 49 ++++++++++++++----- contrib/sdk/httpclient/go.mod | 2 +- contrib/trace/jaeger/go.mod | 2 +- contrib/trace/otlpgrpc/go.mod | 2 +- contrib/trace/otlphttp/go.mod | 2 +- errors/gerror/gerror_api_option.go | 10 +++- errors/gerror/gerror_z_unit_test.go | 2 +- example/go.mod | 28 +++++------ net/ghttp/ghttp.go | 2 +- os/gcfg/gcfg_z_example_test.go | 19 +++++++ os/glog/glog_logger.go | 4 +- os/glog/glog_logger_handler.go | 2 +- os/gsession/gsession.go | 2 +- util/gvalid/gvalid_error.go | 2 +- version.go | 2 +- 39 files changed, 128 insertions(+), 90 deletions(-) diff --git a/cmd/gf/go.mod b/cmd/gf/go.mod index 48579f385b2..07c466123ad 100644 --- a/cmd/gf/go.mod +++ b/cmd/gf/go.mod @@ -3,13 +3,13 @@ module github.com/gogf/gf/cmd/gf/v2 go 1.18 require ( - github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.5.7 - github.com/gogf/gf/contrib/drivers/mssql/v2 v2.5.7 - github.com/gogf/gf/contrib/drivers/mysql/v2 v2.5.7 - github.com/gogf/gf/contrib/drivers/oracle/v2 v2.5.7 - github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.5.7 - github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.5.7 - github.com/gogf/gf/v2 v2.5.7 + github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.6.0-beta + github.com/gogf/gf/contrib/drivers/mssql/v2 v2.6.0-beta + github.com/gogf/gf/contrib/drivers/mysql/v2 v2.6.0-beta + github.com/gogf/gf/contrib/drivers/oracle/v2 v2.6.0-beta + github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.6.0-beta + github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.6.0-beta + github.com/gogf/gf/v2 v2.6.0-beta github.com/minio/selfupdate v0.6.0 github.com/olekukonko/tablewriter v0.0.5 golang.org/x/mod v0.9.0 diff --git a/cmd/gf/go.sum b/cmd/gf/go.sum index 533674fa5aa..bb5f8a4a868 100644 --- a/cmd/gf/go.sum +++ b/cmd/gf/go.sum @@ -38,20 +38,6 @@ github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiU github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI= github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= -github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.5.6 h1:yziPSf9AycEWphv9WiNjcRAVPOJtUauMMvP6pHQB4jY= -github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.5.6/go.mod h1:yOlpwhFXgW+P2sf4goA20PUtxdVLliBx4dJRyJeOtto= -github.com/gogf/gf/contrib/drivers/mssql/v2 v2.5.6 h1:LGQIe5IvYVr4hZ/vUAFiqWssxE7QeILyVPJ9swo1Cmk= -github.com/gogf/gf/contrib/drivers/mssql/v2 v2.5.6/go.mod h1:EcF8v8jqCV61/YqN6DXxdo3kh8waGmEj6WpFqbLkkrM= -github.com/gogf/gf/contrib/drivers/mysql/v2 v2.5.6 h1:oR9F4LVoKa/fjf/o6Y/CQRNiYy35Bszo07WwvMWYMxo= -github.com/gogf/gf/contrib/drivers/mysql/v2 v2.5.6/go.mod h1:gvHSRqCpv2c+N0gDHsEldHgU/yM9tcCBdIEKZ32/TaE= -github.com/gogf/gf/contrib/drivers/oracle/v2 v2.5.6 h1:3Y3lEoO9SoG1AmfaKjgTsDt93+T2q/qTMog8wBvIIGM= -github.com/gogf/gf/contrib/drivers/oracle/v2 v2.5.6/go.mod h1:cR3lFoU6ZtSaMQ3DpCJwWnYW6EvHPYGGeqv/kzgH4gw= -github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.5.6 h1:0WHVzqITqIBu/NNPXt3tN2eiWAGiNjs9sg6wh+WbUvY= -github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.5.6/go.mod h1:qZCTNQ0n2gHcuBwM9wUl3pelync3xK0gTnChJZD6f0I= -github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.5.6 h1:6clfLvFoHXHdw+skmXg4yxw+cLwgAG8gRiS/6f9Y9Xc= -github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.5.6/go.mod h1:QV6Rrj+4G4OaJVkP9XXRZ1LWL+ls6qH7ebeMcxsulqA= -github.com/gogf/gf/v2 v2.5.6 h1:a1UK1yUP3s+l+vPxmV91+8gTarAP9b1IEOw0W7LNl6E= -github.com/gogf/gf/v2 v2.5.6/go.mod h1:17K/gBYrp0bHGC3XYC7bSPoywmZ6MrZHrZakTfh4eIQ= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY= github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= diff --git a/cmd/gf/internal/cmd/cmd_run.go b/cmd/gf/internal/cmd/cmd_run.go index 1771f81cab7..337ba7aa697 100644 --- a/cmd/gf/internal/cmd/cmd_run.go +++ b/cmd/gf/internal/cmd/cmd_run.go @@ -82,11 +82,11 @@ func init() { type ( cRunInput struct { g.Meta `name:"run"` - File string `name:"FILE" arg:"true" brief:"{cRunFileBrief}" v:"required"` - Path string `name:"path" short:"p" brief:"{cRunPathBrief}" d:"./"` - Extra string `name:"extra" short:"e" brief:"{cRunExtraBrief}"` - Args string `name:"args" short:"a" brief:"{cRunArgsBrief}"` - WatchPaths string `name:"watchPaths" short:"w" brief:"{cRunWatchPathsBrief}"` + File string `name:"FILE" arg:"true" brief:"{cRunFileBrief}" v:"required"` + Path string `name:"path" short:"p" brief:"{cRunPathBrief}" d:"./"` + Extra string `name:"extra" short:"e" brief:"{cRunExtraBrief}"` + Args string `name:"args" short:"a" brief:"{cRunArgsBrief}"` + WatchPaths []string `name:"watchPaths" short:"w" brief:"{cRunWatchPathsBrief}"` } cRunOutput struct{} ) @@ -97,12 +97,16 @@ func (c cRun) Index(ctx context.Context, in cRunInput) (out *cRunOutput, err err mlog.Fatalf(`command "go" not found in your environment, please install golang first to proceed this command`) } + if len(in.WatchPaths) == 1 { + in.WatchPaths = strings.Split(in.WatchPaths[0], ",") + } + app := &cRunApp{ File: in.File, Path: in.Path, Options: in.Extra, Args: in.Args, - WatchPaths: strings.Split(in.WatchPaths, ","), + WatchPaths: in.WatchPaths, } dirty := gtype.NewBool() _, err = gfsnotify.Add(gfile.RealPath("."), func(event *gfsnotify.Event) { diff --git a/cmd/gf/internal/cmd/genctrl/genctrl.go b/cmd/gf/internal/cmd/genctrl/genctrl.go index a651a3d8c9d..d7d4b4bdf6a 100644 --- a/cmd/gf/internal/cmd/genctrl/genctrl.go +++ b/cmd/gf/internal/cmd/genctrl/genctrl.go @@ -74,7 +74,7 @@ type ( SdkStdVersion bool `short:"v" name:"sdkStdVersion" brief:"{CGenCtrlBriefSdkStdVersion}" orphan:"true"` SdkNoV1 bool `short:"n" name:"sdkNoV1" brief:"{CGenCtrlBriefSdkNoV1}" orphan:"true"` Clear bool `short:"c" name:"clear" brief:"{CGenCtrlBriefClear}" orphan:"true"` - Merge bool `short:"m" name:"merge" brief:"{CGenCtrlControllerMerge}" orphan:"true"` + Merge bool `short:"m" name:"merge" brief:"{CGenCtrlControllerMerge}" orphan:"true"` } CGenCtrlOutput struct{} ) diff --git a/contrib/config/apollo/go.mod b/contrib/config/apollo/go.mod index 660c4782018..1c2171cdb1e 100644 --- a/contrib/config/apollo/go.mod +++ b/contrib/config/apollo/go.mod @@ -4,7 +4,7 @@ go 1.18 require ( github.com/apolloconfig/agollo/v4 v4.3.1 - github.com/gogf/gf/v2 v2.5.7 + github.com/gogf/gf/v2 v2.6.0-beta ) require ( diff --git a/contrib/config/consul/go.mod b/contrib/config/consul/go.mod index bf1c2fcb46d..907314f91a3 100644 --- a/contrib/config/consul/go.mod +++ b/contrib/config/consul/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/consul/v2 go 1.19 require ( - github.com/gogf/gf/v2 v2.5.7 + github.com/gogf/gf/v2 v2.6.0-beta github.com/hashicorp/consul/api v1.24.0 github.com/hashicorp/go-cleanhttp v0.5.2 ) diff --git a/contrib/config/kubecm/go.mod b/contrib/config/kubecm/go.mod index 3f9770b1bc4..cd7162dfc6f 100644 --- a/contrib/config/kubecm/go.mod +++ b/contrib/config/kubecm/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/kubecm/v2 go 1.19 require ( - github.com/gogf/gf/v2 v2.5.7 + github.com/gogf/gf/v2 v2.6.0-beta k8s.io/api v0.27.4 k8s.io/apimachinery v0.27.4 k8s.io/client-go v0.27.4 diff --git a/contrib/config/nacos/go.mod b/contrib/config/nacos/go.mod index 48b6c46f481..bbc4a44612a 100644 --- a/contrib/config/nacos/go.mod +++ b/contrib/config/nacos/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/nacos/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.5.7 + github.com/gogf/gf/v2 v2.6.0-beta github.com/nacos-group/nacos-sdk-go v1.1.4 ) diff --git a/contrib/config/polaris/go.mod b/contrib/config/polaris/go.mod index 51ae7e0c964..00b065558bb 100644 --- a/contrib/config/polaris/go.mod +++ b/contrib/config/polaris/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/polaris/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.5.7 + github.com/gogf/gf/v2 v2.6.0-beta github.com/polarismesh/polaris-go v1.5.5 ) diff --git a/contrib/drivers/clickhouse/go.mod b/contrib/drivers/clickhouse/go.mod index b9a902dbdf0..ac63af72925 100644 --- a/contrib/drivers/clickhouse/go.mod +++ b/contrib/drivers/clickhouse/go.mod @@ -4,7 +4,7 @@ go 1.18 require ( github.com/ClickHouse/clickhouse-go/v2 v2.0.15 - github.com/gogf/gf/v2 v2.5.7 + github.com/gogf/gf/v2 v2.6.0-beta github.com/google/uuid v1.3.0 github.com/shopspring/decimal v1.3.1 ) diff --git a/contrib/drivers/dm/go.mod b/contrib/drivers/dm/go.mod index 2f187647a19..1b87b9593b2 100644 --- a/contrib/drivers/dm/go.mod +++ b/contrib/drivers/dm/go.mod @@ -6,7 +6,7 @@ replace github.com/gogf/gf/v2 => ../../../ require ( gitee.com/chunanyong/dm v1.8.12 - github.com/gogf/gf/v2 v2.5.7 + github.com/gogf/gf/v2 v2.6.0-beta ) require ( diff --git a/contrib/drivers/mssql/go.mod b/contrib/drivers/mssql/go.mod index 24b42a513ea..f910c220e65 100644 --- a/contrib/drivers/mssql/go.mod +++ b/contrib/drivers/mssql/go.mod @@ -4,7 +4,7 @@ go 1.18 require ( github.com/denisenkom/go-mssqldb v0.12.3 - github.com/gogf/gf/v2 v2.5.7 + github.com/gogf/gf/v2 v2.6.0-beta ) require ( diff --git a/contrib/drivers/mysql/go.mod b/contrib/drivers/mysql/go.mod index 21db76fdd75..618c6417c73 100644 --- a/contrib/drivers/mysql/go.mod +++ b/contrib/drivers/mysql/go.mod @@ -4,7 +4,7 @@ go 1.18 require ( github.com/go-sql-driver/mysql v1.7.1 - github.com/gogf/gf/v2 v2.5.7 + github.com/gogf/gf/v2 v2.6.0-beta ) require ( diff --git a/contrib/drivers/oracle/go.mod b/contrib/drivers/oracle/go.mod index d71523e1097..1dad9a248ab 100644 --- a/contrib/drivers/oracle/go.mod +++ b/contrib/drivers/oracle/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/drivers/oracle/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.5.7 + github.com/gogf/gf/v2 v2.6.0-beta github.com/sijms/go-ora/v2 v2.7.10 ) diff --git a/contrib/drivers/pgsql/go.mod b/contrib/drivers/pgsql/go.mod index 5da1ae1ef52..b6f82b5e4e5 100644 --- a/contrib/drivers/pgsql/go.mod +++ b/contrib/drivers/pgsql/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/drivers/pgsql/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.5.7 + github.com/gogf/gf/v2 v2.6.0-beta github.com/lib/pq v1.10.9 ) diff --git a/contrib/drivers/sqlite/go.mod b/contrib/drivers/sqlite/go.mod index acf2067b522..840fa0764b0 100644 --- a/contrib/drivers/sqlite/go.mod +++ b/contrib/drivers/sqlite/go.mod @@ -4,7 +4,7 @@ go 1.18 require ( github.com/glebarez/go-sqlite v1.21.2 - github.com/gogf/gf/v2 v2.5.7 + github.com/gogf/gf/v2 v2.6.0-beta ) require ( diff --git a/contrib/drivers/sqlitecgo/go.mod b/contrib/drivers/sqlitecgo/go.mod index ee53a450d44..392f7e381de 100644 --- a/contrib/drivers/sqlitecgo/go.mod +++ b/contrib/drivers/sqlitecgo/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/drivers/sqlitecgo/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.5.7 + github.com/gogf/gf/v2 v2.6.0-beta github.com/mattn/go-sqlite3 v1.14.17 ) diff --git a/contrib/nosql/redis/go.mod b/contrib/nosql/redis/go.mod index 0284ad9f7d6..f7029eb4e2f 100644 --- a/contrib/nosql/redis/go.mod +++ b/contrib/nosql/redis/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/nosql/redis/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.5.7 + github.com/gogf/gf/v2 v2.6.0-beta github.com/redis/go-redis/v9 v9.2.1 go.opentelemetry.io/otel v1.14.0 go.opentelemetry.io/otel/trace v1.14.0 diff --git a/contrib/registry/etcd/go.mod b/contrib/registry/etcd/go.mod index 159a9c2100f..a036cd9adba 100644 --- a/contrib/registry/etcd/go.mod +++ b/contrib/registry/etcd/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/registry/etcd/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.5.7 + github.com/gogf/gf/v2 v2.6.0-beta go.etcd.io/etcd/client/v3 v3.5.7 ) diff --git a/contrib/registry/file/go.mod b/contrib/registry/file/go.mod index 83b0ca1c506..1f950ab51bc 100644 --- a/contrib/registry/file/go.mod +++ b/contrib/registry/file/go.mod @@ -2,7 +2,7 @@ module github.com/gogf/gf/contrib/registry/file/v2 go 1.18 -require github.com/gogf/gf/v2 v2.5.7 +require github.com/gogf/gf/v2 v2.6.0-beta require ( github.com/BurntSushi/toml v1.2.0 // indirect diff --git a/contrib/registry/nacos/go.mod b/contrib/registry/nacos/go.mod index bddf9aaa5be..0055ac90c68 100644 --- a/contrib/registry/nacos/go.mod +++ b/contrib/registry/nacos/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/registry/nacos/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.5.7 + github.com/gogf/gf/v2 v2.6.0-beta github.com/joy999/nacos-sdk-go v0.0.0-20231120071639-10a34b3e7288 ) diff --git a/contrib/registry/polaris/go.mod b/contrib/registry/polaris/go.mod index 92c0663d2f0..cbc70976e9a 100644 --- a/contrib/registry/polaris/go.mod +++ b/contrib/registry/polaris/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/registry/polaris/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.5.7 + github.com/gogf/gf/v2 v2.6.0-beta github.com/polarismesh/polaris-go v1.5.5 ) diff --git a/contrib/registry/zookeeper/go.mod b/contrib/registry/zookeeper/go.mod index 61ebd46a1b9..fad7faa5ab4 100644 --- a/contrib/registry/zookeeper/go.mod +++ b/contrib/registry/zookeeper/go.mod @@ -4,7 +4,7 @@ go 1.18 require ( github.com/go-zookeeper/zk v1.0.3 - github.com/gogf/gf/v2 v2.5.7 + github.com/gogf/gf/v2 v2.6.0-beta golang.org/x/sync v0.4.0 ) diff --git a/contrib/rpc/grpcx/go.mod b/contrib/rpc/grpcx/go.mod index eb893110e5a..593fe01987d 100644 --- a/contrib/rpc/grpcx/go.mod +++ b/contrib/rpc/grpcx/go.mod @@ -3,8 +3,8 @@ module github.com/gogf/gf/contrib/rpc/grpcx/v2 go 1.18 require ( - github.com/gogf/gf/contrib/registry/file/v2 v2.5.7 - github.com/gogf/gf/v2 v2.5.7 + github.com/gogf/gf/contrib/registry/file/v2 v2.6.0-beta + github.com/gogf/gf/v2 v2.6.0-beta go.opentelemetry.io/otel v1.14.0 go.opentelemetry.io/otel/trace v1.14.0 google.golang.org/grpc v1.57.2 diff --git a/contrib/rpc/grpcx/grpcx_grpc_server_config.go b/contrib/rpc/grpcx/grpcx_grpc_server_config.go index bcc24b121bb..47ab655da92 100644 --- a/contrib/rpc/grpcx/grpcx_grpc_server_config.go +++ b/contrib/rpc/grpcx/grpcx_grpc_server_config.go @@ -8,7 +8,6 @@ package grpcx import ( "context" - "google.golang.org/grpc" "github.com/gogf/gf/v2/frame/g" @@ -18,18 +17,41 @@ import ( // GrpcServerConfig is the configuration for server. type GrpcServerConfig struct { - Address string // (optional) Single address for server listening, use `:0` or `ip:0` to serve random port. - Name string // (optional) Name for current service. - Logger *glog.Logger // (optional) Logger for server. - LogPath string // (optional) LogPath specifies the directory for storing logging files. - LogStdout bool // (optional) LogStdout specifies whether printing logging content to stdout. - ErrorStack bool // (optional) ErrorStack specifies whether logging stack information when error. - ErrorLogEnabled bool // (optional) ErrorLogEnabled enables error logging content to files. - ErrorLogPattern string // (optional) ErrorLogPattern specifies the error log file pattern like: error-{Ymd}.log - AccessLogEnabled bool // (optional) AccessLogEnabled enables access logging content to file. - AccessLogPattern string // (optional) AccessLogPattern specifies the error log file pattern like: access-{Ymd}.log - Endpoints []string // (optional) Endpoints are custom endpoints for service register, it uses Address if empty. - Options []grpc.ServerOption // (optional) GRPC Server options. + // (optional) Name for current service. + Name string + + // (optional) Single address for server listening, use `:0` or `ip:0` to serve random port. + Address string + + // (optional) Logger for server. + Logger *glog.Logger + + // (optional) LogPath specifies the directory for storing logging files. + LogPath string + + // (optional) LogStdout specifies whether printing logging content to stdout. + LogStdout bool + + // (optional) ErrorStack specifies whether logging stack information when error. + ErrorStack bool + + // (optional) ErrorLogEnabled enables error logging content to files. + ErrorLogEnabled bool + + // (optional) ErrorLogPattern specifies the error log file pattern like: error-{Ymd}.log + ErrorLogPattern string + + // (optional) AccessLogEnabled enables access logging content to file. + AccessLogEnabled bool + + // (optional) AccessLogPattern specifies the error log file pattern like: access-{Ymd}.log + AccessLogPattern string + + // (optional) Endpoints are custom endpoints for service register, it uses Address if empty. + Endpoints []string + + // (optional) GRPC Server options. + Options []grpc.ServerOption } // NewConfig creates and returns a ServerConfig object with default configurations. @@ -51,6 +73,7 @@ func (s modServer) NewConfig() *GrpcServerConfig { ) // Reading configuration file and updating the configured keys. if g.Cfg().Available(ctx) { + // Server attributes configuration. if err = g.Cfg().MustGet(ctx, configNodeNameGrpcServer).Struct(&config); err != nil { g.Log().Error(ctx, err) } diff --git a/contrib/sdk/httpclient/go.mod b/contrib/sdk/httpclient/go.mod index f848861ae92..5de6891c484 100644 --- a/contrib/sdk/httpclient/go.mod +++ b/contrib/sdk/httpclient/go.mod @@ -2,7 +2,7 @@ module github.com/gogf/gf/contrib/sdk/httpclient/v2 go 1.18 -require github.com/gogf/gf/v2 v2.5.7 +require github.com/gogf/gf/v2 v2.6.0-beta require ( github.com/BurntSushi/toml v1.2.0 // indirect diff --git a/contrib/trace/jaeger/go.mod b/contrib/trace/jaeger/go.mod index dd1ad15fc9c..0de613f6466 100644 --- a/contrib/trace/jaeger/go.mod +++ b/contrib/trace/jaeger/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/trace/jaeger/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.5.7 + github.com/gogf/gf/v2 v2.6.0-beta go.opentelemetry.io/otel v1.14.0 go.opentelemetry.io/otel/exporters/jaeger v1.14.0 go.opentelemetry.io/otel/sdk v1.14.0 diff --git a/contrib/trace/otlpgrpc/go.mod b/contrib/trace/otlpgrpc/go.mod index 867c1e99823..7962c8a252a 100644 --- a/contrib/trace/otlpgrpc/go.mod +++ b/contrib/trace/otlpgrpc/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/trace/otlpgrpc/v2 go 1.20 require ( - github.com/gogf/gf/v2 v2.5.7 + github.com/gogf/gf/v2 v2.6.0-beta go.opentelemetry.io/otel v1.19.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.19.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.19.0 diff --git a/contrib/trace/otlphttp/go.mod b/contrib/trace/otlphttp/go.mod index 83d998684ef..3c110331d99 100644 --- a/contrib/trace/otlphttp/go.mod +++ b/contrib/trace/otlphttp/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/trace/otlphttp/v2 go 1.20 require ( - github.com/gogf/gf/v2 v2.5.7 + github.com/gogf/gf/v2 v2.6.0-beta go.opentelemetry.io/otel v1.19.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.19.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.19.0 diff --git a/errors/gerror/gerror_api_option.go b/errors/gerror/gerror_api_option.go index 33ed881f775..4ac7f1d9320 100644 --- a/errors/gerror/gerror_api_option.go +++ b/errors/gerror/gerror_api_option.go @@ -16,9 +16,9 @@ type Option struct { Code gcode.Code // Error code if necessary. } -// NewOption creates and returns a custom error with Option. +// NewWithOption creates and returns a custom error with Option. // It is the senior usage for creating error, which is often used internally in framework. -func NewOption(option Option) error { +func NewWithOption(option Option) error { err := &Error{ error: option.Error, text: option.Text, @@ -29,3 +29,9 @@ func NewOption(option Option) error { } return err } + +// NewOption creates and returns a custom error with Option. +// Deprecated: use NewWithOption instead. +func NewOption(option Option) error { + return NewWithOption(option) +} diff --git a/errors/gerror/gerror_z_unit_test.go b/errors/gerror/gerror_z_unit_test.go index 7ea90bd9348..71a1b4fc792 100644 --- a/errors/gerror/gerror_z_unit_test.go +++ b/errors/gerror/gerror_z_unit_test.go @@ -442,7 +442,7 @@ func Test_HashCode(t *testing.T) { func Test_NewOption(t *testing.T) { gtest.C(t, func(t *gtest.T) { - t.AssertNE(gerror.NewOption(gerror.Option{ + t.AssertNE(gerror.NewWithOption(gerror.Option{ Error: errors.New("NewOptionError"), Stack: true, Text: "Text", diff --git a/example/go.mod b/example/go.mod index c95a2700d82..26a4c0eff2b 100644 --- a/example/go.mod +++ b/example/go.mod @@ -3,21 +3,21 @@ module github.com/gogf/gf/example go 1.20 require ( - github.com/gogf/gf/contrib/config/apollo/v2 v2.5.7 - github.com/gogf/gf/contrib/config/consul/v2 v2.5.7 - github.com/gogf/gf/contrib/config/kubecm/v2 v2.5.7 - github.com/gogf/gf/contrib/config/nacos/v2 v2.5.7 - github.com/gogf/gf/contrib/config/polaris/v2 v2.5.7 - github.com/gogf/gf/contrib/drivers/mysql/v2 v2.5.7 - github.com/gogf/gf/contrib/nosql/redis/v2 v2.5.7 - github.com/gogf/gf/contrib/registry/etcd/v2 v2.5.7 - github.com/gogf/gf/contrib/registry/file/v2 v2.5.7 + github.com/gogf/gf/contrib/config/apollo/v2 v2.6.0-beta + github.com/gogf/gf/contrib/config/consul/v2 v2.6.0-beta + github.com/gogf/gf/contrib/config/kubecm/v2 v2.6.0-beta + github.com/gogf/gf/contrib/config/nacos/v2 v2.6.0-beta + github.com/gogf/gf/contrib/config/polaris/v2 v2.6.0-beta + github.com/gogf/gf/contrib/drivers/mysql/v2 v2.6.0-beta + github.com/gogf/gf/contrib/nosql/redis/v2 v2.6.0-beta + github.com/gogf/gf/contrib/registry/etcd/v2 v2.6.0-beta + github.com/gogf/gf/contrib/registry/file/v2 v2.6.0-beta github.com/gogf/gf/contrib/registry/nacos/v2 v2.5.6 - github.com/gogf/gf/contrib/registry/polaris/v2 v2.5.7 - github.com/gogf/gf/contrib/rpc/grpcx/v2 v2.5.7 - github.com/gogf/gf/contrib/trace/otlpgrpc/v2 v2.5.7 - github.com/gogf/gf/contrib/trace/otlphttp/v2 v2.5.7 - github.com/gogf/gf/v2 v2.5.7 + github.com/gogf/gf/contrib/registry/polaris/v2 v2.6.0-beta + github.com/gogf/gf/contrib/rpc/grpcx/v2 v2.6.0-beta + github.com/gogf/gf/contrib/trace/otlpgrpc/v2 v2.6.0-beta + github.com/gogf/gf/contrib/trace/otlphttp/v2 v2.6.0-beta + github.com/gogf/gf/v2 v2.6.0-beta github.com/hashicorp/consul/api v1.24.0 github.com/hashicorp/go-cleanhttp v0.5.2 github.com/nacos-group/nacos-sdk-go v1.1.4 diff --git a/net/ghttp/ghttp.go b/net/ghttp/ghttp.go index 3d120427197..6d53f66d614 100644 --- a/net/ghttp/ghttp.go +++ b/net/ghttp/ghttp.go @@ -205,7 +205,7 @@ var ( ) var ( - ErrNeedJsonBody = gerror.NewOption(gerror.Option{ + ErrNeedJsonBody = gerror.NewWithOption(gerror.Option{ Text: "the request body content should be JSON format", Code: gcode.CodeInvalidRequest, }) diff --git a/os/gcfg/gcfg_z_example_test.go b/os/gcfg/gcfg_z_example_test.go index a64a2e4cae2..d45d74e6aa0 100644 --- a/os/gcfg/gcfg_z_example_test.go +++ b/os/gcfg/gcfg_z_example_test.go @@ -11,6 +11,7 @@ import ( "os" "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/os/gcfg" "github.com/gogf/gf/v2/os/gcmd" "github.com/gogf/gf/v2/os/gctx" "github.com/gogf/gf/v2/os/genv" @@ -64,3 +65,21 @@ func ExampleConfig_GetWithCmd() { // cmd: // cmd:yes } + +func Example_NewWithAdapter() { + var ( + ctx = gctx.New() + content = `{"a":"b", "c":1}` + adapter, err = gcfg.NewAdapterContent(content) + ) + if err != nil { + panic(err) + } + config := gcfg.NewWithAdapter(adapter) + fmt.Println(config.MustGet(ctx, "a")) + fmt.Println(config.MustGet(ctx, "c")) + + // Output: + // b + // 1 +} diff --git a/os/glog/glog_logger.go b/os/glog/glog_logger.go index 5eb8b3c246b..b2484553e8c 100644 --- a/os/glog/glog_logger.go +++ b/os/glog/glog_logger.go @@ -219,8 +219,8 @@ func (l *Logger) print(ctx context.Context, level int, stack string, values ...a } } -// doDefaultPrint outputs the logging content according configuration. -func (l *Logger) doDefaultPrint(ctx context.Context, input *HandlerInput) *bytes.Buffer { +// doFinalPrint outputs the logging content according configuration. +func (l *Logger) doFinalPrint(ctx context.Context, input *HandlerInput) *bytes.Buffer { var buffer *bytes.Buffer // Allow output to stdout? if l.config.StdoutPrint { diff --git a/os/glog/glog_logger_handler.go b/os/glog/glog_logger_handler.go index 9b632beaa79..e2d931592c3 100644 --- a/os/glog/glog_logger_handler.go +++ b/os/glog/glog_logger_handler.go @@ -49,7 +49,7 @@ var defaultHandler Handler // doFinalPrint is a handler for logging content printing. // This handler outputs logging content to file/stdout/write if any of them configured. func doFinalPrint(ctx context.Context, in *HandlerInput) { - buffer := in.Logger.doDefaultPrint(ctx, in) + buffer := in.Logger.doFinalPrint(ctx, in) if in.Buffer.Len() == 0 { in.Buffer = buffer } diff --git a/os/gsession/gsession.go b/os/gsession/gsession.go index fa09173837f..e6ed66e63ce 100644 --- a/os/gsession/gsession.go +++ b/os/gsession/gsession.go @@ -15,7 +15,7 @@ import ( var ( // ErrorDisabled is used for marking certain interface function not used. - ErrorDisabled = gerror.NewOption(gerror.Option{ + ErrorDisabled = gerror.NewWithOption(gerror.Option{ Text: "this feature is disabled in this storage", Code: gcode.CodeNotSupported, }) diff --git a/util/gvalid/gvalid_error.go b/util/gvalid/gvalid_error.go index cd6593da747..099c8987850 100644 --- a/util/gvalid/gvalid_error.go +++ b/util/gvalid/gvalid_error.go @@ -44,7 +44,7 @@ func newValidationError(code gcode.Code, rules []fieldRule, fieldRuleErrorMap ma for field, ruleErrorMap := range fieldRuleErrorMap { for rule, err := range ruleErrorMap { if !gerror.HasStack(err) { - ruleErrorMap[rule] = gerror.NewOption(gerror.Option{ + ruleErrorMap[rule] = gerror.NewWithOption(gerror.Option{ Stack: false, Text: gstr.Trim(err.Error()), Code: code, diff --git a/version.go b/version.go index 2cd4a2f6ea7..12825ec9cef 100644 --- a/version.go +++ b/version.go @@ -2,5 +2,5 @@ package gf const ( // VERSION is the current GoFrame version. - VERSION = "v2.5.7" + VERSION = "v2.6.0-beta" ) From 33584506ab17d7236fb31e6b45fe15791b8979eb Mon Sep 17 00:00:00 2001 From: zhangyuyu <1580074674@qq.com> Date: Thu, 14 Dec 2023 14:18:31 +0800 Subject: [PATCH 23/52] fix issue: request body was closed while retrying in callRequest method (#3199) --- net/gclient/gclient_request.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/net/gclient/gclient_request.go b/net/gclient/gclient_request.go index 88dac9dc222..ecaa467bbad 100644 --- a/net/gclient/gclient_request.go +++ b/net/gclient/gclient_request.go @@ -338,8 +338,8 @@ func (c *Client) callRequest(req *http.Request) (resp *Response, err error) { // raw HTTP request-response procedure. reqBodyContent, _ := io.ReadAll(req.Body) resp.requestBody = reqBodyContent - req.Body = utils.NewReadCloser(reqBodyContent, false) for { + req.Body = utils.NewReadCloser(reqBodyContent, false) if resp.Response, err = c.Do(req); err != nil { err = gerror.Wrapf(err, `request failed`) // The response might not be nil when err != nil. From dd8a5dcf32532a73959fa851272db31104dcb3af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B5=B7=E4=BA=AE?= <739476267@qq.com> Date: Thu, 14 Dec 2023 21:51:28 +0800 Subject: [PATCH 24/52] fix: #3179 (#3195) --- net/ghttp/ghttp_server_admin_process.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/net/ghttp/ghttp_server_admin_process.go b/net/ghttp/ghttp_server_admin_process.go index 9bfead5941b..7aa12b81f25 100644 --- a/net/ghttp/ghttp_server_admin_process.go +++ b/net/ghttp/ghttp_server_admin_process.go @@ -117,7 +117,7 @@ func forkReloadProcess(ctx context.Context, newExeFilePath ...string) error { var ( path = os.Args[0] ) - if len(newExeFilePath) > 0 { + if len(newExeFilePath) > 0 && newExeFilePath[0] != "" { path = newExeFilePath[0] } var ( @@ -156,12 +156,12 @@ func forkReloadProcess(ctx context.Context, newExeFilePath ...string) error { } // forkRestartProcess creates a new server process. -func forkRestartProcess(ctx context.Context, newExeFilePath string) error { +func forkRestartProcess(ctx context.Context, newExeFilePath ...string) error { var ( path = os.Args[0] ) - if newExeFilePath != "" { - path = newExeFilePath + if len(newExeFilePath) > 0 && newExeFilePath[0] != "" { + path = newExeFilePath[0] } if err := os.Unsetenv(adminActionReloadEnvKey); err != nil { intlog.Errorf(ctx, `%+v`, err) From fc02e0642330450b6a4d1dab31f088db1ff58479 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B5=B7=E4=BA=AE?= <739476267@qq.com> Date: Fri, 15 Dec 2023 15:56:08 +0800 Subject: [PATCH 25/52] doc: update readme img (#3207) --- .github/workflows/golangci-lint.yml | 2 +- README.MD | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index 7578b4d4a4d..dc5c86c6e93 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -36,7 +36,7 @@ jobs: golangci: strategy: matrix: - go-version: [ '1.18','1.19','1.20','1.21' ] + go-version: [ '1.18','1.19','1.20','1.21.4' ] name: golangci-lint runs-on: ubuntu-latest steps: diff --git a/README.MD b/README.MD index eb4dd5c6e61..85ed14b3dc2 100644 --- a/README.MD +++ b/README.MD @@ -9,6 +9,15 @@ [![Code Coverage](https://codecov.io/gh/gogf/gf/branch/master/graph/badge.svg)](https://codecov.io/gh/gogf/gf) [![Production Ready](https://img.shields.io/badge/production-ready-blue.svg)](https://github.com/gogf/gf) [![License](https://img.shields.io/github/license/gogf/gf.svg?style=flat)](https://github.com/gogf/gf) + +[![Release](https://img.shields.io/github/v/release/gogf/gf)](https://github.com/gogf/gf/releases) +[![GitHub pull requests](https://img.shields.io/github/issues-pr/gogf/gf)](https://github.com/gogf/gf/pulls) +[![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed/gogf/gf)](https://github.com/gogf/gf/pulls?q=is%3Apr+is%3Aclosed) +[![GitHub issues](https://img.shields.io/github/issues/gogf/gf)](https://github.com/gogf/gf/issues) +[![GitHub closed issues](https://img.shields.io/github/issues-closed/gogf/gf)](https://github.com/gogf/gf/issues?q=is%3Aissue+is%3Aclosed) +![Stars](https://img.shields.io/github/stars/gogf/gf) +![Forks](https://img.shields.io/github/forks/gogf/gf) + `GoFrame` is a modular, powerful, high-performance and enterprise-class application development framework of Golang. From bb19877430bc1cf45bda802f0a45c56310a87a68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B5=B7=E4=BA=AE?= <739476267@qq.com> Date: Mon, 18 Dec 2023 19:11:39 +0800 Subject: [PATCH 26/52] fix: #3197 (#3206) --- cmd/gf/go.mod | 2 +- cmd/gf/go.sum | 5 ++--- cmd/gf/internal/cmd/cmd_up.go | 2 +- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/cmd/gf/go.mod b/cmd/gf/go.mod index 07c466123ad..9a9faae1fe7 100644 --- a/cmd/gf/go.mod +++ b/cmd/gf/go.mod @@ -10,7 +10,7 @@ require ( github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.6.0-beta github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.6.0-beta github.com/gogf/gf/v2 v2.6.0-beta - github.com/minio/selfupdate v0.6.0 + github.com/gogf/selfupdate v0.0.0-20231215043001-5c48c528462f github.com/olekukonko/tablewriter v0.0.5 golang.org/x/mod v0.9.0 golang.org/x/tools v0.7.0 diff --git a/cmd/gf/go.sum b/cmd/gf/go.sum index bb5f8a4a868..349b148ec49 100644 --- a/cmd/gf/go.sum +++ b/cmd/gf/go.sum @@ -38,6 +38,8 @@ github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiU github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI= github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= +github.com/gogf/selfupdate v0.0.0-20231215043001-5c48c528462f h1:7xfXR/BhG3JDqO1s45n65Oyx9t4E/UqDOXep6jXdLCM= +github.com/gogf/selfupdate v0.0.0-20231215043001-5c48c528462f/go.mod h1:HnYoio6S7VaFJdryKcD/r9HgX+4QzYfr00XiXUo/xz0= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY= github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= @@ -73,8 +75,6 @@ github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-sqlite3 v1.9.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= -github.com/minio/selfupdate v0.6.0 h1:i76PgT0K5xO9+hjzKcacQtO7+MjJ4JKA8Ak8XQ9DDwU= -github.com/minio/selfupdate v0.6.0/go.mod h1:bO02GTIPCMQFTEvE5h4DjYB58bCoZ35XLeBf0buTDdM= github.com/mkevac/debugcharts v0.0.0-20191222103121-ae1c48aa8615/go.mod h1:Ad7oeElCZqA1Ufj0U9/liOF4BtVepxRcTvr2ey7zTvM= github.com/modocache/gover v0.0.0-20171022184752-b58185e213c5/go.mod h1:caMODM3PzxT8aQXRPkAt8xlV/e7d7w8GM5g0fa5F0D8= github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= @@ -126,7 +126,6 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= -golang.org/x/crypto v0.0.0-20211209193657-4570a0811e8b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc= golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= diff --git a/cmd/gf/internal/cmd/cmd_up.go b/cmd/gf/internal/cmd/cmd_up.go index a0882a63d87..c26c636ca99 100644 --- a/cmd/gf/internal/cmd/cmd_up.go +++ b/cmd/gf/internal/cmd/cmd_up.go @@ -11,7 +11,7 @@ import ( "fmt" "runtime" - "github.com/minio/selfupdate" + "github.com/gogf/selfupdate" "github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog" "github.com/gogf/gf/cmd/gf/v2/internal/utility/utils" From 44819b135ecac57ec8a76d0410a02cf26920b335 Mon Sep 17 00:00:00 2001 From: John Guo Date: Mon, 18 Dec 2023 20:19:18 +0800 Subject: [PATCH 27/52] fix issue #3204 (#3212) --- contrib/drivers/mysql/mysql_issue_test.go | 25 +++++++++++++++++++++++ database/gdb/gdb_core_structure.go | 2 +- database/gdb/gdb_func.go | 18 +++++++++++----- database/gdb/gdb_model_insert.go | 2 +- 4 files changed, 40 insertions(+), 7 deletions(-) diff --git a/contrib/drivers/mysql/mysql_issue_test.go b/contrib/drivers/mysql/mysql_issue_test.go index 0a8a2687233..a57ba1ea1bf 100644 --- a/contrib/drivers/mysql/mysql_issue_test.go +++ b/contrib/drivers/mysql/mysql_issue_test.go @@ -881,3 +881,28 @@ func Test_Issue3086(t *testing.T) { t.Assert(n, 2) }) } + +// https://github.com/gogf/gf/issues/3204 +func Test_Issue3204(t *testing.T) { + table := createInitTable() + defer dropTable(table) + db.SetDebug(true) + gtest.C(t, func(t *gtest.T) { + type User struct { + g.Meta `orm:"do:true"` + Id interface{} `orm:"id,omitempty"` + Passport interface{} `orm:"passport,omitempty"` + Password interface{} `orm:"password,omitempty"` + Nickname interface{} `orm:"nickname,omitempty"` + CreateTime interface{} `orm:"create_time,omitempty"` + } + where := User{ + Id: 2, + Passport: "", + } + all, err := db.Model(table).Where(where).All() + t.AssertNil(err) + t.Assert(len(all), 1) + t.Assert(all[0]["id"], 2) + }) +} diff --git a/database/gdb/gdb_core_structure.go b/database/gdb/gdb_core_structure.go index da4980d0cdc..bcfa5abb19c 100644 --- a/database/gdb/gdb_core_structure.go +++ b/database/gdb/gdb_core_structure.go @@ -60,7 +60,7 @@ func (c *Core) GetFieldType(ctx context.Context, fieldName, table, schema string func (c *Core) ConvertDataForRecord(ctx context.Context, value interface{}, table string) (map[string]interface{}, error) { var ( err error - data = DataToMapDeep(value) + data = MapOrStructToMapDeep(value, false) ) for fieldName, fieldValue := range data { data[fieldName], err = c.db.ConvertValueForField( diff --git a/database/gdb/gdb_func.go b/database/gdb/gdb_func.go index ec5850902a5..3fbf1e7de5f 100644 --- a/database/gdb/gdb_func.go +++ b/database/gdb/gdb_func.go @@ -213,11 +213,19 @@ func anyValueToMapBeforeToRecord(value interface{}) map[string]interface{} { return gconv.Map(value, gconv.MapOption{Tags: structTagPriority}) } -// DataToMapDeep converts `value` to map type recursively(if attribute struct is embedded). +// DaToMapDeep is deprecated, use MapOrStructToMapDeep instead. +func DaToMapDeep(value interface{}) map[string]interface{} { + return MapOrStructToMapDeep(value, false) +} + +// MapOrStructToMapDeep converts `value` to map type recursively(if attribute struct is embedded). // The parameter `value` should be type of *map/map/*struct/struct. // It supports embedded struct definition for struct. -func DataToMapDeep(value interface{}) map[string]interface{} { - m := gconv.Map(value, gconv.MapOption{Tags: structTagPriority}) +func MapOrStructToMapDeep(value interface{}, omitempty bool) map[string]interface{} { + m := gconv.Map(value, gconv.MapOption{ + Tags: structTagPriority, + OmitEmpty: omitempty, + }) for k, v := range m { switch v.(type) { case time.Time, *time.Time, gtime.Time, *gtime.Time, gjson.Json, *gjson.Json: @@ -413,7 +421,7 @@ func formatWhereHolder(ctx context.Context, db DB, in formatWhereHolderInput) (n newArgs = formatWhereInterfaces(db, gconv.Interfaces(in.Where), buffer, newArgs) case reflect.Map: - for key, value := range DataToMapDeep(in.Where) { + for key, value := range MapOrStructToMapDeep(in.Where, true) { if in.OmitNil && empty.IsNil(value) { continue } @@ -468,7 +476,7 @@ func formatWhereHolder(ctx context.Context, db DB, in formatWhereHolderInput) (n var ( reflectType = reflectInfo.OriginValue.Type() structField reflect.StructField - data = DataToMapDeep(in.Where) + data = MapOrStructToMapDeep(in.Where, true) ) // If `Prefix` is given, it checks and retrieves the table name. if in.Prefix != "" { diff --git a/database/gdb/gdb_model_insert.go b/database/gdb/gdb_model_insert.go index 343f36a5e6d..bc6b8aa82be 100644 --- a/database/gdb/gdb_model_insert.go +++ b/database/gdb/gdb_model_insert.go @@ -268,7 +268,7 @@ func (m *Model) doInsertWithOption(ctx context.Context, insertOption InsertOptio default: // It uses gconv.Map here to simply fo the type converting from interface{} to map[string]interface{}, - // as there's another DataToMapDeep in next logic to do the deep converting. + // as there's another MapOrStructToMapDeep in next logic to do the deep converting. reflectInfo := reflection.OriginValueAndKind(newData) switch reflectInfo.OriginKind { // If it's slice type, it then converts it to List type. From 565790036e906378dd126dcd5b5ed0639a606079 Mon Sep 17 00:00:00 2001 From: zhangyuyu <1580074674@qq.com> Date: Mon, 18 Dec 2023 20:26:43 +0800 Subject: [PATCH 28/52] improve gen dao to support removeFieldPrefix (#3208) --- cmd/gf/internal/cmd/gendao/gendao.go | 47 ++++++------ cmd/gf/internal/cmd/gendao/gendao_dao.go | 25 ++++-- .../internal/cmd/gendao/gendao_structure.go | 7 +- .../internal/cmd/genpbentity/genpbentity.go | 76 +++++++++++-------- 4 files changed, 93 insertions(+), 62 deletions(-) diff --git a/cmd/gf/internal/cmd/gendao/gendao.go b/cmd/gf/internal/cmd/gendao/gendao.go index 5da3ba57773..37f9ac551f3 100644 --- a/cmd/gf/internal/cmd/gendao/gendao.go +++ b/cmd/gf/internal/cmd/gendao/gendao.go @@ -59,28 +59,29 @@ CONFIGURATION SUPPORT numeric: type: string ` - CGenDaoBriefPath = `directory path for generated files` - CGenDaoBriefLink = `database configuration, the same as the ORM configuration of GoFrame` - CGenDaoBriefTables = `generate models only for given tables, multiple table names separated with ','` - CGenDaoBriefTablesEx = `generate models excluding given tables, multiple table names separated with ','` - CGenDaoBriefPrefix = `add prefix for all table of specified link/database tables` - CGenDaoBriefRemovePrefix = `remove specified prefix of the table, multiple prefix separated with ','` - CGenDaoBriefStdTime = `use time.Time from stdlib instead of gtime.Time for generated time/date fields of tables` - CGenDaoBriefWithTime = `add created time for auto produced go files` - CGenDaoBriefGJsonSupport = `use gJsonSupport to use *gjson.Json instead of string for generated json fields of tables` - CGenDaoBriefImportPrefix = `custom import prefix for generated go files` - CGenDaoBriefDaoPath = `directory path for storing generated dao files under path` - CGenDaoBriefDoPath = `directory path for storing generated do files under path` - CGenDaoBriefEntityPath = `directory path for storing generated entity files under path` - CGenDaoBriefOverwriteDao = `overwrite all dao files both inside/outside internal folder` - CGenDaoBriefModelFile = `custom file name for storing generated model content` - CGenDaoBriefModelFileForDao = `custom file name generating model for DAO operations like Where/Data. It's empty in default` - CGenDaoBriefDescriptionTag = `add comment to description tag for each field` - CGenDaoBriefNoJsonTag = `no json tag will be added for each field` - CGenDaoBriefNoModelComment = `no model comment will be added for each field` - CGenDaoBriefClear = `delete all generated go files that do not exist in database` - CGenDaoBriefTypeMapping = `custom local type mapping for generated struct attributes relevant to fields of table` - CGenDaoBriefGroup = ` + CGenDaoBriefPath = `directory path for generated files` + CGenDaoBriefLink = `database configuration, the same as the ORM configuration of GoFrame` + CGenDaoBriefTables = `generate models only for given tables, multiple table names separated with ','` + CGenDaoBriefTablesEx = `generate models excluding given tables, multiple table names separated with ','` + CGenDaoBriefPrefix = `add prefix for all table of specified link/database tables` + CGenDaoBriefRemovePrefix = `remove specified prefix of the table, multiple prefix separated with ','` + CGenDaoBriefRemoveFieldPrefix = `remove specified prefix of the field, multiple prefix separated with ','` + CGenDaoBriefStdTime = `use time.Time from stdlib instead of gtime.Time for generated time/date fields of tables` + CGenDaoBriefWithTime = `add created time for auto produced go files` + CGenDaoBriefGJsonSupport = `use gJsonSupport to use *gjson.Json instead of string for generated json fields of tables` + CGenDaoBriefImportPrefix = `custom import prefix for generated go files` + CGenDaoBriefDaoPath = `directory path for storing generated dao files under path` + CGenDaoBriefDoPath = `directory path for storing generated do files under path` + CGenDaoBriefEntityPath = `directory path for storing generated entity files under path` + CGenDaoBriefOverwriteDao = `overwrite all dao files both inside/outside internal folder` + CGenDaoBriefModelFile = `custom file name for storing generated model content` + CGenDaoBriefModelFileForDao = `custom file name generating model for DAO operations like Where/Data. It's empty in default` + CGenDaoBriefDescriptionTag = `add comment to description tag for each field` + CGenDaoBriefNoJsonTag = `no json tag will be added for each field` + CGenDaoBriefNoModelComment = `no model comment will be added for each field` + CGenDaoBriefClear = `delete all generated go files that do not exist in database` + CGenDaoBriefTypeMapping = `custom local type mapping for generated struct attributes relevant to fields of table` + CGenDaoBriefGroup = ` specifying the configuration group name of database for generated ORM instance, it's not necessary and the default value is "default" ` @@ -145,6 +146,7 @@ func init() { `CGenDaoBriefTablesEx`: CGenDaoBriefTablesEx, `CGenDaoBriefPrefix`: CGenDaoBriefPrefix, `CGenDaoBriefRemovePrefix`: CGenDaoBriefRemovePrefix, + `CGenDaoBriefRemoveFieldPrefix`: CGenDaoBriefRemoveFieldPrefix, `CGenDaoBriefStdTime`: CGenDaoBriefStdTime, `CGenDaoBriefWithTime`: CGenDaoBriefWithTime, `CGenDaoBriefDaoPath`: CGenDaoBriefDaoPath, @@ -180,6 +182,7 @@ type ( Group string `name:"group" short:"g" brief:"{CGenDaoBriefGroup}" d:"default"` Prefix string `name:"prefix" short:"f" brief:"{CGenDaoBriefPrefix}"` RemovePrefix string `name:"removePrefix" short:"r" brief:"{CGenDaoBriefRemovePrefix}"` + RemoveFieldPrefix string `name:"removeFieldPrefix" short:"fr" brief:"{CGenDaoBriefRemoveFieldPrefix}"` JsonCase string `name:"jsonCase" short:"j" brief:"{CGenDaoBriefJsonCase}" d:"CamelLower"` ImportPrefix string `name:"importPrefix" short:"i" brief:"{CGenDaoBriefImportPrefix}"` DaoPath string `name:"daoPath" short:"d" brief:"{CGenDaoBriefDaoPath}" d:"dao"` diff --git a/cmd/gf/internal/cmd/gendao/gendao_dao.go b/cmd/gf/internal/cmd/gendao/gendao_dao.go index de3bdd528f7..0b572405e0c 100644 --- a/cmd/gf/internal/cmd/gendao/gendao_dao.go +++ b/cmd/gf/internal/cmd/gendao/gendao_dao.go @@ -138,6 +138,7 @@ type generateDaoInternalInput struct { func generateDaoInternal(in generateDaoInternalInput) { path := filepath.FromSlash(gfile.Join(in.DirPathDaoInternal, in.FileName+".go")) + removeFieldPrefixArray := gstr.SplitAndTrim(in.RemoveFieldPrefix, ",") modelContent := gstr.ReplaceByMap( getTemplateFromPathOrDefault(in.TplDaoInternalPath, consts.TemplateGenDaoInternalContent), g.MapStrStr{ @@ -146,8 +147,8 @@ func generateDaoInternal(in generateDaoInternalInput) { tplVarGroupName: in.Group, tplVarTableNameCamelCase: in.TableNameCamelCase, tplVarTableNameCamelLowerCase: in.TableNameCamelLowerCase, - tplVarColumnDefine: gstr.Trim(generateColumnDefinitionForDao(in.FieldMap)), - tplVarColumnNames: gstr.Trim(generateColumnNamesForDao(in.FieldMap)), + tplVarColumnDefine: gstr.Trim(generateColumnDefinitionForDao(in.FieldMap, removeFieldPrefixArray)), + tplVarColumnNames: gstr.Trim(generateColumnNamesForDao(in.FieldMap, removeFieldPrefixArray)), }) modelContent = replaceDefaultVar(in.CGenDaoInternalInput, modelContent) if err := gfile.PutContents(path, strings.TrimSpace(modelContent)); err != nil { @@ -160,16 +161,23 @@ func generateDaoInternal(in generateDaoInternalInput) { // generateColumnNamesForDao generates and returns the column names assignment content of column struct // for specified table. -func generateColumnNamesForDao(fieldMap map[string]*gdb.TableField) string { +func generateColumnNamesForDao(fieldMap map[string]*gdb.TableField, removeFieldPrefixArray []string) string { var ( buffer = bytes.NewBuffer(nil) array = make([][]string, len(fieldMap)) names = sortFieldKeyForDao(fieldMap) ) + for index, name := range names { field := fieldMap[name] + + newFiledName := field.Name + for _, v := range removeFieldPrefixArray { + newFiledName = gstr.TrimLeftStr(newFiledName, v, 1) + } + array[index] = []string{ - " #" + gstr.CaseCamel(field.Name) + ":", + " #" + gstr.CaseCamel(newFiledName) + ":", fmt.Sprintf(` #"%s",`, field.Name), } } @@ -189,12 +197,13 @@ func generateColumnNamesForDao(fieldMap map[string]*gdb.TableField) string { } // generateColumnDefinitionForDao generates and returns the column names definition for specified table. -func generateColumnDefinitionForDao(fieldMap map[string]*gdb.TableField) string { +func generateColumnDefinitionForDao(fieldMap map[string]*gdb.TableField, removeFieldPrefixArray []string) string { var ( buffer = bytes.NewBuffer(nil) array = make([][]string, len(fieldMap)) names = sortFieldKeyForDao(fieldMap) ) + for index, name := range names { var ( field = fieldMap[name] @@ -203,8 +212,12 @@ func generateColumnDefinitionForDao(fieldMap map[string]*gdb.TableField) string "\r", " ", })) ) + newFiledName := field.Name + for _, v := range removeFieldPrefixArray { + newFiledName = gstr.TrimLeftStr(newFiledName, v, 1) + } array[index] = []string{ - " #" + gstr.CaseCamel(field.Name), + " #" + gstr.CaseCamel(newFiledName), " # " + "string", " #" + fmt.Sprintf(`// %s`, comment), } diff --git a/cmd/gf/internal/cmd/gendao/gendao_structure.go b/cmd/gf/internal/cmd/gendao/gendao_structure.go index 77d84b6624b..c4398c8c1e7 100644 --- a/cmd/gf/internal/cmd/gendao/gendao_structure.go +++ b/cmd/gf/internal/cmd/gendao/gendao_structure.go @@ -126,8 +126,13 @@ func generateStructFieldDefinition( tagKey = "`" descriptionTag = gstr.Replace(formatComment(field.Comment), `"`, `\"`) ) + removeFieldPrefixArray := gstr.SplitAndTrim(in.RemoveFieldPrefix, ",") + newFiledName := field.Name + for _, v := range removeFieldPrefixArray { + newFiledName = gstr.TrimLeftStr(newFiledName, v, 1) + } attrLines = []string{ - " #" + gstr.CaseCamel(field.Name), + " #" + gstr.CaseCamel(newFiledName), " #" + localTypeNameStr, } attrLines = append(attrLines, " #"+fmt.Sprintf(tagKey+`json:"%s"`, jsonTag)) diff --git a/cmd/gf/internal/cmd/genpbentity/genpbentity.go b/cmd/gf/internal/cmd/genpbentity/genpbentity.go index 83d9e32bd91..624c450c264 100644 --- a/cmd/gf/internal/cmd/genpbentity/genpbentity.go +++ b/cmd/gf/internal/cmd/genpbentity/genpbentity.go @@ -31,16 +31,17 @@ import ( type ( CGenPbEntity struct{} CGenPbEntityInput struct { - g.Meta `name:"pbentity" config:"{CGenPbEntityConfig}" brief:"{CGenPbEntityBrief}" eg:"{CGenPbEntityEg}" ad:"{CGenPbEntityAd}"` - Path string `name:"path" short:"p" brief:"{CGenPbEntityBriefPath}" d:"manifest/protobuf/pbentity"` - Package string `name:"package" short:"k" brief:"{CGenPbEntityBriefPackage}"` - Link string `name:"link" short:"l" brief:"{CGenPbEntityBriefLink}"` - Tables string `name:"tables" short:"t" brief:"{CGenPbEntityBriefTables}"` - Prefix string `name:"prefix" short:"f" brief:"{CGenPbEntityBriefPrefix}"` - RemovePrefix string `name:"removePrefix" short:"r" brief:"{CGenPbEntityBriefRemovePrefix}"` - NameCase string `name:"nameCase" short:"n" brief:"{CGenPbEntityBriefNameCase}" d:"Camel"` - JsonCase string `name:"jsonCase" short:"j" brief:"{CGenPbEntityBriefJsonCase}" d:"CamelLower"` - Option string `name:"option" short:"o" brief:"{CGenPbEntityBriefOption}"` + g.Meta `name:"pbentity" config:"{CGenPbEntityConfig}" brief:"{CGenPbEntityBrief}" eg:"{CGenPbEntityEg}" ad:"{CGenPbEntityAd}"` + Path string `name:"path" short:"p" brief:"{CGenPbEntityBriefPath}" d:"manifest/protobuf/pbentity"` + Package string `name:"package" short:"k" brief:"{CGenPbEntityBriefPackage}"` + Link string `name:"link" short:"l" brief:"{CGenPbEntityBriefLink}"` + Tables string `name:"tables" short:"t" brief:"{CGenPbEntityBriefTables}"` + Prefix string `name:"prefix" short:"f" brief:"{CGenPbEntityBriefPrefix}"` + RemovePrefix string `name:"removePrefix" short:"r" brief:"{CGenPbEntityBriefRemovePrefix}"` + RemoveFieldPrefix string `name:"removeFieldPrefix" short:"fr" brief:"{CGenPbEntityBriefRemoveFieldPrefix}"` + NameCase string `name:"nameCase" short:"n" brief:"{CGenPbEntityBriefNameCase}" d:"Camel"` + JsonCase string `name:"jsonCase" short:"j" brief:"{CGenPbEntityBriefJsonCase}" d:"CamelLower"` + Option string `name:"option" short:"o" brief:"{CGenPbEntityBriefOption}"` } CGenPbEntityOutput struct{} @@ -87,14 +88,15 @@ CONFIGURATION SUPPORT option java_package = "protobuf/demos"; option php_namespace = "protobuf/demos"; ` - CGenPbEntityBriefPath = `directory path for generated files storing` - CGenPbEntityBriefPackage = `package path for all entity proto files` - CGenPbEntityBriefLink = `database configuration, the same as the ORM configuration of GoFrame` - CGenPbEntityBriefTables = `generate models only for given tables, multiple table names separated with ','` - CGenPbEntityBriefPrefix = `add specified prefix for all entity names and entity proto files` - CGenPbEntityBriefRemovePrefix = `remove specified prefix of the table, multiple prefix separated with ','` - CGenPbEntityBriefOption = `extra protobuf options` - CGenPbEntityBriefGroup = ` + CGenPbEntityBriefPath = `directory path for generated files storing` + CGenPbEntityBriefPackage = `package path for all entity proto files` + CGenPbEntityBriefLink = `database configuration, the same as the ORM configuration of GoFrame` + CGenPbEntityBriefTables = `generate models only for given tables, multiple table names separated with ','` + CGenPbEntityBriefPrefix = `add specified prefix for all entity names and entity proto files` + CGenPbEntityBriefRemovePrefix = `remove specified prefix of the table, multiple prefix separated with ','` + CGenPbEntityBriefRemoveFieldPrefix = `remove specified prefix of the field, multiple prefix separated with ','` + CGenPbEntityBriefOption = `extra protobuf options` + CGenPbEntityBriefGroup = ` specifying the configuration group name of database for generated ORM instance, it's not necessary and the default value is "default" ` @@ -120,20 +122,21 @@ set it to "none" to ignore json tag generating. func init() { gtag.Sets(g.MapStrStr{ - `CGenPbEntityConfig`: CGenPbEntityConfig, - `CGenPbEntityBrief`: CGenPbEntityBrief, - `CGenPbEntityEg`: CGenPbEntityEg, - `CGenPbEntityAd`: CGenPbEntityAd, - `CGenPbEntityBriefPath`: CGenPbEntityBriefPath, - `CGenPbEntityBriefPackage`: CGenPbEntityBriefPackage, - `CGenPbEntityBriefLink`: CGenPbEntityBriefLink, - `CGenPbEntityBriefTables`: CGenPbEntityBriefTables, - `CGenPbEntityBriefPrefix`: CGenPbEntityBriefPrefix, - `CGenPbEntityBriefRemovePrefix`: CGenPbEntityBriefRemovePrefix, - `CGenPbEntityBriefGroup`: CGenPbEntityBriefGroup, - `CGenPbEntityBriefNameCase`: CGenPbEntityBriefNameCase, - `CGenPbEntityBriefJsonCase`: CGenPbEntityBriefJsonCase, - `CGenPbEntityBriefOption`: CGenPbEntityBriefOption, + `CGenPbEntityConfig`: CGenPbEntityConfig, + `CGenPbEntityBrief`: CGenPbEntityBrief, + `CGenPbEntityEg`: CGenPbEntityEg, + `CGenPbEntityAd`: CGenPbEntityAd, + `CGenPbEntityBriefPath`: CGenPbEntityBriefPath, + `CGenPbEntityBriefPackage`: CGenPbEntityBriefPackage, + `CGenPbEntityBriefLink`: CGenPbEntityBriefLink, + `CGenPbEntityBriefTables`: CGenPbEntityBriefTables, + `CGenPbEntityBriefPrefix`: CGenPbEntityBriefPrefix, + `CGenPbEntityBriefRemovePrefix`: CGenPbEntityBriefRemovePrefix, + `CGenPbEntityBriefRemoveFieldPrefix`: CGenPbEntityBriefRemoveFieldPrefix, + `CGenPbEntityBriefGroup`: CGenPbEntityBriefGroup, + `CGenPbEntityBriefNameCase`: CGenPbEntityBriefNameCase, + `CGenPbEntityBriefJsonCase`: CGenPbEntityBriefJsonCase, + `CGenPbEntityBriefOption`: CGenPbEntityBriefOption, }) } @@ -351,9 +354,16 @@ func generateMessageFieldForPbEntity(index int, field *gdb.TableField, in CGenPb jsonTagStr = " " + jsonTagStr } } + + removeFieldPrefixArray := gstr.SplitAndTrim(in.RemoveFieldPrefix, ",") + newFiledName := field.Name + for _, v := range removeFieldPrefixArray { + newFiledName = gstr.TrimLeftStr(newFiledName, v, 1) + } + return []string{ " #" + localTypeNameStr, - " #" + formatCase(field.Name, in.NameCase), + " #" + formatCase(newFiledName, in.NameCase), " #= " + gconv.String(index) + jsonTagStr + ";", " #" + fmt.Sprintf(`// %s`, comment), } From 7975e391f05328a63b497df0536f0e046ef18eb8 Mon Sep 17 00:00:00 2001 From: John Guo Date: Mon, 18 Dec 2023 20:59:09 +0800 Subject: [PATCH 29/52] Version/v2.6.0 (#3213) --- cmd/gf/go.mod | 14 +++++----- cmd/gf/internal/cmd/gendao/gendao.go | 2 +- .../internal/cmd/genpbentity/genpbentity.go | 2 +- contrib/config/apollo/go.mod | 2 +- contrib/config/consul/go.mod | 2 +- contrib/config/kubecm/go.mod | 2 +- contrib/config/nacos/go.mod | 2 +- contrib/config/polaris/go.mod | 2 +- contrib/drivers/clickhouse/go.mod | 2 +- contrib/drivers/dm/go.mod | 2 +- contrib/drivers/mssql/go.mod | 2 +- contrib/drivers/mysql/go.mod | 2 +- contrib/drivers/oracle/go.mod | 2 +- contrib/drivers/pgsql/go.mod | 2 +- contrib/drivers/sqlite/go.mod | 2 +- contrib/drivers/sqlitecgo/go.mod | 2 +- contrib/nosql/redis/go.mod | 2 +- contrib/registry/etcd/go.mod | 2 +- contrib/registry/file/go.mod | 2 +- contrib/registry/nacos/go.mod | 2 +- contrib/registry/polaris/go.mod | 2 +- contrib/registry/zookeeper/go.mod | 2 +- contrib/rpc/grpcx/go.mod | 4 +-- contrib/sdk/httpclient/go.mod | 2 +- contrib/trace/jaeger/go.mod | 2 +- contrib/trace/otlpgrpc/go.mod | 2 +- contrib/trace/otlphttp/go.mod | 2 +- example/go.mod | 28 +++++++++---------- version.go | 2 +- 29 files changed, 49 insertions(+), 49 deletions(-) diff --git a/cmd/gf/go.mod b/cmd/gf/go.mod index 9a9faae1fe7..3f7bcff4009 100644 --- a/cmd/gf/go.mod +++ b/cmd/gf/go.mod @@ -3,13 +3,13 @@ module github.com/gogf/gf/cmd/gf/v2 go 1.18 require ( - github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.6.0-beta - github.com/gogf/gf/contrib/drivers/mssql/v2 v2.6.0-beta - github.com/gogf/gf/contrib/drivers/mysql/v2 v2.6.0-beta - github.com/gogf/gf/contrib/drivers/oracle/v2 v2.6.0-beta - github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.6.0-beta - github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.6.0-beta - github.com/gogf/gf/v2 v2.6.0-beta + github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.6.0 + github.com/gogf/gf/contrib/drivers/mssql/v2 v2.6.0 + github.com/gogf/gf/contrib/drivers/mysql/v2 v2.6.0 + github.com/gogf/gf/contrib/drivers/oracle/v2 v2.6.0 + github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.6.0 + github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.6.0 + github.com/gogf/gf/v2 v2.6.0 github.com/gogf/selfupdate v0.0.0-20231215043001-5c48c528462f github.com/olekukonko/tablewriter v0.0.5 golang.org/x/mod v0.9.0 diff --git a/cmd/gf/internal/cmd/gendao/gendao.go b/cmd/gf/internal/cmd/gendao/gendao.go index 37f9ac551f3..765c63a441b 100644 --- a/cmd/gf/internal/cmd/gendao/gendao.go +++ b/cmd/gf/internal/cmd/gendao/gendao.go @@ -182,7 +182,7 @@ type ( Group string `name:"group" short:"g" brief:"{CGenDaoBriefGroup}" d:"default"` Prefix string `name:"prefix" short:"f" brief:"{CGenDaoBriefPrefix}"` RemovePrefix string `name:"removePrefix" short:"r" brief:"{CGenDaoBriefRemovePrefix}"` - RemoveFieldPrefix string `name:"removeFieldPrefix" short:"fr" brief:"{CGenDaoBriefRemoveFieldPrefix}"` + RemoveFieldPrefix string `name:"removeFieldPrefix" short:"rf" brief:"{CGenDaoBriefRemoveFieldPrefix}"` JsonCase string `name:"jsonCase" short:"j" brief:"{CGenDaoBriefJsonCase}" d:"CamelLower"` ImportPrefix string `name:"importPrefix" short:"i" brief:"{CGenDaoBriefImportPrefix}"` DaoPath string `name:"daoPath" short:"d" brief:"{CGenDaoBriefDaoPath}" d:"dao"` diff --git a/cmd/gf/internal/cmd/genpbentity/genpbentity.go b/cmd/gf/internal/cmd/genpbentity/genpbentity.go index 624c450c264..055d241b8bf 100644 --- a/cmd/gf/internal/cmd/genpbentity/genpbentity.go +++ b/cmd/gf/internal/cmd/genpbentity/genpbentity.go @@ -38,7 +38,7 @@ type ( Tables string `name:"tables" short:"t" brief:"{CGenPbEntityBriefTables}"` Prefix string `name:"prefix" short:"f" brief:"{CGenPbEntityBriefPrefix}"` RemovePrefix string `name:"removePrefix" short:"r" brief:"{CGenPbEntityBriefRemovePrefix}"` - RemoveFieldPrefix string `name:"removeFieldPrefix" short:"fr" brief:"{CGenPbEntityBriefRemoveFieldPrefix}"` + RemoveFieldPrefix string `name:"removeFieldPrefix" short:"rf" brief:"{CGenPbEntityBriefRemoveFieldPrefix}"` NameCase string `name:"nameCase" short:"n" brief:"{CGenPbEntityBriefNameCase}" d:"Camel"` JsonCase string `name:"jsonCase" short:"j" brief:"{CGenPbEntityBriefJsonCase}" d:"CamelLower"` Option string `name:"option" short:"o" brief:"{CGenPbEntityBriefOption}"` diff --git a/contrib/config/apollo/go.mod b/contrib/config/apollo/go.mod index 1c2171cdb1e..4aa84d471a8 100644 --- a/contrib/config/apollo/go.mod +++ b/contrib/config/apollo/go.mod @@ -4,7 +4,7 @@ go 1.18 require ( github.com/apolloconfig/agollo/v4 v4.3.1 - github.com/gogf/gf/v2 v2.6.0-beta + github.com/gogf/gf/v2 v2.6.0 ) require ( diff --git a/contrib/config/consul/go.mod b/contrib/config/consul/go.mod index 907314f91a3..0c7dff58cbc 100644 --- a/contrib/config/consul/go.mod +++ b/contrib/config/consul/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/consul/v2 go 1.19 require ( - github.com/gogf/gf/v2 v2.6.0-beta + github.com/gogf/gf/v2 v2.6.0 github.com/hashicorp/consul/api v1.24.0 github.com/hashicorp/go-cleanhttp v0.5.2 ) diff --git a/contrib/config/kubecm/go.mod b/contrib/config/kubecm/go.mod index cd7162dfc6f..fa6d4e84ef2 100644 --- a/contrib/config/kubecm/go.mod +++ b/contrib/config/kubecm/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/kubecm/v2 go 1.19 require ( - github.com/gogf/gf/v2 v2.6.0-beta + github.com/gogf/gf/v2 v2.6.0 k8s.io/api v0.27.4 k8s.io/apimachinery v0.27.4 k8s.io/client-go v0.27.4 diff --git a/contrib/config/nacos/go.mod b/contrib/config/nacos/go.mod index bbc4a44612a..e614e98b83d 100644 --- a/contrib/config/nacos/go.mod +++ b/contrib/config/nacos/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/nacos/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.6.0-beta + github.com/gogf/gf/v2 v2.6.0 github.com/nacos-group/nacos-sdk-go v1.1.4 ) diff --git a/contrib/config/polaris/go.mod b/contrib/config/polaris/go.mod index 00b065558bb..2242775ac0d 100644 --- a/contrib/config/polaris/go.mod +++ b/contrib/config/polaris/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/polaris/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.6.0-beta + github.com/gogf/gf/v2 v2.6.0 github.com/polarismesh/polaris-go v1.5.5 ) diff --git a/contrib/drivers/clickhouse/go.mod b/contrib/drivers/clickhouse/go.mod index ac63af72925..c66bfd3d005 100644 --- a/contrib/drivers/clickhouse/go.mod +++ b/contrib/drivers/clickhouse/go.mod @@ -4,7 +4,7 @@ go 1.18 require ( github.com/ClickHouse/clickhouse-go/v2 v2.0.15 - github.com/gogf/gf/v2 v2.6.0-beta + github.com/gogf/gf/v2 v2.6.0 github.com/google/uuid v1.3.0 github.com/shopspring/decimal v1.3.1 ) diff --git a/contrib/drivers/dm/go.mod b/contrib/drivers/dm/go.mod index 1b87b9593b2..6f9ecf5c963 100644 --- a/contrib/drivers/dm/go.mod +++ b/contrib/drivers/dm/go.mod @@ -6,7 +6,7 @@ replace github.com/gogf/gf/v2 => ../../../ require ( gitee.com/chunanyong/dm v1.8.12 - github.com/gogf/gf/v2 v2.6.0-beta + github.com/gogf/gf/v2 v2.6.0 ) require ( diff --git a/contrib/drivers/mssql/go.mod b/contrib/drivers/mssql/go.mod index f910c220e65..4252772b974 100644 --- a/contrib/drivers/mssql/go.mod +++ b/contrib/drivers/mssql/go.mod @@ -4,7 +4,7 @@ go 1.18 require ( github.com/denisenkom/go-mssqldb v0.12.3 - github.com/gogf/gf/v2 v2.6.0-beta + github.com/gogf/gf/v2 v2.6.0 ) require ( diff --git a/contrib/drivers/mysql/go.mod b/contrib/drivers/mysql/go.mod index 618c6417c73..22c847fc626 100644 --- a/contrib/drivers/mysql/go.mod +++ b/contrib/drivers/mysql/go.mod @@ -4,7 +4,7 @@ go 1.18 require ( github.com/go-sql-driver/mysql v1.7.1 - github.com/gogf/gf/v2 v2.6.0-beta + github.com/gogf/gf/v2 v2.6.0 ) require ( diff --git a/contrib/drivers/oracle/go.mod b/contrib/drivers/oracle/go.mod index 1dad9a248ab..1498db14d1a 100644 --- a/contrib/drivers/oracle/go.mod +++ b/contrib/drivers/oracle/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/drivers/oracle/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.6.0-beta + github.com/gogf/gf/v2 v2.6.0 github.com/sijms/go-ora/v2 v2.7.10 ) diff --git a/contrib/drivers/pgsql/go.mod b/contrib/drivers/pgsql/go.mod index b6f82b5e4e5..192908b3da2 100644 --- a/contrib/drivers/pgsql/go.mod +++ b/contrib/drivers/pgsql/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/drivers/pgsql/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.6.0-beta + github.com/gogf/gf/v2 v2.6.0 github.com/lib/pq v1.10.9 ) diff --git a/contrib/drivers/sqlite/go.mod b/contrib/drivers/sqlite/go.mod index 840fa0764b0..82ecdaaefee 100644 --- a/contrib/drivers/sqlite/go.mod +++ b/contrib/drivers/sqlite/go.mod @@ -4,7 +4,7 @@ go 1.18 require ( github.com/glebarez/go-sqlite v1.21.2 - github.com/gogf/gf/v2 v2.6.0-beta + github.com/gogf/gf/v2 v2.6.0 ) require ( diff --git a/contrib/drivers/sqlitecgo/go.mod b/contrib/drivers/sqlitecgo/go.mod index 392f7e381de..599f16a8d8c 100644 --- a/contrib/drivers/sqlitecgo/go.mod +++ b/contrib/drivers/sqlitecgo/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/drivers/sqlitecgo/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.6.0-beta + github.com/gogf/gf/v2 v2.6.0 github.com/mattn/go-sqlite3 v1.14.17 ) diff --git a/contrib/nosql/redis/go.mod b/contrib/nosql/redis/go.mod index f7029eb4e2f..ba1b467545c 100644 --- a/contrib/nosql/redis/go.mod +++ b/contrib/nosql/redis/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/nosql/redis/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.6.0-beta + github.com/gogf/gf/v2 v2.6.0 github.com/redis/go-redis/v9 v9.2.1 go.opentelemetry.io/otel v1.14.0 go.opentelemetry.io/otel/trace v1.14.0 diff --git a/contrib/registry/etcd/go.mod b/contrib/registry/etcd/go.mod index a036cd9adba..8967d52106f 100644 --- a/contrib/registry/etcd/go.mod +++ b/contrib/registry/etcd/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/registry/etcd/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.6.0-beta + github.com/gogf/gf/v2 v2.6.0 go.etcd.io/etcd/client/v3 v3.5.7 ) diff --git a/contrib/registry/file/go.mod b/contrib/registry/file/go.mod index 1f950ab51bc..0b879e3ba9f 100644 --- a/contrib/registry/file/go.mod +++ b/contrib/registry/file/go.mod @@ -2,7 +2,7 @@ module github.com/gogf/gf/contrib/registry/file/v2 go 1.18 -require github.com/gogf/gf/v2 v2.6.0-beta +require github.com/gogf/gf/v2 v2.6.0 require ( github.com/BurntSushi/toml v1.2.0 // indirect diff --git a/contrib/registry/nacos/go.mod b/contrib/registry/nacos/go.mod index 0055ac90c68..b61a463a2f3 100644 --- a/contrib/registry/nacos/go.mod +++ b/contrib/registry/nacos/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/registry/nacos/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.6.0-beta + github.com/gogf/gf/v2 v2.6.0 github.com/joy999/nacos-sdk-go v0.0.0-20231120071639-10a34b3e7288 ) diff --git a/contrib/registry/polaris/go.mod b/contrib/registry/polaris/go.mod index cbc70976e9a..55b82a1c092 100644 --- a/contrib/registry/polaris/go.mod +++ b/contrib/registry/polaris/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/registry/polaris/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.6.0-beta + github.com/gogf/gf/v2 v2.6.0 github.com/polarismesh/polaris-go v1.5.5 ) diff --git a/contrib/registry/zookeeper/go.mod b/contrib/registry/zookeeper/go.mod index fad7faa5ab4..c9cc2c6141a 100644 --- a/contrib/registry/zookeeper/go.mod +++ b/contrib/registry/zookeeper/go.mod @@ -4,7 +4,7 @@ go 1.18 require ( github.com/go-zookeeper/zk v1.0.3 - github.com/gogf/gf/v2 v2.6.0-beta + github.com/gogf/gf/v2 v2.6.0 golang.org/x/sync v0.4.0 ) diff --git a/contrib/rpc/grpcx/go.mod b/contrib/rpc/grpcx/go.mod index 593fe01987d..aced4f90f4f 100644 --- a/contrib/rpc/grpcx/go.mod +++ b/contrib/rpc/grpcx/go.mod @@ -3,8 +3,8 @@ module github.com/gogf/gf/contrib/rpc/grpcx/v2 go 1.18 require ( - github.com/gogf/gf/contrib/registry/file/v2 v2.6.0-beta - github.com/gogf/gf/v2 v2.6.0-beta + github.com/gogf/gf/contrib/registry/file/v2 v2.6.0 + github.com/gogf/gf/v2 v2.6.0 go.opentelemetry.io/otel v1.14.0 go.opentelemetry.io/otel/trace v1.14.0 google.golang.org/grpc v1.57.2 diff --git a/contrib/sdk/httpclient/go.mod b/contrib/sdk/httpclient/go.mod index 5de6891c484..9d558be432c 100644 --- a/contrib/sdk/httpclient/go.mod +++ b/contrib/sdk/httpclient/go.mod @@ -2,7 +2,7 @@ module github.com/gogf/gf/contrib/sdk/httpclient/v2 go 1.18 -require github.com/gogf/gf/v2 v2.6.0-beta +require github.com/gogf/gf/v2 v2.6.0 require ( github.com/BurntSushi/toml v1.2.0 // indirect diff --git a/contrib/trace/jaeger/go.mod b/contrib/trace/jaeger/go.mod index 0de613f6466..582db1e2552 100644 --- a/contrib/trace/jaeger/go.mod +++ b/contrib/trace/jaeger/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/trace/jaeger/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.6.0-beta + github.com/gogf/gf/v2 v2.6.0 go.opentelemetry.io/otel v1.14.0 go.opentelemetry.io/otel/exporters/jaeger v1.14.0 go.opentelemetry.io/otel/sdk v1.14.0 diff --git a/contrib/trace/otlpgrpc/go.mod b/contrib/trace/otlpgrpc/go.mod index 7962c8a252a..407a1619259 100644 --- a/contrib/trace/otlpgrpc/go.mod +++ b/contrib/trace/otlpgrpc/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/trace/otlpgrpc/v2 go 1.20 require ( - github.com/gogf/gf/v2 v2.6.0-beta + github.com/gogf/gf/v2 v2.6.0 go.opentelemetry.io/otel v1.19.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.19.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.19.0 diff --git a/contrib/trace/otlphttp/go.mod b/contrib/trace/otlphttp/go.mod index 3c110331d99..d26e1ff5889 100644 --- a/contrib/trace/otlphttp/go.mod +++ b/contrib/trace/otlphttp/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/trace/otlphttp/v2 go 1.20 require ( - github.com/gogf/gf/v2 v2.6.0-beta + github.com/gogf/gf/v2 v2.6.0 go.opentelemetry.io/otel v1.19.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.19.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.19.0 diff --git a/example/go.mod b/example/go.mod index 26a4c0eff2b..dc200d27e07 100644 --- a/example/go.mod +++ b/example/go.mod @@ -3,21 +3,21 @@ module github.com/gogf/gf/example go 1.20 require ( - github.com/gogf/gf/contrib/config/apollo/v2 v2.6.0-beta - github.com/gogf/gf/contrib/config/consul/v2 v2.6.0-beta - github.com/gogf/gf/contrib/config/kubecm/v2 v2.6.0-beta - github.com/gogf/gf/contrib/config/nacos/v2 v2.6.0-beta - github.com/gogf/gf/contrib/config/polaris/v2 v2.6.0-beta - github.com/gogf/gf/contrib/drivers/mysql/v2 v2.6.0-beta - github.com/gogf/gf/contrib/nosql/redis/v2 v2.6.0-beta - github.com/gogf/gf/contrib/registry/etcd/v2 v2.6.0-beta - github.com/gogf/gf/contrib/registry/file/v2 v2.6.0-beta + github.com/gogf/gf/contrib/config/apollo/v2 v2.6.0 + github.com/gogf/gf/contrib/config/consul/v2 v2.6.0 + github.com/gogf/gf/contrib/config/kubecm/v2 v2.6.0 + github.com/gogf/gf/contrib/config/nacos/v2 v2.6.0 + github.com/gogf/gf/contrib/config/polaris/v2 v2.6.0 + github.com/gogf/gf/contrib/drivers/mysql/v2 v2.6.0 + github.com/gogf/gf/contrib/nosql/redis/v2 v2.6.0 + github.com/gogf/gf/contrib/registry/etcd/v2 v2.6.0 + github.com/gogf/gf/contrib/registry/file/v2 v2.6.0 github.com/gogf/gf/contrib/registry/nacos/v2 v2.5.6 - github.com/gogf/gf/contrib/registry/polaris/v2 v2.6.0-beta - github.com/gogf/gf/contrib/rpc/grpcx/v2 v2.6.0-beta - github.com/gogf/gf/contrib/trace/otlpgrpc/v2 v2.6.0-beta - github.com/gogf/gf/contrib/trace/otlphttp/v2 v2.6.0-beta - github.com/gogf/gf/v2 v2.6.0-beta + github.com/gogf/gf/contrib/registry/polaris/v2 v2.6.0 + github.com/gogf/gf/contrib/rpc/grpcx/v2 v2.6.0 + github.com/gogf/gf/contrib/trace/otlpgrpc/v2 v2.6.0 + github.com/gogf/gf/contrib/trace/otlphttp/v2 v2.6.0 + github.com/gogf/gf/v2 v2.6.0 github.com/hashicorp/consul/api v1.24.0 github.com/hashicorp/go-cleanhttp v0.5.2 github.com/nacos-group/nacos-sdk-go v1.1.4 diff --git a/version.go b/version.go index 12825ec9cef..2f9e499ba7c 100644 --- a/version.go +++ b/version.go @@ -2,5 +2,5 @@ package gf const ( // VERSION is the current GoFrame version. - VERSION = "v2.6.0-beta" + VERSION = "v2.6.0" ) From 645c5ff5b5819f124386891c56b3bfa7f2492f91 Mon Sep 17 00:00:00 2001 From: John Guo Date: Tue, 19 Dec 2023 21:58:12 +0800 Subject: [PATCH 30/52] fix issue #3218 #3204 (#3220) --- contrib/drivers/mysql/mysql_issue_test.go | 95 +++++++++++++++++++- contrib/drivers/mysql/testdata/issue3218.sql | 14 +++ database/gdb/gdb_core_structure.go | 2 +- database/gdb/gdb_func.go | 14 ++- util/gconv/gconv_interface.go | 5 ++ util/gconv/gconv_map.go | 13 ++- 6 files changed, 134 insertions(+), 9 deletions(-) create mode 100644 contrib/drivers/mysql/testdata/issue3218.sql diff --git a/contrib/drivers/mysql/mysql_issue_test.go b/contrib/drivers/mysql/mysql_issue_test.go index a57ba1ea1bf..1f2e0d5f4ee 100644 --- a/contrib/drivers/mysql/mysql_issue_test.go +++ b/contrib/drivers/mysql/mysql_issue_test.go @@ -7,6 +7,7 @@ package mysql_test import ( + "context" "fmt" "testing" "time" @@ -886,7 +887,8 @@ func Test_Issue3086(t *testing.T) { func Test_Issue3204(t *testing.T) { table := createInitTable() defer dropTable(table) - db.SetDebug(true) + + // where gtest.C(t, func(t *gtest.T) { type User struct { g.Meta `orm:"do:true"` @@ -905,4 +907,95 @@ func Test_Issue3204(t *testing.T) { t.Assert(len(all), 1) t.Assert(all[0]["id"], 2) }) + // data + gtest.C(t, func(t *gtest.T) { + type User struct { + g.Meta `orm:"do:true"` + Id interface{} `orm:"id,omitempty"` + Passport interface{} `orm:"passport,omitempty"` + Password interface{} `orm:"password,omitempty"` + Nickname interface{} `orm:"nickname,omitempty"` + CreateTime interface{} `orm:"create_time,omitempty"` + } + var ( + err error + sqlArray []string + insertId int64 + data = User{ + Id: 20, + Passport: "passport_20", + Password: "", + } + ) + sqlArray, err = gdb.CatchSQL(ctx, func(ctx context.Context) error { + insertId, err = db.Ctx(ctx).Model(table).Data(data).InsertAndGetId() + return err + }) + t.AssertNil(err) + t.Assert(insertId, 20) + t.Assert( + gstr.Contains(sqlArray[len(sqlArray)-1], "(`id`,`passport`) VALUES(20,'passport_20')"), + true, + ) + }) + // update data + gtest.C(t, func(t *gtest.T) { + type User struct { + g.Meta `orm:"do:true"` + Id interface{} `orm:"id,omitempty"` + Passport interface{} `orm:"passport,omitempty"` + Password interface{} `orm:"password,omitempty"` + Nickname interface{} `orm:"nickname,omitempty"` + CreateTime interface{} `orm:"create_time,omitempty"` + } + var ( + err error + sqlArray []string + data = User{ + Passport: "passport_1", + Password: "", + Nickname: "", + } + ) + sqlArray, err = gdb.CatchSQL(ctx, func(ctx context.Context) error { + _, err = db.Ctx(ctx).Model(table).Data(data).WherePri(1).Update() + return err + }) + t.AssertNil(err) + t.Assert( + gstr.Contains(sqlArray[len(sqlArray)-1], "SET `passport`='passport_1' WHERE `id`=1"), + true, + ) + }) +} + +// https://github.com/gogf/gf/issues/3218 +func Test_Issue3218(t *testing.T) { + table := "issue3218_sys_config" + array := gstr.SplitAndTrim(gtest.DataContent(`issue3218.sql`), ";") + for _, v := range array { + if _, err := db.Exec(ctx, v); err != nil { + gtest.Error(err) + } + } + defer dropTable(table) + gtest.C(t, func(t *gtest.T) { + type SysConfigInfo struct { + Name string `json:"name"` + Value map[string]string `json:"value"` + } + var configData *SysConfigInfo + err := db.Model(table).Scan(&configData) + t.AssertNil(err) + t.Assert(configData, &SysConfigInfo{ + Name: "site", + Value: map[string]string{ + "fixed_page": "", + "site_name": "22", + "version": "22", + "banned_ip": "22", + "filings": "2222", + }, + }) + }) } diff --git a/contrib/drivers/mysql/testdata/issue3218.sql b/contrib/drivers/mysql/testdata/issue3218.sql new file mode 100644 index 00000000000..93b5f9dacc9 --- /dev/null +++ b/contrib/drivers/mysql/testdata/issue3218.sql @@ -0,0 +1,14 @@ +CREATE TABLE `issue3218_sys_config` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '配置名称', + `value` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '配置值', + `created_at` timestamp NULL DEFAULT NULL COMMENT '创建时间', + `updated_at` timestamp NULL DEFAULT NULL COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `name`(`name`(191)) USING BTREE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci; + +-- ---------------------------- +-- Records of sys_config +-- ---------------------------- +INSERT INTO `issue3218_sys_config` VALUES (49, 'site', '{\"banned_ip\":\"22\",\"filings\":\"2222\",\"fixed_page\":\"\",\"site_name\":\"22\",\"version\":\"22\"}', '2023-12-19 14:08:25', '2023-12-19 14:08:25'); \ No newline at end of file diff --git a/database/gdb/gdb_core_structure.go b/database/gdb/gdb_core_structure.go index bcfa5abb19c..161825094d8 100644 --- a/database/gdb/gdb_core_structure.go +++ b/database/gdb/gdb_core_structure.go @@ -60,7 +60,7 @@ func (c *Core) GetFieldType(ctx context.Context, fieldName, table, schema string func (c *Core) ConvertDataForRecord(ctx context.Context, value interface{}, table string) (map[string]interface{}, error) { var ( err error - data = MapOrStructToMapDeep(value, false) + data = MapOrStructToMapDeep(value, true) ) for fieldName, fieldValue := range data { data[fieldName], err = c.db.ConvertValueForField( diff --git a/database/gdb/gdb_func.go b/database/gdb/gdb_func.go index 3fbf1e7de5f..4d2f9b41f91 100644 --- a/database/gdb/gdb_func.go +++ b/database/gdb/gdb_func.go @@ -96,7 +96,9 @@ func DBFromCtx(ctx context.Context) DB { return nil } -// ToSQL formats and returns the last one of sql statements in given closure function without truly executing it. +// ToSQL formats and returns the last one of sql statements in given closure function +// WITHOUT TRULY EXECUTING IT. +// Be caution that, all the following sql statements should use the context object passing by function `f`. func ToSQL(ctx context.Context, f func(ctx context.Context) error) (sql string, err error) { var manager = &CatchSQLManager{ SQLArray: garray.NewStrArray(), @@ -108,7 +110,8 @@ func ToSQL(ctx context.Context, f func(ctx context.Context) error) (sql string, return } -// CatchSQL catches and returns all sql statements that are executed in given closure function. +// CatchSQL catches and returns all sql statements that are EXECUTED in given closure function. +// Be caution that, all the following sql statements should use the context object passing by function `f`. func CatchSQL(ctx context.Context, f func(ctx context.Context) error) (sqlArray []string, err error) { var manager = &CatchSQLManager{ SQLArray: garray.NewStrArray(), @@ -210,12 +213,15 @@ func GetInsertOperationByOption(option InsertOption) string { } func anyValueToMapBeforeToRecord(value interface{}) map[string]interface{} { - return gconv.Map(value, gconv.MapOption{Tags: structTagPriority}) + return gconv.Map(value, gconv.MapOption{ + Tags: structTagPriority, + OmitEmpty: true, // To be compatible with old version from v2.6.0. + }) } // DaToMapDeep is deprecated, use MapOrStructToMapDeep instead. func DaToMapDeep(value interface{}) map[string]interface{} { - return MapOrStructToMapDeep(value, false) + return MapOrStructToMapDeep(value, true) } // MapOrStructToMapDeep converts `value` to map type recursively(if attribute struct is embedded). diff --git a/util/gconv/gconv_interface.go b/util/gconv/gconv_interface.go index 9440e978f9a..8ba7361bc2e 100644 --- a/util/gconv/gconv_interface.go +++ b/util/gconv/gconv_interface.go @@ -8,6 +8,11 @@ package gconv import "github.com/gogf/gf/v2/os/gtime" +// iVal is used for type assert api for String(). +type iVal interface { + Val() interface{} +} + // iString is used for type assert api for String(). type iString interface { String() string diff --git a/util/gconv/gconv_map.go b/util/gconv/gconv_map.go index 7627d684077..7d52fcda3e2 100644 --- a/util/gconv/gconv_map.go +++ b/util/gconv/gconv_map.go @@ -29,7 +29,7 @@ type MapOption struct { // a map[string]interface{} type variable. Deep bool - // OmitEmpty ignores the attributes that has json omitempty tag. + // OmitEmpty ignores the attributes that has json `omitempty` tag. OmitEmpty bool // Tags specifies the converted map key name by struct tag name. @@ -64,8 +64,15 @@ func doMapConvert(value interface{}, recursive recursiveType, mustMapReturn bool if value == nil { return nil } - var usedOption = getUsedMapOption(option...) - newTags := StructTagPriority + // It redirects to its underlying value if it has implemented interface iVal. + if v, ok := value.(iVal); ok { + value = v.Val() + } + + var ( + usedOption = getUsedMapOption(option...) + newTags = StructTagPriority + ) switch len(usedOption.Tags) { case 0: // No need handling. From d08e3ef83884fd51f476cc8ddc4e2447b31577d4 Mon Sep 17 00:00:00 2001 From: glennliao Date: Wed, 20 Dec 2023 20:21:15 +0800 Subject: [PATCH 31/52] fix: #2689 change sessionId in cookie (#3203) --- net/ghttp/ghttp_server_handler.go | 18 +++- .../ghttp_z_unit_feature_session_test.go | 89 +++++++++++++++++++ 2 files changed, 103 insertions(+), 4 deletions(-) diff --git a/net/ghttp/ghttp_server_handler.go b/net/ghttp/ghttp_server_handler.go index 09c66be3420..da4863032a9 100644 --- a/net/ghttp/ghttp_server_handler.go +++ b/net/ghttp/ghttp_server_handler.go @@ -43,6 +43,9 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Create a new request object. request := newRequest(s, r, w) + // Get sessionId before user handler + sessionId := request.GetSessionId() + defer func() { request.LeaveTime = gtime.TimestampMilli() // error log handling. @@ -176,10 +179,17 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Automatically set the session id to cookie // if it creates a new session id in this request // and SessionCookieOutput is enabled. - if s.config.SessionCookieOutput && - request.Session.IsDirty() && - request.Session.MustId() != request.GetSessionId() { - request.Cookie.SetSessionId(request.Session.MustId()) + if s.config.SessionCookieOutput && request.Session.IsDirty() { + // Can change by r.Session.SetId("") before init session + // Can change by r.Cookie.SetSessionId("") + sidFromSession, sidFromRequest := request.Session.MustId(), request.GetSessionId() + if sidFromSession != sidFromRequest { + if sidFromSession != sessionId { + request.Cookie.SetSessionId(sidFromSession) + } else { + request.Cookie.SetSessionId(sidFromRequest) + } + } } // Output the cookie content to the client. request.Cookie.Flush() diff --git a/net/ghttp/ghttp_z_unit_feature_session_test.go b/net/ghttp/ghttp_z_unit_feature_session_test.go index 7bb9514a4be..2f4b36dd5a4 100644 --- a/net/ghttp/ghttp_z_unit_feature_session_test.go +++ b/net/ghttp/ghttp_z_unit_feature_session_test.go @@ -189,3 +189,92 @@ func Test_Session_Custom_Id(t *testing.T) { t.Assert(client.GetContent(ctx, "/value"), value) }) } + +func Test_Session_New_Id(t *testing.T) { + var ( + sessionId = "1234567890" + newSessionId = "0987654321" + newSessionId2 = "abcdefghij" + key = "key" + value = "value" + s = g.Server(guid.S()) + ) + s.BindHandler("/id", func(r *ghttp.Request) { + if err := r.Session.SetId(sessionId); err != nil { + r.Response.WriteExit(err.Error()) + } + if err := r.Session.Set(key, value); err != nil { + r.Response.WriteExit(err.Error()) + } + r.Response.WriteExit(r.Session.Id()) + }) + + s.BindHandler("/newIdBySession", func(r *ghttp.Request) { + // Use before session init + if err := r.Session.SetId(newSessionId); err != nil { + r.Response.WriteExit(err.Error()) + } + if err := r.Session.Set(key, value); err != nil { + r.Response.WriteExit(err.Error()) + } + r.Response.WriteExit(r.Session.Id()) + }) + + s.BindHandler("/newIdByCookie", func(r *ghttp.Request) { + if err := r.Session.Remove("someKey"); err != nil { + r.Response.WriteExit(err.Error()) + } + + r.Cookie.SetSessionId(newSessionId2) + //r.Response.WriteExit(r.Session.Id()) // only change in cookie + + r.Response.WriteExit(newSessionId2) + }) + + s.BindHandler("/value", func(r *ghttp.Request) { + r.Response.WriteExit(r.Session.Get(key)) + }) + s.SetDumpRouterMap(false) + s.Start() + defer s.Shutdown() + + time.Sleep(100 * time.Millisecond) + + gtest.C(t, func(t *gtest.T) { + client := g.Client() + client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", s.GetListenedPort())) + r, err := client.Get(ctx, "/id") + t.AssertNil(err) + defer r.Close() + t.Assert(r.ReadAllString(), sessionId) + t.Assert(r.GetCookie(s.GetSessionIdName()), sessionId) + }) + gtest.C(t, func(t *gtest.T) { + client := g.Client() + client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", s.GetListenedPort())) + client.SetHeader(s.GetSessionIdName(), sessionId) + t.Assert(client.GetContent(ctx, "/value"), value) + }) + + gtest.C(t, func(t *gtest.T) { + client := g.Client() + client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", s.GetListenedPort())) + client.SetHeader(s.GetSessionIdName(), sessionId) + r, err := client.Get(ctx, "/newIdBySession") + t.AssertNil(err) + defer r.Close() + t.Assert(r.ReadAllString(), newSessionId) + t.Assert(r.GetCookie(s.GetSessionIdName()), newSessionId) + }) + + gtest.C(t, func(t *gtest.T) { + client := g.Client() + client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", s.GetListenedPort())) + r, err := client.Get(ctx, "/newIdByCookie") + client.SetHeader(s.GetSessionIdName(), sessionId) + t.AssertNil(err) + defer r.Close() + t.Assert(r.ReadAllString(), newSessionId2) + t.Assert(r.GetCookie(s.GetSessionIdName()), newSessionId2) + }) +} From 7f9467d1f87652b9946939a453549dd866f357af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B5=B7=E4=BA=AE?= <739476267@qq.com> Date: Wed, 20 Dec 2023 20:25:23 +0800 Subject: [PATCH 32/52] fix: #2938 (#3178) --- example/httpserver/upload_file/main.go | 44 +++++++++++++++++++ net/ghttp/ghttp_request_param.go | 2 - net/ghttp/ghttp_z_unit_feature_config_test.go | 8 +++- 3 files changed, 50 insertions(+), 4 deletions(-) create mode 100644 example/httpserver/upload_file/main.go diff --git a/example/httpserver/upload_file/main.go b/example/httpserver/upload_file/main.go new file mode 100644 index 00000000000..e103a572560 --- /dev/null +++ b/example/httpserver/upload_file/main.go @@ -0,0 +1,44 @@ +package main + +import ( + "context" + + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/net/ghttp" +) + +type UploadReq struct { + g.Meta `path:"/upload" method:"POST" tags:"Upload" mime:"multipart/form-data" summary:"上传文件"` + File *ghttp.UploadFile `p:"file" type:"file" dc:"选择上传文件"` + Msg string `dc:"消息"` +} +type UploadRes struct { + FileName string `json:"fileName"` +} + +type cUpload struct{} + +func (u cUpload) Upload(ctx context.Context, req *UploadReq) (*UploadRes, error) { + if req.File != nil { + return &UploadRes{ + FileName: req.File.Filename, + }, nil + } + return nil, nil +} + +func main() { + s := g.Server() + s.Group("/", func(group *ghttp.RouterGroup) { + group.Middleware(ghttp.MiddlewareHandlerResponse) + group.Bind(cUpload{}) + }) + s.SetClientMaxBodySize(600 * 1024 * 1024) // 600M + s.SetPort(8199) + s.SetAccessLogEnabled(true) + s.Run() +} + +// curl --location 'http://127.0.0.1:8199/upload' \ +// --form 'file=@"/D:/下载/goframe-v2.5.pdf"' \ +// --form 'msg="666"' diff --git a/net/ghttp/ghttp_request_param.go b/net/ghttp/ghttp_request_param.go index 806428ae4e4..aaa873468cf 100644 --- a/net/ghttp/ghttp_request_param.go +++ b/net/ghttp/ghttp_request_param.go @@ -269,8 +269,6 @@ func (r *Request) parseForm() { return } if contentType := r.Header.Get("Content-Type"); contentType != "" { - r.MakeBodyRepeatableRead(true) - var err error if gstr.Contains(contentType, "multipart/") { // multipart/form-data, multipart/mixed diff --git a/net/ghttp/ghttp_z_unit_feature_config_test.go b/net/ghttp/ghttp_z_unit_feature_config_test.go index e3542ce2a2d..e408e4f625f 100644 --- a/net/ghttp/ghttp_z_unit_feature_config_test.go +++ b/net/ghttp/ghttp_z_unit_feature_config_test.go @@ -8,6 +8,7 @@ package ghttp_test import ( "fmt" + "strings" "testing" "time" @@ -154,8 +155,11 @@ func Test_ClientMaxBodySize_File(t *testing.T) { t.Assert(gfile.PutBytes(path, data), nil) defer gfile.Remove(path) t.Assert( - gstr.Trim(c.PostContent(ctx, "/", "name=john&file=@file:"+path)), - "Read from request Body failed: http: request body too large", + true, + strings.Contains( + gstr.Trim(c.PostContent(ctx, "/", "name=john&file=@file:"+path)), + "http: request body too large", + ), ) }) } From d60d7674d799f89f626a5dca4de84c13e8ab437b Mon Sep 17 00:00:00 2001 From: zhonghuaxunGM <50815786+zhonghuaxunGM@users.noreply.github.com> Date: Wed, 20 Dec 2023 20:33:58 +0800 Subject: [PATCH 33/52] fix issues for package contrib/drivers/dm (#3157) --- contrib/drivers/dm/dm.go | 17 ++- contrib/drivers/dm/dm_init_test.go | 141 ++++++++++++--------- contrib/drivers/dm/dm_z_basic_test.go | 173 ++++++++++++++------------ 3 files changed, 191 insertions(+), 140 deletions(-) diff --git a/contrib/drivers/dm/dm.go b/contrib/drivers/dm/dm.go index 076c70d77b5..3855003b1ef 100644 --- a/contrib/drivers/dm/dm.go +++ b/contrib/drivers/dm/dm.go @@ -74,9 +74,16 @@ func (d *Driver) Open(config *gdb.ConfigNode) (db *sql.DB, err error) { } // Data Source Name of DM8: // dm://userName:password@ip:port/dbname + // dm://userName:password@DW/dbname?DW=(192.168.1.1:5236,192.168.1.2:5236) + var domain string + if config.Port != "" { + domain = fmt.Sprintf("%s:%s", config.Host, config.Port) + } else { + domain = config.Host + } source = fmt.Sprintf( - "dm://%s:%s@%s:%s/%s?charset=%s&schema=%s", - config.User, config.Pass, config.Host, config.Port, config.Name, config.Charset, config.Name, + "dm://%s:%s@%s/%s?charset=%s&schema=%s", + config.User, config.Pass, domain, config.Name, config.Charset, config.Name, ) // Demo of timezone setting: // &loc=Asia/Shanghai @@ -210,7 +217,11 @@ func (d *Driver) DoFilter(ctx context.Context, link gdb.Link, sql string, args [ // TODO The current approach is too rough. We should deal with the GROUP_CONCAT function and the parsing of the index field from within the select from match. // (GROUP_CONCAT DM does not approve; index cannot be used as a query column name, and security characters need to be added, such as "index") l, r := d.GetChars() - newSql = gstr.ReplaceI(newSql, "INDEX", l+"INDEX"+r) + if strings.Contains(newSql, "INDEX") || strings.Contains(newSql, "index") { + if !(strings.Contains(newSql, "_INDEX") || strings.Contains(newSql, "_index")) { + newSql = gstr.ReplaceI(newSql, "INDEX", l+"INDEX"+r) + } + } // TODO i tried to do but it never work: // array, err := gregex.MatchAllString(`SELECT (.*INDEX.*) FROM .*`, newSql) diff --git a/contrib/drivers/dm/dm_init_test.go b/contrib/drivers/dm/dm_init_test.go index 7f72bd69310..bfecf1ecfb6 100644 --- a/contrib/drivers/dm/dm_init_test.go +++ b/contrib/drivers/dm/dm_init_test.go @@ -21,38 +21,44 @@ import ( ) var ( - db gdb.DB - dblink gdb.DB - dbErr gdb.DB - ctx context.Context -) - -const ( + db gdb.DB + dblink gdb.DB + dbErr gdb.DB + ctx context.Context TableSize = 10 - - // TableName = "inf_group" - // TableNamePrefix = "t_" - // TestSchema = "SYSDBADP" ) const ( - TestDbIP = "127.0.0.1" - TestDbPort = "5236" - TestDbUser = "SYSDBA" - TestDbPass = "SYSDBA001" - TestDbName = "SYSDBA" - TestDbType = "dm" + TestDBHost = "127.0.0.1" + TestDBPort = "5236" + TestDBUser = "SYSDBA" + TestDBPass = "SYSDBA001" + TestDBName = "SYSDBA" + TestDBType = "dm" TestCharset = "utf8" ) +type User struct { + ID int64 `orm:"id"` + AccountName string `orm:"account_name"` + PwdReset int64 `orm:"pwd_reset"` + AttrIndex int64 `orm:"attr_index"` + Enabled int64 `orm:"enabled"` + Deleted int64 `orm:"deleted"` + CreatedBy string `orm:"created_by"` + CreatedTime time.Time `orm:"created_time"` + UpdatedBy string `orm:"updated_by"` + UpdatedTime time.Time `orm:"updated_time"` +} + func init() { node := gdb.ConfigNode{ - Host: TestDbIP, - Port: TestDbPort, - User: TestDbUser, - Pass: TestDbPass, - Name: TestDbName, - Type: TestDbType, + Host: TestDBHost, + Port: TestDBPort, + User: TestDBUser, + Pass: TestDBPass, + Name: TestDBName, + Type: TestDBType, Role: "master", Charset: TestCharset, Weight: 1, @@ -62,22 +68,23 @@ func init() { UpdatedAt: "updated_time", } + // todo nodeLink := gdb.ConfigNode{ - Type: TestDbType, - Name: TestDbName, + Type: TestDBType, + Name: TestDBName, Link: fmt.Sprintf( "dm:%s:%s@tcp(%s:%s)/%s?charset=%s", - TestDbUser, TestDbPass, TestDbIP, TestDbPort, TestDbName, TestCharset, + TestDBUser, TestDBPass, TestDBHost, TestDBPort, TestDBName, TestCharset, ), } nodeErr := gdb.ConfigNode{ - Host: TestDbIP, - Port: TestDbPort, - User: TestDbUser, + Host: TestDBHost, + Port: TestDBPort, + User: TestDBUser, Pass: "1234", - Name: TestDbName, - Type: TestDbType, + Name: TestDBName, + Type: TestDBType, Role: "master", Charset: TestCharset, Weight: 1, @@ -107,6 +114,23 @@ func init() { ctx = context.Background() } +func dropTable(table string) { + count, err := db.GetCount( + ctx, + "SELECT COUNT(*) FROM all_tables WHERE owner = ? And table_name= ?", TestDBName, strings.ToUpper(table), + ) + if err != nil { + gtest.Fatal(err) + } + + if count == 0 { + return + } + if _, err := db.Exec(ctx, fmt.Sprintf("DROP TABLE %s", table)); err != nil { + gtest.Fatal(err) + } +} + func createTable(table ...string) (name string) { if len(table) > 0 { name = table[0] @@ -124,6 +148,7 @@ func createTable(table ...string) (name string) { "PWD_RESET" TINYINT DEFAULT 0 NOT NULL, "ENABLED" INT DEFAULT 1 NOT NULL, "DELETED" INT DEFAULT 0 NOT NULL, +"ATTR_INDEX" INT DEFAULT 0 , "CREATED_BY" VARCHAR(32) DEFAULT '' NOT NULL, "CREATED_TIME" TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP() NOT NULL, "UPDATED_BY" VARCHAR(32) DEFAULT '' NOT NULL, @@ -136,18 +161,6 @@ NOT CLUSTER PRIMARY KEY("ID")) STORAGE(ON "MAIN", CLUSTERBTR) ; return } -type User struct { - ID int64 `orm:"id"` - AccountName string `orm:"account_name"` - PwdReset int64 `orm:"pwd_reset"` - Enabled int64 `orm:"enabled"` - Deleted int64 `orm:"deleted"` - CreatedBy string `orm:"created_by"` - CreatedTime time.Time `orm:"created_time"` - UpdatedBy string `orm:"updated_by"` - UpdatedTime time.Time `orm:"updated_time"` -} - func createInitTable(table ...string) (name string) { name = createTable(table...) array := garray.New(true) @@ -156,10 +169,11 @@ func createInitTable(table ...string) (name string) { "id": i, "account_name": fmt.Sprintf(`name_%d`, i), "pwd_reset": 0, + "attr_index": i, "create_time": gtime.Now().String(), }) } - result, err := db.Schema(TestDbName).Insert(context.Background(), name, array.Slice()) + result, err := db.Schema(TestDBName).Insert(context.Background(), name, array.Slice()) gtest.Assert(err, nil) n, e := result.RowsAffected() @@ -168,19 +182,34 @@ func createInitTable(table ...string) (name string) { return } -func dropTable(table string) { - count, err := db.GetCount( - ctx, - "SELECT COUNT(*) FROM USER_TABLES WHERE TABLE_NAME = ?", strings.ToUpper(table), - ) - if err != nil { - gtest.Fatal(err) +func createTableFalse(table ...string) (name string, err error) { + if len(table) > 0 { + name = table[0] + } else { + name = fmt.Sprintf("random_%d", gtime.Timestamp()) } - if count == 0 { - return - } - if _, err := db.Exec(ctx, fmt.Sprintf("DROP TABLE %s", table)); err != nil { - gtest.Fatal(err) + dropTable(name) + + if _, err := db.Exec(ctx, fmt.Sprintf(` + CREATE TABLE "%s" +( +"ID" BIGINT NOT NULL, +"ACCOUNT_NAME" VARCHAR(128) DEFAULT '' NOT NULL, +"PWD_RESET" TINYINT DEFAULT 0 NOT NULL, +"ENABLED" INT DEFAULT 1 NOT NULL, +"DELETED" INT DEFAULT 0 NOT NULL, +"INDEX" INT DEFAULT 0 , +"ATTR_INDEX" INT DEFAULT 0 , +"CREATED_BY" VARCHAR(32) DEFAULT '' NOT NULL, +"CREATED_TIME" TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP() NOT NULL, +"UPDATED_BY" VARCHAR(32) DEFAULT '' NOT NULL, +"UPDATED_TIME" TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP() NOT NULL, +NOT CLUSTER PRIMARY KEY("ID")) STORAGE(ON "MAIN", CLUSTERBTR) ; + `, name)); err != nil { + // gtest.Fatal(err) + return name, fmt.Errorf("createTableFalse") } + + return name, nil } diff --git a/contrib/drivers/dm/dm_z_basic_test.go b/contrib/drivers/dm/dm_z_basic_test.go index 5f6eba8335c..c1322ce77b1 100644 --- a/contrib/drivers/dm/dm_z_basic_test.go +++ b/contrib/drivers/dm/dm_z_basic_test.go @@ -27,13 +27,11 @@ func Test_DB_Ping(t *testing.T) { } func TestTables(t *testing.T) { + tables := []string{"A_tables", "A_tables2"} + for _, v := range tables { + createInitTable(v) + } gtest.C(t, func(t *gtest.T) { - tables := []string{"A_tables", "A_tables2"} - - for _, v := range tables { - createInitTable(v) - // createTable(v) - } result, err := db.Tables(ctx) gtest.Assert(err, nil) @@ -63,13 +61,31 @@ func TestTables(t *testing.T) { }) } +// The test scenario index of this test case (exact matching field) is a keyword in the Dameng database and cannot exist as a field name. +// If the data structure previously migrated from mysql has an index (completely matching field), it will also be allowed. +// However, when processing the index (completely matching field), the adapter will automatically add security character +// In principle, such problems will not occur if you directly use Dameng database initialization instead of migrating the data structure from mysql. +// If so, the adapter has also taken care of it. +func TestTablesFalse(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + tables := []string{"A_tables", "A_tables2"} + for _, v := range tables { + _, err := createTableFalse(v) + gtest.Assert(err, fmt.Errorf("createTableFalse")) + // createTable(v) + } + }) +} + func TestTableFields(t *testing.T) { + tables := "A_tables" + createInitTable(tables) gtest.C(t, func(t *gtest.T) { - tables := "A_tables" var expect = map[string][]interface{}{ "ID": {"BIGINT", false}, "ACCOUNT_NAME": {"VARCHAR", false}, "PWD_RESET": {"TINYINT", false}, + "ATTR_INDEX": {"INT", true}, "DELETED": {"INT", false}, "CREATED_TIME": {"TIMESTAMP", false}, } @@ -98,8 +114,9 @@ func TestTableFields(t *testing.T) { } func Test_DB_Query(t *testing.T) { + tableName := "A_tables" + createInitTable(tableName) gtest.C(t, func(t *gtest.T) { - tableName := "A_tables" // createTable(tableName) _, err := db.Query(ctx, fmt.Sprintf("SELECT * from %s", tableName)) t.AssertNil(err) @@ -121,16 +138,18 @@ func Test_DB_Query(t *testing.T) { } func TestModelSave(t *testing.T) { + table := "A_tables" + createInitTable(table) gtest.C(t, func(t *gtest.T) { - // createTable("A_tables") data := []User{ { ID: 100, AccountName: "user_100", + AttrIndex: 100, CreatedTime: time.Now(), }, } - _, err := db.Model("A_tables").Data(data).Save() + _, err := db.Model(table).Data(data).Save() gtest.Assert(err, nil) data2 := []User{ @@ -139,7 +158,7 @@ func TestModelSave(t *testing.T) { AccountName: "user_101", }, } - _, err = db.Model("A_tables").Data(&data2).Save() + _, err = db.Model(table).Data(&data2).Save() gtest.Assert(err, nil) data3 := []User{ @@ -149,7 +168,7 @@ func TestModelSave(t *testing.T) { PwdReset: 10, }, } - _, err = db.Model("A_tables").Save(data3) + _, err = db.Model(table).Save(data3) gtest.Assert(err, nil) data4 := []User{ @@ -159,63 +178,68 @@ func TestModelSave(t *testing.T) { CreatedTime: time.Now(), }, } - _, err = db.Model("A_tables").Save(&data4) + _, err = db.Model(table).Save(&data4) gtest.Assert(err, nil) // TODO:: Should be Supported 'Replace' Operation - // _, err = db.Schema(TestDbName).Replace(ctx, "DoInsert", data, 10) + // _, err = db.Schema(TestDBName).Replace(ctx, "DoInsert", data, 10) // gtest.Assert(err, nil) }) } func TestModelInsert(t *testing.T) { // g.Model.insert not lost default not null coloumn + table := "A_tables" + createInitTable(table) gtest.C(t, func(t *gtest.T) { - // createTable("A_tables") i := 200 data := User{ ID: int64(i), AccountName: fmt.Sprintf(`A%dtwo`, i), PwdReset: 0, + AttrIndex: 99, // CreatedTime: time.Now(), UpdatedTime: time.Now(), } - // _, err := db.Schema(TestDbName).Model("A_tables").Data(data).Insert() - _, err := db.Model("A_tables").Insert(&data) + // _, err := db.Schema(TestDBName).Model(table).Data(data).Insert() + _, err := db.Model(table).Insert(&data) gtest.Assert(err, nil) }) gtest.C(t, func(t *gtest.T) { - // createTable("A_tables") i := 201 data := User{ ID: int64(i), AccountName: fmt.Sprintf(`A%dtwoONE`, i), PwdReset: 1, CreatedTime: time.Now(), + AttrIndex: 98, // UpdatedTime: time.Now(), } - // _, err := db.Schema(TestDbName).Model("A_tables").Data(data).Insert() - _, err := db.Model("A_tables").Data(&data).Insert() + // _, err := db.Schema(TestDBName).Model(table).Data(data).Insert() + _, err := db.Model(table).Data(&data).Insert() gtest.Assert(err, nil) }) } func TestDBInsert(t *testing.T) { + table := "A_tables" + createInitTable("A_tables") gtest.C(t, func(t *gtest.T) { - // createTable("A_tables") i := 300 data := g.Map{ "ID": i, "ACCOUNT_NAME": fmt.Sprintf(`A%dthress`, i), "PWD_RESET": 3, + "ATTR_INDEX": 98, } - _, err := db.Insert(ctx, "A_tables", &data) + _, err := db.Insert(ctx, table, &data) gtest.Assert(err, nil) }) } func Test_DB_Exec(t *testing.T) { + createInitTable("A_tables") gtest.C(t, func(t *gtest.T) { _, err := db.Exec(ctx, "SELECT ? from dual", 1) t.AssertNil(err) @@ -226,18 +250,18 @@ func Test_DB_Exec(t *testing.T) { } func Test_DB_Insert(t *testing.T) { - // table := createTable() - // defer dropTable(table) + table := "A_tables" + createInitTable(table) gtest.C(t, func(t *gtest.T) { // normal map - _, err := db.Insert(ctx, "A_tables", g.Map{ + _, err := db.Insert(ctx, table, g.Map{ "ID": 1000, "ACCOUNT_NAME": "map1", "CREATED_TIME": gtime.Now(), }) t.AssertNil(err) - result, err := db.Insert(ctx, "A_tables", g.Map{ + result, err := db.Insert(ctx, table, g.Map{ "ID": "2000", "ACCOUNT_NAME": "map2", "CREATED_TIME": gtime.Now(), @@ -246,7 +270,7 @@ func Test_DB_Insert(t *testing.T) { n, _ := result.RowsAffected() t.Assert(n, 1) - result, err = db.Insert(ctx, "A_tables", g.Map{ + result, err = db.Insert(ctx, table, g.Map{ "ID": 3000, "ACCOUNT_NAME": "map3", // "CREATED_TIME": gtime.Now(), @@ -256,7 +280,7 @@ func Test_DB_Insert(t *testing.T) { t.Assert(n, 1) // struct - result, err = db.Insert(ctx, "A_tables", User{ + result, err = db.Insert(ctx, table, User{ ID: 4000, AccountName: "struct_4", // CreatedTime: timeStr, @@ -266,7 +290,7 @@ func Test_DB_Insert(t *testing.T) { n, _ = result.RowsAffected() t.Assert(n, 1) - ones, err := db.Model("A_tables").Where("ID", 4000).All() + ones, err := db.Model(table).Where("ID", 4000).All() t.AssertNil(err) t.Assert(ones[0]["ID"].Int(), 4000) t.Assert(ones[0]["ACCOUNT_NAME"].String(), "struct_4") @@ -276,7 +300,7 @@ func Test_DB_Insert(t *testing.T) { // *struct timeStr := time.Now() - result, err = db.Insert(ctx, "A_tables", &User{ + result, err = db.Insert(ctx, table, &User{ ID: 5000, AccountName: "struct_5", CreatedTime: timeStr, @@ -286,13 +310,13 @@ func Test_DB_Insert(t *testing.T) { n, _ = result.RowsAffected() t.Assert(n, 1) - one, err := db.Model("A_tables").Where("ID", 5000).One() + one, err := db.Model(table).Where("ID", 5000).One() t.AssertNil(err) t.Assert(one["ID"].Int(), 5000) t.Assert(one["ACCOUNT_NAME"].String(), "struct_5") // batch with Insert - r, err := db.Insert(ctx, "A_tables", g.Slice{ + r, err := db.Insert(ctx, table, g.Slice{ g.Map{ "ID": 6000, "ACCOUNT_NAME": "t6000", @@ -306,7 +330,7 @@ func Test_DB_Insert(t *testing.T) { n, _ = r.RowsAffected() t.Assert(n, 2) - one, err = db.Model("A_tables").Where("ID", 6000).One() + one, err = db.Model(table).Where("ID", 6000).One() t.AssertNil(err) t.Assert(one["ID"].Int(), 6000) t.Assert(one["ACCOUNT_NAME"].String(), "t6000") @@ -314,8 +338,9 @@ func Test_DB_Insert(t *testing.T) { } func Test_DB_BatchInsert(t *testing.T) { + table := "A_tables" + createInitTable(table) gtest.C(t, func(t *gtest.T) { - table := "A_tables" r, err := db.Insert(ctx, table, g.List{ { "ID": 400, @@ -334,9 +359,6 @@ func Test_DB_BatchInsert(t *testing.T) { }) gtest.C(t, func(t *gtest.T) { - table := "A_tables" - // table := createTable() - // defer dropTable(table) // []interface{} r, err := db.Insert(ctx, table, g.Slice{ g.Map{ @@ -357,9 +379,6 @@ func Test_DB_BatchInsert(t *testing.T) { // batch insert map gtest.C(t, func(t *gtest.T) { - table := "A_tables" - // table := createTable() - // defer dropTable(table) result, err := db.Insert(ctx, table, g.Map{ "ID": 600, "ACCOUNT_NAME": "600_batch_600", @@ -373,10 +392,9 @@ func Test_DB_BatchInsert(t *testing.T) { func Test_DB_BatchInsert_Struct(t *testing.T) { // batch insert struct + table := "A_tables" + createInitTable(table) gtest.C(t, func(t *gtest.T) { - table := "A_tables" - // table := createTable() - // defer dropTable(table) user := &User{ ID: 700, AccountName: "BatchInsert_Struct_700", @@ -391,26 +409,25 @@ func Test_DB_BatchInsert_Struct(t *testing.T) { func Test_DB_Update(t *testing.T) { table := "A_tables" - // table := createInitTable() + createInitTable(table) gtest.C(t, func(t *gtest.T) { - result, err := db.Update(ctx, table, "pwd_reset=7", "id=700") + result, err := db.Update(ctx, table, "pwd_reset=7", "id=7") t.AssertNil(err) n, _ := result.RowsAffected() t.Assert(n, 1) - one, err := db.Model(table).Where("ID", 700).One() + one, err := db.Model(table).Where("ID", 7).One() t.AssertNil(err) - t.Assert(one["ID"].Int(), 700) - t.Assert(one["ACCOUNT_NAME"].String(), "BatchInsert_Struct_700") + t.Assert(one["ID"].Int(), 7) + t.Assert(one["ACCOUNT_NAME"].String(), "name_7") t.Assert(one["PWD_RESET"].String(), "7") }) } func Test_DB_GetAll(t *testing.T) { table := "A_tables" - // table := createInitTable() - // defer dropTable(table) + createInitTable(table) gtest.C(t, func(t *gtest.T) { result, err := db.GetAll(ctx, fmt.Sprintf("SELECT * FROM %s WHERE id=?", table), 1) @@ -459,41 +476,38 @@ func Test_DB_GetAll(t *testing.T) { } func Test_DB_GetOne(t *testing.T) { - // table := createInitTable() table := "A_tables" + createInitTable(table) gtest.C(t, func(t *gtest.T) { - record, err := db.GetOne(ctx, fmt.Sprintf("SELECT * FROM %s WHERE account_name=?", table), "struct_4") + record, err := db.GetOne(ctx, fmt.Sprintf("SELECT * FROM %s WHERE account_name=?", table), "name_4") t.AssertNil(err) - t.Assert(record["ACCOUNT_NAME"].String(), "struct_4") + t.Assert(record["ACCOUNT_NAME"].String(), "name_4") }) } func Test_DB_GetValue(t *testing.T) { table := "A_tables" - // table := createInitTable() - // defer dropTable(table) + createInitTable(table) gtest.C(t, func(t *gtest.T) { - value, err := db.GetValue(ctx, fmt.Sprintf("SELECT id FROM %s WHERE account_name=?", table), "map2") + value, err := db.GetValue(ctx, fmt.Sprintf("SELECT id FROM %s WHERE account_name=?", table), "name_2") t.AssertNil(err) - t.Assert(value.Int(), 2000) + t.Assert(value.Int(), 2) }) } func Test_DB_GetCount(t *testing.T) { table := "A_tables" - // table := createInitTable() - // defer dropTable(table) + createInitTable(table) gtest.C(t, func(t *gtest.T) { count, err := db.GetCount(ctx, fmt.Sprintf("SELECT * FROM %s", table)) t.AssertNil(err) - t.Assert(count, 28) + t.Assert(count, 10) }) } func Test_DB_GetStruct(t *testing.T) { table := "A_tables" - // table := createInitTable() - // defer dropTable(table) + createInitTable(table) gtest.C(t, func(t *gtest.T) { user := new(User) err := db.GetScan(ctx, user, fmt.Sprintf("SELECT * FROM %s WHERE id=?", table), 3) @@ -502,33 +516,31 @@ func Test_DB_GetStruct(t *testing.T) { }) gtest.C(t, func(t *gtest.T) { user := new(User) - err := db.GetScan(ctx, user, fmt.Sprintf("SELECT * FROM %s WHERE id=?", table), 200) + err := db.GetScan(ctx, user, fmt.Sprintf("SELECT * FROM %s WHERE id=?", table), 2) t.AssertNil(err) - t.Assert(user.AccountName, "A200two") + t.Assert(user.AccountName, "name_2") }) } func Test_DB_GetStructs(t *testing.T) { table := "A_tables" - // table := createInitTable() - // defer dropTable(table) + createInitTable(table) gtest.C(t, func(t *gtest.T) { var users []User - err := db.GetScan(ctx, &users, fmt.Sprintf("SELECT * FROM %s WHERE id>?", table), 4000) + err := db.GetScan(ctx, &users, fmt.Sprintf("SELECT * FROM %s WHERE id>?", table), 4) t.AssertNil(err) - t.Assert(users[0].ID, 5000) - t.Assert(users[1].ID, 6000) - t.Assert(users[2].ID, 6001) - t.Assert(users[0].AccountName, "struct_5") - t.Assert(users[1].AccountName, "t6000") - t.Assert(users[2].AccountName, "t6001") + t.Assert(users[0].ID, 5) + t.Assert(users[1].ID, 6) + t.Assert(users[2].ID, 7) + t.Assert(users[0].AccountName, "name_5") + t.Assert(users[1].AccountName, "name_6") + t.Assert(users[2].AccountName, "name_7") }) } func Test_DB_GetScan(t *testing.T) { table := "A_tables" - // table := createInitTable() - // defer dropTable(table) + createInitTable(table) gtest.C(t, func(t *gtest.T) { user := new(User) err := db.GetScan(ctx, user, fmt.Sprintf("SELECT * FROM %s WHERE id=?", table), 3) @@ -555,17 +567,17 @@ func Test_DB_GetScan(t *testing.T) { } func Test_DB_Delete(t *testing.T) { - // table := createInitTable() - // defer dropTable(table) + table := "A_tables" + createInitTable(table) gtest.C(t, func(t *gtest.T) { - result, err := db.Delete(ctx, "A_tables", "id=32") + result, err := db.Delete(ctx, table, "id=32") t.AssertNil(err) n, _ := result.RowsAffected() t.Assert(n, 0) }) gtest.C(t, func(t *gtest.T) { - result, err := db.Model("A_tables").Where("id", 33).Delete() + result, err := db.Model(table).Where("id", 33).Delete() t.AssertNil(err) n, _ := result.RowsAffected() t.Assert(n, 0) @@ -574,8 +586,7 @@ func Test_DB_Delete(t *testing.T) { func Test_Empty_Slice_Argument(t *testing.T) { table := "A_tables" - // table := createInitTable() - // defer dropTable(table) + createInitTable(table) gtest.C(t, func(t *gtest.T) { result, err := db.GetAll(ctx, fmt.Sprintf(`select * from %s where id in(?)`, table), g.Slice{}) t.AssertNil(err) From 4cce8557e699f300ef7ab546227cf52c03288103 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B5=B7=E4=BA=AE?= <739476267@qq.com> Date: Thu, 21 Dec 2023 10:16:14 +0800 Subject: [PATCH 34/52] fix: #2924 (#3177) --- cmd/gf/internal/cmd/cmd_z_init_test.go | 31 +++++++- .../internal/cmd/cmd_z_unit_gen_dao_test.go | 24 ++----- .../cmd/cmd_z_unit_gen_pbentity_test.go | 70 +++++++++++++++++++ .../internal/cmd/genpbentity/genpbentity.go | 29 ++------ .../generated_user/table_user.proto | 21 ++++++ .../cmd/testdata/genpbentity/user.tpl.sql | 10 +++ 6 files changed, 138 insertions(+), 47 deletions(-) create mode 100644 cmd/gf/internal/cmd/cmd_z_unit_gen_pbentity_test.go create mode 100644 cmd/gf/internal/cmd/testdata/genpbentity/generated_user/table_user.proto create mode 100644 cmd/gf/internal/cmd/testdata/genpbentity/user.tpl.sql diff --git a/cmd/gf/internal/cmd/cmd_z_init_test.go b/cmd/gf/internal/cmd/cmd_z_init_test.go index 8ad499ff427..1e71cbd8bb6 100644 --- a/cmd/gf/internal/cmd/cmd_z_init_test.go +++ b/cmd/gf/internal/cmd/cmd_z_init_test.go @@ -6,6 +6,33 @@ package cmd -import "context" +import ( + "context" + "fmt" -var ctx = context.Background() + "github.com/gogf/gf/v2/database/gdb" + "github.com/gogf/gf/v2/test/gtest" +) + +var ( + ctx = context.Background() + testDB gdb.DB + link = "mysql:root:12345678@tcp(127.0.0.1:3306)/test?loc=Local&parseTime=true" +) + +func init() { + var err error + testDB, err = gdb.New(gdb.ConfigNode{ + Link: link, + }) + if err != nil { + panic(err) + } +} + +func dropTableWithDb(db gdb.DB, table string) { + dropTableStmt := fmt.Sprintf("DROP TABLE IF EXISTS `%s`", table) + if _, err := db.Exec(ctx, dropTableStmt); err != nil { + gtest.Error(err) + } +} diff --git a/cmd/gf/internal/cmd/cmd_z_unit_gen_dao_test.go b/cmd/gf/internal/cmd/cmd_z_unit_gen_dao_test.go index 18323b03482..71818fb82dc 100644 --- a/cmd/gf/internal/cmd/cmd_z_unit_gen_dao_test.go +++ b/cmd/gf/internal/cmd/cmd_z_unit_gen_dao_test.go @@ -12,7 +12,6 @@ import ( "testing" "github.com/gogf/gf/cmd/gf/v2/internal/cmd/gendao" - "github.com/gogf/gf/v2/database/gdb" "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/text/gstr" @@ -20,22 +19,11 @@ import ( "github.com/gogf/gf/v2/util/gutil" ) -func dropTableWithDb(db gdb.DB, table string) { - dropTableStmt := fmt.Sprintf("DROP TABLE IF EXISTS `%s`", table) - if _, err := db.Exec(ctx, dropTableStmt); err != nil { - gtest.Error(err) - } -} - func Test_Gen_Dao_Default(t *testing.T) { - link := "mysql:root:12345678@tcp(127.0.0.1:3306)/test?loc=Local&parseTime=true" - db, err := gdb.New(gdb.ConfigNode{ - Link: link, - }) - gtest.AssertNil(err) - gtest.C(t, func(t *gtest.T) { var ( + err error + db = testDB table = "table_user" sqlContent = fmt.Sprintf( gtest.DataContent(`gendao`, `user.tpl.sql`), @@ -123,14 +111,10 @@ func Test_Gen_Dao_Default(t *testing.T) { } func Test_Gen_Dao_TypeMapping(t *testing.T) { - link := "mysql:root:12345678@tcp(127.0.0.1:3306)/test?loc=Local&parseTime=true" - db, err := gdb.New(gdb.ConfigNode{ - Link: link, - }) - gtest.AssertNil(err) - gtest.C(t, func(t *gtest.T) { var ( + err error + db = testDB table = "table_user" sqlContent = fmt.Sprintf( gtest.DataContent(`gendao`, `user.tpl.sql`), diff --git a/cmd/gf/internal/cmd/cmd_z_unit_gen_pbentity_test.go b/cmd/gf/internal/cmd/cmd_z_unit_gen_pbentity_test.go new file mode 100644 index 00000000000..48ebdb9a4ff --- /dev/null +++ b/cmd/gf/internal/cmd/cmd_z_unit_gen_pbentity_test.go @@ -0,0 +1,70 @@ +// Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +package cmd + +import ( + "fmt" + "os" + "path/filepath" + "testing" + + "github.com/gogf/gf/v2/os/gcmd" + "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/text/gstr" + "github.com/gogf/gf/v2/util/guid" +) + +func Test_Gen_Pbentity_NameCase(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + var ( + err error + db = testDB + table = "table_user" + sqlContent = fmt.Sprintf( + gtest.DataContent(`genpbentity`, `user.tpl.sql`), + table, + ) + ) + dropTableWithDb(db, table) + array := gstr.SplitAndTrim(sqlContent, ";") + for _, v := range array { + if _, err = db.Exec(ctx, v); err != nil { + t.AssertNil(err) + } + } + defer dropTableWithDb(db, table) + var path = gfile.Temp(guid.S()) + err = gfile.Mkdir(path) + t.AssertNil(err) + defer gfile.Remove(path) + + root, err := gcmd.NewFromObject(GF) + t.AssertNil(err) + err = root.AddObject( + Gen, + ) + t.AssertNil(err) + os.Args = []string{"gf", "gen", "pbentity", "-l", link, "-p", path, "-package=unittest", "-nameCase=SnakeScreaming"} + + err = root.RunWithError(ctx) + t.AssertNil(err) + + files := []string{ + filepath.FromSlash(path + "/table_user.proto"), + } + + testPath := gtest.DataPath("genpbentity", "generated_user") + expectFiles := []string{ + filepath.FromSlash(testPath + "/table_user.proto"), + } + // check files content + for i := range files { + t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i])) + } + }) +} diff --git a/cmd/gf/internal/cmd/genpbentity/genpbentity.go b/cmd/gf/internal/cmd/genpbentity/genpbentity.go index 055d241b8bf..1263ac1e21e 100644 --- a/cmd/gf/internal/cmd/genpbentity/genpbentity.go +++ b/cmd/gf/internal/cmd/genpbentity/genpbentity.go @@ -40,7 +40,7 @@ type ( RemovePrefix string `name:"removePrefix" short:"r" brief:"{CGenPbEntityBriefRemovePrefix}"` RemoveFieldPrefix string `name:"removeFieldPrefix" short:"rf" brief:"{CGenPbEntityBriefRemoveFieldPrefix}"` NameCase string `name:"nameCase" short:"n" brief:"{CGenPbEntityBriefNameCase}" d:"Camel"` - JsonCase string `name:"jsonCase" short:"j" brief:"{CGenPbEntityBriefJsonCase}" d:"CamelLower"` + JsonCase string `name:"jsonCase" short:"j" brief:"{CGenPbEntityBriefJsonCase}" d:"none"` Option string `name:"option" short:"o" brief:"{CGenPbEntityBriefOption}"` } CGenPbEntityOutput struct{} @@ -342,6 +342,7 @@ func generateMessageFieldForPbEntity(index int, field *gdb.TableField, in CGenPb comment = gstr.Replace(comment, `\n`, " ") comment, _ = gregex.ReplaceString(`\s{2,}`, ` `, comment) if jsonTagName := formatCase(field.Name, in.JsonCase); jsonTagName != "" { + jsonTagStr = fmt.Sprintf(`[json_name = "%s"]`, jsonTagName) // beautiful indent. if index < 10 { // 3 spaces @@ -378,32 +379,10 @@ func getTplPbEntityContent(tplEntityPath string) string { // formatCase call gstr.Case* function to convert the s to specified case. func formatCase(str, caseStr string) string { - switch gstr.ToLower(caseStr) { - case gstr.ToLower("Camel"): - return gstr.CaseCamel(str) - - case gstr.ToLower("CamelLower"): - return gstr.CaseCamelLower(str) - - case gstr.ToLower("Kebab"): - return gstr.CaseKebab(str) - - case gstr.ToLower("KebabScreaming"): - return gstr.CaseKebabScreaming(str) - - case gstr.ToLower("Snake"): - return gstr.CaseSnake(str) - - case gstr.ToLower("SnakeFirstUpper"): - return gstr.CaseSnakeFirstUpper(str) - - case gstr.ToLower("SnakeScreaming"): - return gstr.CaseSnakeScreaming(str) - - case "none": + if caseStr == "none" { return "" } - return str + return gstr.CaseConvert(str, gstr.CaseTypeMatch(caseStr)) } func sortFieldKeyForPbEntity(fieldMap map[string]*gdb.TableField) []string { diff --git a/cmd/gf/internal/cmd/testdata/genpbentity/generated_user/table_user.proto b/cmd/gf/internal/cmd/testdata/genpbentity/generated_user/table_user.proto new file mode 100644 index 00000000000..365999ece70 --- /dev/null +++ b/cmd/gf/internal/cmd/testdata/genpbentity/generated_user/table_user.proto @@ -0,0 +1,21 @@ +// ========================================================================== +// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT. +// ========================================================================== + +syntax = "proto3"; + +package unittest; + +option go_package = "unittest"; + +import "google/protobuf/timestamp.proto"; + +message TableUser { + uint32 ID = 1; // User ID + string PASSPORT = 2; // User Passport + string PASSWORD = 3; // User Password + string NICKNAME = 4; // User Nickname + string SCORE = 5; // Total score amount. + google.protobuf.Timestamp CREATE_AT = 6; // Created Time + google.protobuf.Timestamp UPDATE_AT = 7; // Updated Time +} \ No newline at end of file diff --git a/cmd/gf/internal/cmd/testdata/genpbentity/user.tpl.sql b/cmd/gf/internal/cmd/testdata/genpbentity/user.tpl.sql new file mode 100644 index 00000000000..f27fc11bd31 --- /dev/null +++ b/cmd/gf/internal/cmd/testdata/genpbentity/user.tpl.sql @@ -0,0 +1,10 @@ +CREATE TABLE `%s` ( + `id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'User ID', + `passport` varchar(45) NOT NULL COMMENT 'User Passport', + `password` varchar(45) NOT NULL COMMENT 'User Password', + `nickname` varchar(45) NOT NULL COMMENT 'User Nickname', + `score` decimal(10,2) unsigned DEFAULT NULL COMMENT 'Total score amount.', + `create_at` datetime DEFAULT NULL COMMENT 'Created Time', + `update_at` datetime DEFAULT NULL COMMENT 'Updated Time', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; From 85d95e3e2777f378ac968a0e67cca81df03a4931 Mon Sep 17 00:00:00 2001 From: John Guo Date: Thu, 21 Dec 2023 21:12:51 +0800 Subject: [PATCH 35/52] version v2.6.1 (#3222) --- cmd/gf/go.mod | 14 +++++++------- contrib/config/apollo/go.mod | 2 +- contrib/config/consul/go.mod | 2 +- contrib/config/kubecm/go.mod | 2 +- contrib/config/nacos/go.mod | 2 +- contrib/config/polaris/go.mod | 2 +- contrib/drivers/clickhouse/go.mod | 2 +- contrib/drivers/dm/go.mod | 2 +- contrib/drivers/mssql/go.mod | 2 +- contrib/drivers/mysql/go.mod | 2 +- contrib/drivers/mysql/mysql__test.go | 1 - contrib/drivers/oracle/go.mod | 2 +- contrib/drivers/pgsql/go.mod | 2 +- contrib/drivers/sqlite/go.mod | 2 +- contrib/drivers/sqlitecgo/go.mod | 2 +- contrib/nosql/redis/go.mod | 2 +- contrib/registry/etcd/go.mod | 2 +- contrib/registry/file/go.mod | 2 +- contrib/registry/nacos/go.mod | 2 +- contrib/registry/polaris/go.mod | 2 +- contrib/registry/zookeeper/go.mod | 2 +- contrib/rpc/grpcx/go.mod | 4 ++-- contrib/sdk/httpclient/go.mod | 2 +- contrib/trace/jaeger/go.mod | 2 +- contrib/trace/otlpgrpc/go.mod | 2 +- contrib/trace/otlphttp/go.mod | 2 +- example/go.mod | 28 ++++++++++++++-------------- version.go | 2 +- 28 files changed, 47 insertions(+), 48 deletions(-) diff --git a/cmd/gf/go.mod b/cmd/gf/go.mod index 3f7bcff4009..ed19f43dc47 100644 --- a/cmd/gf/go.mod +++ b/cmd/gf/go.mod @@ -3,13 +3,13 @@ module github.com/gogf/gf/cmd/gf/v2 go 1.18 require ( - github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.6.0 - github.com/gogf/gf/contrib/drivers/mssql/v2 v2.6.0 - github.com/gogf/gf/contrib/drivers/mysql/v2 v2.6.0 - github.com/gogf/gf/contrib/drivers/oracle/v2 v2.6.0 - github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.6.0 - github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.6.0 - github.com/gogf/gf/v2 v2.6.0 + github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.6.1 + github.com/gogf/gf/contrib/drivers/mssql/v2 v2.6.1 + github.com/gogf/gf/contrib/drivers/mysql/v2 v2.6.1 + github.com/gogf/gf/contrib/drivers/oracle/v2 v2.6.1 + github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.6.1 + github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.6.1 + github.com/gogf/gf/v2 v2.6.1 github.com/gogf/selfupdate v0.0.0-20231215043001-5c48c528462f github.com/olekukonko/tablewriter v0.0.5 golang.org/x/mod v0.9.0 diff --git a/contrib/config/apollo/go.mod b/contrib/config/apollo/go.mod index 4aa84d471a8..817d3f719d8 100644 --- a/contrib/config/apollo/go.mod +++ b/contrib/config/apollo/go.mod @@ -4,7 +4,7 @@ go 1.18 require ( github.com/apolloconfig/agollo/v4 v4.3.1 - github.com/gogf/gf/v2 v2.6.0 + github.com/gogf/gf/v2 v2.6.1 ) require ( diff --git a/contrib/config/consul/go.mod b/contrib/config/consul/go.mod index 0c7dff58cbc..4ee7b0beee6 100644 --- a/contrib/config/consul/go.mod +++ b/contrib/config/consul/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/consul/v2 go 1.19 require ( - github.com/gogf/gf/v2 v2.6.0 + github.com/gogf/gf/v2 v2.6.1 github.com/hashicorp/consul/api v1.24.0 github.com/hashicorp/go-cleanhttp v0.5.2 ) diff --git a/contrib/config/kubecm/go.mod b/contrib/config/kubecm/go.mod index fa6d4e84ef2..438eb882c6d 100644 --- a/contrib/config/kubecm/go.mod +++ b/contrib/config/kubecm/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/kubecm/v2 go 1.19 require ( - github.com/gogf/gf/v2 v2.6.0 + github.com/gogf/gf/v2 v2.6.1 k8s.io/api v0.27.4 k8s.io/apimachinery v0.27.4 k8s.io/client-go v0.27.4 diff --git a/contrib/config/nacos/go.mod b/contrib/config/nacos/go.mod index e614e98b83d..1672270f720 100644 --- a/contrib/config/nacos/go.mod +++ b/contrib/config/nacos/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/nacos/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.6.0 + github.com/gogf/gf/v2 v2.6.1 github.com/nacos-group/nacos-sdk-go v1.1.4 ) diff --git a/contrib/config/polaris/go.mod b/contrib/config/polaris/go.mod index 2242775ac0d..9bcc44bf367 100644 --- a/contrib/config/polaris/go.mod +++ b/contrib/config/polaris/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/polaris/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.6.0 + github.com/gogf/gf/v2 v2.6.1 github.com/polarismesh/polaris-go v1.5.5 ) diff --git a/contrib/drivers/clickhouse/go.mod b/contrib/drivers/clickhouse/go.mod index c66bfd3d005..6967a60354a 100644 --- a/contrib/drivers/clickhouse/go.mod +++ b/contrib/drivers/clickhouse/go.mod @@ -4,7 +4,7 @@ go 1.18 require ( github.com/ClickHouse/clickhouse-go/v2 v2.0.15 - github.com/gogf/gf/v2 v2.6.0 + github.com/gogf/gf/v2 v2.6.1 github.com/google/uuid v1.3.0 github.com/shopspring/decimal v1.3.1 ) diff --git a/contrib/drivers/dm/go.mod b/contrib/drivers/dm/go.mod index 6f9ecf5c963..64a0566644a 100644 --- a/contrib/drivers/dm/go.mod +++ b/contrib/drivers/dm/go.mod @@ -6,7 +6,7 @@ replace github.com/gogf/gf/v2 => ../../../ require ( gitee.com/chunanyong/dm v1.8.12 - github.com/gogf/gf/v2 v2.6.0 + github.com/gogf/gf/v2 v2.6.1 ) require ( diff --git a/contrib/drivers/mssql/go.mod b/contrib/drivers/mssql/go.mod index 4252772b974..beeed917ccb 100644 --- a/contrib/drivers/mssql/go.mod +++ b/contrib/drivers/mssql/go.mod @@ -4,7 +4,7 @@ go 1.18 require ( github.com/denisenkom/go-mssqldb v0.12.3 - github.com/gogf/gf/v2 v2.6.0 + github.com/gogf/gf/v2 v2.6.1 ) require ( diff --git a/contrib/drivers/mysql/go.mod b/contrib/drivers/mysql/go.mod index 22c847fc626..8ef66b79a7a 100644 --- a/contrib/drivers/mysql/go.mod +++ b/contrib/drivers/mysql/go.mod @@ -4,7 +4,7 @@ go 1.18 require ( github.com/go-sql-driver/mysql v1.7.1 - github.com/gogf/gf/v2 v2.6.0 + github.com/gogf/gf/v2 v2.6.1 ) require ( diff --git a/contrib/drivers/mysql/mysql__test.go b/contrib/drivers/mysql/mysql__test.go index fabafd8d811..ea4b8694cfd 100644 --- a/contrib/drivers/mysql/mysql__test.go +++ b/contrib/drivers/mysql/mysql__test.go @@ -55,7 +55,6 @@ func init() { nodeInvalid := gdb.ConfigNode{ Link: fmt.Sprintf("mysql:root:%s@tcp(127.0.0.1:3307)/?loc=Local&parseTime=true", TestDbPass), } - gdb.AddConfigNode("test", nodeDefault) gdb.AddConfigNode("prefix", nodePrefix) gdb.AddConfigNode("nodeinvalid", nodeInvalid) diff --git a/contrib/drivers/oracle/go.mod b/contrib/drivers/oracle/go.mod index 1498db14d1a..3cd843100ef 100644 --- a/contrib/drivers/oracle/go.mod +++ b/contrib/drivers/oracle/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/drivers/oracle/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.6.0 + github.com/gogf/gf/v2 v2.6.1 github.com/sijms/go-ora/v2 v2.7.10 ) diff --git a/contrib/drivers/pgsql/go.mod b/contrib/drivers/pgsql/go.mod index 192908b3da2..8d9295e1dc5 100644 --- a/contrib/drivers/pgsql/go.mod +++ b/contrib/drivers/pgsql/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/drivers/pgsql/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.6.0 + github.com/gogf/gf/v2 v2.6.1 github.com/lib/pq v1.10.9 ) diff --git a/contrib/drivers/sqlite/go.mod b/contrib/drivers/sqlite/go.mod index 82ecdaaefee..166b88a0217 100644 --- a/contrib/drivers/sqlite/go.mod +++ b/contrib/drivers/sqlite/go.mod @@ -4,7 +4,7 @@ go 1.18 require ( github.com/glebarez/go-sqlite v1.21.2 - github.com/gogf/gf/v2 v2.6.0 + github.com/gogf/gf/v2 v2.6.1 ) require ( diff --git a/contrib/drivers/sqlitecgo/go.mod b/contrib/drivers/sqlitecgo/go.mod index 599f16a8d8c..d4caa017d8c 100644 --- a/contrib/drivers/sqlitecgo/go.mod +++ b/contrib/drivers/sqlitecgo/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/drivers/sqlitecgo/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.6.0 + github.com/gogf/gf/v2 v2.6.1 github.com/mattn/go-sqlite3 v1.14.17 ) diff --git a/contrib/nosql/redis/go.mod b/contrib/nosql/redis/go.mod index ba1b467545c..4c5fbed52b9 100644 --- a/contrib/nosql/redis/go.mod +++ b/contrib/nosql/redis/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/nosql/redis/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.6.0 + github.com/gogf/gf/v2 v2.6.1 github.com/redis/go-redis/v9 v9.2.1 go.opentelemetry.io/otel v1.14.0 go.opentelemetry.io/otel/trace v1.14.0 diff --git a/contrib/registry/etcd/go.mod b/contrib/registry/etcd/go.mod index 8967d52106f..a198b7cb7f0 100644 --- a/contrib/registry/etcd/go.mod +++ b/contrib/registry/etcd/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/registry/etcd/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.6.0 + github.com/gogf/gf/v2 v2.6.1 go.etcd.io/etcd/client/v3 v3.5.7 ) diff --git a/contrib/registry/file/go.mod b/contrib/registry/file/go.mod index 0b879e3ba9f..22dcac4521c 100644 --- a/contrib/registry/file/go.mod +++ b/contrib/registry/file/go.mod @@ -2,7 +2,7 @@ module github.com/gogf/gf/contrib/registry/file/v2 go 1.18 -require github.com/gogf/gf/v2 v2.6.0 +require github.com/gogf/gf/v2 v2.6.1 require ( github.com/BurntSushi/toml v1.2.0 // indirect diff --git a/contrib/registry/nacos/go.mod b/contrib/registry/nacos/go.mod index b61a463a2f3..fd6aef21473 100644 --- a/contrib/registry/nacos/go.mod +++ b/contrib/registry/nacos/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/registry/nacos/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.6.0 + github.com/gogf/gf/v2 v2.6.1 github.com/joy999/nacos-sdk-go v0.0.0-20231120071639-10a34b3e7288 ) diff --git a/contrib/registry/polaris/go.mod b/contrib/registry/polaris/go.mod index 55b82a1c092..bee2a705208 100644 --- a/contrib/registry/polaris/go.mod +++ b/contrib/registry/polaris/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/registry/polaris/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.6.0 + github.com/gogf/gf/v2 v2.6.1 github.com/polarismesh/polaris-go v1.5.5 ) diff --git a/contrib/registry/zookeeper/go.mod b/contrib/registry/zookeeper/go.mod index c9cc2c6141a..ceb25a441c2 100644 --- a/contrib/registry/zookeeper/go.mod +++ b/contrib/registry/zookeeper/go.mod @@ -4,7 +4,7 @@ go 1.18 require ( github.com/go-zookeeper/zk v1.0.3 - github.com/gogf/gf/v2 v2.6.0 + github.com/gogf/gf/v2 v2.6.1 golang.org/x/sync v0.4.0 ) diff --git a/contrib/rpc/grpcx/go.mod b/contrib/rpc/grpcx/go.mod index aced4f90f4f..84ec65263a7 100644 --- a/contrib/rpc/grpcx/go.mod +++ b/contrib/rpc/grpcx/go.mod @@ -3,8 +3,8 @@ module github.com/gogf/gf/contrib/rpc/grpcx/v2 go 1.18 require ( - github.com/gogf/gf/contrib/registry/file/v2 v2.6.0 - github.com/gogf/gf/v2 v2.6.0 + github.com/gogf/gf/contrib/registry/file/v2 v2.6.1 + github.com/gogf/gf/v2 v2.6.1 go.opentelemetry.io/otel v1.14.0 go.opentelemetry.io/otel/trace v1.14.0 google.golang.org/grpc v1.57.2 diff --git a/contrib/sdk/httpclient/go.mod b/contrib/sdk/httpclient/go.mod index 9d558be432c..30d3efb51a7 100644 --- a/contrib/sdk/httpclient/go.mod +++ b/contrib/sdk/httpclient/go.mod @@ -2,7 +2,7 @@ module github.com/gogf/gf/contrib/sdk/httpclient/v2 go 1.18 -require github.com/gogf/gf/v2 v2.6.0 +require github.com/gogf/gf/v2 v2.6.1 require ( github.com/BurntSushi/toml v1.2.0 // indirect diff --git a/contrib/trace/jaeger/go.mod b/contrib/trace/jaeger/go.mod index 582db1e2552..5b815511316 100644 --- a/contrib/trace/jaeger/go.mod +++ b/contrib/trace/jaeger/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/trace/jaeger/v2 go 1.18 require ( - github.com/gogf/gf/v2 v2.6.0 + github.com/gogf/gf/v2 v2.6.1 go.opentelemetry.io/otel v1.14.0 go.opentelemetry.io/otel/exporters/jaeger v1.14.0 go.opentelemetry.io/otel/sdk v1.14.0 diff --git a/contrib/trace/otlpgrpc/go.mod b/contrib/trace/otlpgrpc/go.mod index 407a1619259..3127e961477 100644 --- a/contrib/trace/otlpgrpc/go.mod +++ b/contrib/trace/otlpgrpc/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/trace/otlpgrpc/v2 go 1.20 require ( - github.com/gogf/gf/v2 v2.6.0 + github.com/gogf/gf/v2 v2.6.1 go.opentelemetry.io/otel v1.19.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.19.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.19.0 diff --git a/contrib/trace/otlphttp/go.mod b/contrib/trace/otlphttp/go.mod index d26e1ff5889..ff01fa854cb 100644 --- a/contrib/trace/otlphttp/go.mod +++ b/contrib/trace/otlphttp/go.mod @@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/trace/otlphttp/v2 go 1.20 require ( - github.com/gogf/gf/v2 v2.6.0 + github.com/gogf/gf/v2 v2.6.1 go.opentelemetry.io/otel v1.19.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.19.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.19.0 diff --git a/example/go.mod b/example/go.mod index dc200d27e07..b4ee15026c0 100644 --- a/example/go.mod +++ b/example/go.mod @@ -3,21 +3,21 @@ module github.com/gogf/gf/example go 1.20 require ( - github.com/gogf/gf/contrib/config/apollo/v2 v2.6.0 - github.com/gogf/gf/contrib/config/consul/v2 v2.6.0 - github.com/gogf/gf/contrib/config/kubecm/v2 v2.6.0 - github.com/gogf/gf/contrib/config/nacos/v2 v2.6.0 - github.com/gogf/gf/contrib/config/polaris/v2 v2.6.0 - github.com/gogf/gf/contrib/drivers/mysql/v2 v2.6.0 - github.com/gogf/gf/contrib/nosql/redis/v2 v2.6.0 - github.com/gogf/gf/contrib/registry/etcd/v2 v2.6.0 - github.com/gogf/gf/contrib/registry/file/v2 v2.6.0 + github.com/gogf/gf/contrib/config/apollo/v2 v2.6.1 + github.com/gogf/gf/contrib/config/consul/v2 v2.6.1 + github.com/gogf/gf/contrib/config/kubecm/v2 v2.6.1 + github.com/gogf/gf/contrib/config/nacos/v2 v2.6.1 + github.com/gogf/gf/contrib/config/polaris/v2 v2.6.1 + github.com/gogf/gf/contrib/drivers/mysql/v2 v2.6.1 + github.com/gogf/gf/contrib/nosql/redis/v2 v2.6.1 + github.com/gogf/gf/contrib/registry/etcd/v2 v2.6.1 + github.com/gogf/gf/contrib/registry/file/v2 v2.6.1 github.com/gogf/gf/contrib/registry/nacos/v2 v2.5.6 - github.com/gogf/gf/contrib/registry/polaris/v2 v2.6.0 - github.com/gogf/gf/contrib/rpc/grpcx/v2 v2.6.0 - github.com/gogf/gf/contrib/trace/otlpgrpc/v2 v2.6.0 - github.com/gogf/gf/contrib/trace/otlphttp/v2 v2.6.0 - github.com/gogf/gf/v2 v2.6.0 + github.com/gogf/gf/contrib/registry/polaris/v2 v2.6.1 + github.com/gogf/gf/contrib/rpc/grpcx/v2 v2.6.1 + github.com/gogf/gf/contrib/trace/otlpgrpc/v2 v2.6.1 + github.com/gogf/gf/contrib/trace/otlphttp/v2 v2.6.1 + github.com/gogf/gf/v2 v2.6.1 github.com/hashicorp/consul/api v1.24.0 github.com/hashicorp/go-cleanhttp v0.5.2 github.com/nacos-group/nacos-sdk-go v1.1.4 diff --git a/version.go b/version.go index 2f9e499ba7c..35ea070d7bb 100644 --- a/version.go +++ b/version.go @@ -2,5 +2,5 @@ package gf const ( // VERSION is the current GoFrame version. - VERSION = "v2.6.0" + VERSION = "v2.6.1" ) From 16a43bcb6cd5c48e64067251a5c715f1e6bd64b5 Mon Sep 17 00:00:00 2001 From: zhangyuyu <1580074674@qq.com> Date: Tue, 26 Dec 2023 16:19:59 +0800 Subject: [PATCH 36/52] Add comment for Format method so that you can know Layout method. (#3230) --- os/gtime/gtime_format.go | 1 + 1 file changed, 1 insertion(+) diff --git a/os/gtime/gtime_format.go b/os/gtime/gtime_format.go index fd1d214bac9..9214e4b2125 100644 --- a/os/gtime/gtime_format.go +++ b/os/gtime/gtime_format.go @@ -67,6 +67,7 @@ var ( ) // Format formats and returns the formatted result with custom `format`. +// Refer method Layout, if you want to follow stdlib layout. func (t *Time) Format(format string) string { if t == nil { return "" From 9f7ce42c740b4ba6e3c0ace2eed5800c22f818bc Mon Sep 17 00:00:00 2001 From: oldme <45782393+oldme-git@users.noreply.github.com> Date: Thu, 28 Dec 2023 20:07:07 +0800 Subject: [PATCH 37/52] enhance #3221 (#3224) --- os/gstructs/gstructs_field.go | 17 ++++++++++ util/gutil/gutil_struct.go | 11 ++++++- util/gutil/gutil_z_unit_struct_test.go | 45 ++++++++++++++++++++------ 3 files changed, 63 insertions(+), 10 deletions(-) diff --git a/os/gstructs/gstructs_field.go b/os/gstructs/gstructs_field.go index 12213b73d44..639291fd25c 100644 --- a/os/gstructs/gstructs_field.go +++ b/os/gstructs/gstructs_field.go @@ -92,9 +92,26 @@ func (f *Field) OriginalKind() reflect.Kind { reflectType = reflectType.Elem() reflectKind = reflectType.Kind() } + return reflectKind } +// OriginalValue retrieves and returns the original reflect.Value of Field `f`. +func (f *Field) OriginalValue() reflect.Value { + var ( + reflectValue = f.Value + reflectType = reflectValue.Type() + reflectKind = reflectType.Kind() + ) + + for reflectKind == reflect.Ptr && !f.IsNil() { + reflectValue = reflectValue.Elem() + reflectKind = reflectValue.Type().Kind() + } + + return reflectValue +} + // IsEmpty checks and returns whether the value of this Field is empty. func (f *Field) IsEmpty() bool { return empty.IsEmpty(f.Value) diff --git a/util/gutil/gutil_struct.go b/util/gutil/gutil_struct.go index dee73648119..f0b87cbcd90 100644 --- a/util/gutil/gutil_struct.go +++ b/util/gutil/gutil_struct.go @@ -83,12 +83,20 @@ func FillStructWithDefault(structPtr interface{}) error { } fields, err := gstructs.Fields(gstructs.FieldsInput{ Pointer: reflectValue, - RecursiveOption: gstructs.RecursiveOptionNone, + RecursiveOption: gstructs.RecursiveOptionEmbedded, }) if err != nil { return err } for _, field := range fields { + if field.OriginalKind() == reflect.Struct { + err := FillStructWithDefault(field.OriginalValue().Addr()) + if err != nil { + return err + } + continue + } + if defaultValue := field.TagDefault(); defaultValue != "" { if field.IsEmpty() { field.Value.Set(reflect.ValueOf( @@ -97,5 +105,6 @@ func FillStructWithDefault(structPtr interface{}) error { } } } + return nil } diff --git a/util/gutil/gutil_z_unit_struct_test.go b/util/gutil/gutil_z_unit_struct_test.go index fe4b62e9753..d9ebde8057b 100755 --- a/util/gutil/gutil_z_unit_struct_test.go +++ b/util/gutil/gutil_z_unit_struct_test.go @@ -39,17 +39,44 @@ func Test_StructToSlice(t *testing.T) { func Test_FillStructWithDefault(t *testing.T) { gtest.C(t, func(t *gtest.T) { - type A struct { - V1 int `d:"1.01"` - V2 string `d:"1.01"` - V3 float32 `d:"1.01"` + type myInt int + type Inner1 struct { + I1V1 int + I1V2 bool `d:"true"` } - a := A{} - err := gutil.FillStructWithDefault(&a) + type Inner2 struct { + I2V1 float64 `d:"1.01"` + } + type Inner3 struct { + Inner1 Inner1 + I3V1 myInt `d:"1"` + } + type Inner4 struct { + } + type Outer struct { + O1 int `d:"1.01"` + O2 string `d:"1.01"` + O3 float32 `d:"1.01"` + *Inner1 + O4 bool `d:"true"` + Inner2 + Inner3 Inner3 + Inner4 *Inner4 + } + + outer := Outer{} + err := gutil.FillStructWithDefault(&outer) t.AssertNil(err) - t.Assert(a.V1, `1`) - t.Assert(a.V2, `1.01`) - t.Assert(a.V3, `1.01`) + t.Assert(outer.O1, 1) + t.Assert(outer.O2, `1.01`) + t.Assert(outer.O3, `1.01`) + t.Assert(outer.O4, true) + t.Assert(outer.Inner1, nil) + t.Assert(outer.Inner2.I2V1, `1.01`) + t.Assert(outer.Inner3.I3V1, 1) + t.Assert(outer.Inner3.Inner1.I1V1, 0) + t.Assert(outer.Inner3.Inner1.I1V2, true) + t.Assert(outer.Inner4, nil) }) } From 984cca8b82752b49d5423e441ac646cfbc9a3fb1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B5=B7=E4=BA=AE?= <739476267@qq.com> Date: Thu, 28 Dec 2023 20:13:21 +0800 Subject: [PATCH 38/52] feat: update dependent redoc js for swagger ui (#3217) --- contrib/rpc/grpcx/grpcx_grpc_server_config.go | 1 + example/httpserver/swagger/main.go | 4 ++ .../swagger_set_template/config.yaml | 4 ++ .../httpserver/swagger_set_template/main.go | 71 +++++++++++++++++++ net/ghttp/ghttp_server_config.go | 5 +- net/ghttp/ghttp_server_config_mess.go | 5 ++ net/ghttp/ghttp_server_swagger.go | 20 +++--- 7 files changed, 98 insertions(+), 12 deletions(-) create mode 100644 example/httpserver/swagger_set_template/config.yaml create mode 100644 example/httpserver/swagger_set_template/main.go diff --git a/contrib/rpc/grpcx/grpcx_grpc_server_config.go b/contrib/rpc/grpcx/grpcx_grpc_server_config.go index 47ab655da92..f5e7c878ef1 100644 --- a/contrib/rpc/grpcx/grpcx_grpc_server_config.go +++ b/contrib/rpc/grpcx/grpcx_grpc_server_config.go @@ -8,6 +8,7 @@ package grpcx import ( "context" + "google.golang.org/grpc" "github.com/gogf/gf/v2/frame/g" diff --git a/example/httpserver/swagger/main.go b/example/httpserver/swagger/main.go index 2105fcba7be..b494c73d2e3 100644 --- a/example/httpserver/swagger/main.go +++ b/example/httpserver/swagger/main.go @@ -8,17 +8,21 @@ import ( "github.com/gogf/gf/v2/net/ghttp" ) +// HelloReq hello request type HelloReq struct { g.Meta `path:"/hello" method:"get" sort:"1"` Name string `v:"required" dc:"Your name"` } +// HelloRes hello response type HelloRes struct { Reply string `dc:"Reply content"` } +// Hello Controller type Hello struct{} +// Say function func (Hello) Say(ctx context.Context, req *HelloReq) (res *HelloRes, err error) { g.Log().Debugf(ctx, `receive say: %+v`, req) res = &HelloRes{ diff --git a/example/httpserver/swagger_set_template/config.yaml b/example/httpserver/swagger_set_template/config.yaml new file mode 100644 index 00000000000..b15f8d00786 --- /dev/null +++ b/example/httpserver/swagger_set_template/config.yaml @@ -0,0 +1,4 @@ +server: + address: ":8199" + openapiPath: "/api.json" + swaggerPath: "/swagger" \ No newline at end of file diff --git a/example/httpserver/swagger_set_template/main.go b/example/httpserver/swagger_set_template/main.go new file mode 100644 index 00000000000..1277de461d4 --- /dev/null +++ b/example/httpserver/swagger_set_template/main.go @@ -0,0 +1,71 @@ +package main + +import ( + "context" + "fmt" + + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/net/ghttp" +) + +// HelloReq hello request +type HelloReq struct { + g.Meta `path:"/hello" method:"get" sort:"1"` + Name string `v:"required" dc:"Your name"` +} + +// HelloRes hello response +type HelloRes struct { + Reply string `dc:"Reply content"` +} + +// Hello Controller +type Hello struct{} + +// Say function +func (Hello) Say(ctx context.Context, req *HelloReq) (res *HelloRes, err error) { + g.Log().Debugf(ctx, `receive say: %+v`, req) + res = &HelloRes{ + Reply: fmt.Sprintf(`Hi %s`, req.Name), + } + return +} + +const ( + MySwaggerUITemplate = ` + + + + + + + SwaggerUI + + + +
+ + + + +` +) + +func main() { + s := g.Server() + s.Use(ghttp.MiddlewareHandlerResponse) + s.Group("/", func(group *ghttp.RouterGroup) { + group.Bind( + new(Hello), + ) + }) + s.SetSwaggerUITemplate(MySwaggerUITemplate) + s.Run() +} diff --git a/net/ghttp/ghttp_server_config.go b/net/ghttp/ghttp_server_config.go index 1319aff6b55..4d3355f7bb4 100644 --- a/net/ghttp/ghttp_server_config.go +++ b/net/ghttp/ghttp_server_config.go @@ -222,8 +222,9 @@ type ServerConfig struct { // API & Swagger. // ====================================================================================================== - OpenApiPath string `json:"openapiPath"` // OpenApiPath specifies the OpenApi specification file path. - SwaggerPath string `json:"swaggerPath"` // SwaggerPath specifies the swagger UI path for route registering. + OpenApiPath string `json:"openapiPath"` // OpenApiPath specifies the OpenApi specification file path. + SwaggerPath string `json:"swaggerPath"` // SwaggerPath specifies the swagger UI path for route registering. + SwaggerUITemplate string `json:"swaggerUITemplate"` // SwaggerUITemplate specifies the swagger UI custom template // ====================================================================================================== // Other. diff --git a/net/ghttp/ghttp_server_config_mess.go b/net/ghttp/ghttp_server_config_mess.go index 23d23e8b345..44113877885 100644 --- a/net/ghttp/ghttp_server_config_mess.go +++ b/net/ghttp/ghttp_server_config_mess.go @@ -32,6 +32,11 @@ func (s *Server) SetSwaggerPath(path string) { s.config.SwaggerPath = path } +// SetSwaggerUITemplate sets the Swagger template for server. +func (s *Server) SetSwaggerUITemplate(swaggerUITemplate string) { + s.config.SwaggerUITemplate = swaggerUITemplate +} + // SetOpenApiPath sets the OpenApiPath for server. func (s *Server) SetOpenApiPath(path string) { s.config.OpenApiPath = path diff --git a/net/ghttp/ghttp_server_swagger.go b/net/ghttp/ghttp_server_swagger.go index 2068e89c1f8..7ef7a19181e 100644 --- a/net/ghttp/ghttp_server_swagger.go +++ b/net/ghttp/ghttp_server_swagger.go @@ -7,16 +7,12 @@ package ghttp import ( - "fmt" - "github.com/gogf/gf/v2/text/gstr" ) const ( - swaggerUIDocName = `redoc.standalone.js` - swaggerUIDocNamePlaceHolder = `{SwaggerUIDocName}` - swaggerUIDocURLPlaceHolder = `{SwaggerUIDocUrl}` - swaggerUITemplate = ` + swaggerUIDocURLPlaceHolder = `{SwaggerUIDocUrl}` + swaggerUITemplate = ` @@ -32,7 +28,7 @@ const ( - + ` @@ -44,10 +40,14 @@ func (s *Server) swaggerUI(r *Request) { if s.config.OpenApiPath == "" { return } + var templateContent = swaggerUITemplate + if s.config.SwaggerUITemplate != "" { + templateContent = s.config.SwaggerUITemplate + } + if r.StaticFile != nil && r.StaticFile.File != nil && r.StaticFile.IsDir { - content := gstr.ReplaceByMap(swaggerUITemplate, map[string]string{ - swaggerUIDocURLPlaceHolder: s.config.OpenApiPath, - swaggerUIDocNamePlaceHolder: gstr.TrimRight(fmt.Sprintf(`//%s%s`, r.Host, r.Server.config.SwaggerPath), "/") + "/" + swaggerUIDocName, + content := gstr.ReplaceByMap(templateContent, map[string]string{ + swaggerUIDocURLPlaceHolder: s.config.OpenApiPath, }) r.Response.Write(content) r.ExitAll() From 63bdf41d40a8804225578bd354d19bbaa53ffd30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B5=B7=E4=BA=AE?= <739476267@qq.com> Date: Thu, 28 Dec 2023 20:18:29 +0800 Subject: [PATCH 39/52] fix #3191 (#3194) --- contrib/nosql/redis/redis.go | 39 ++------------ contrib/nosql/redis/redis_group_generic.go | 48 ++++++++--------- contrib/nosql/redis/redis_group_hash.go | 32 ++++++------ contrib/nosql/redis/redis_group_list.go | 42 +++++++-------- contrib/nosql/redis/redis_group_pubsub.go | 10 ++-- contrib/nosql/redis/redis_group_script.go | 16 +++--- contrib/nosql/redis/redis_group_set.go | 34 ++++++------ contrib/nosql/redis/redis_group_sorted_set.go | 32 ++++++------ contrib/nosql/redis/redis_group_string.go | 42 +++++++-------- contrib/nosql/redis/redis_operation.go | 45 ++++++++++++++++ database/gredis/gredis_adapter.go | 29 ++++++----- example/nosql/redis/adapter/main.go | 52 +++++++++++++++++++ 12 files changed, 247 insertions(+), 174 deletions(-) create mode 100644 contrib/nosql/redis/redis_operation.go create mode 100644 example/nosql/redis/adapter/main.go diff --git a/contrib/nosql/redis/redis.go b/contrib/nosql/redis/redis.go index 5240bd8fd27..248624334d0 100644 --- a/contrib/nosql/redis/redis.go +++ b/contrib/nosql/redis/redis.go @@ -8,20 +8,19 @@ package redis import ( - "context" "crypto/tls" "time" "github.com/redis/go-redis/v9" - "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/database/gredis" - "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/text/gstr" ) // Redis is an implement of Adapter using go-redis. type Redis struct { + gredis.AdapterOperation + client redis.UniversalClient config *gredis.Config } @@ -75,40 +74,12 @@ func New(config *gredis.Config) *Redis { client = redis.NewClient(opts.Simple()) } - return &Redis{ + r := &Redis{ client: client, config: config, } -} - -// Do send a command to the server and returns the received reply. -// It uses json.Marshal for struct/slice/map type values before committing them to redis. -func (r *Redis) Do(ctx context.Context, command string, args ...interface{}) (*gvar.Var, error) { - conn, err := r.Conn(ctx) - if err != nil { - return nil, err - } - defer func() { - _ = conn.Close(ctx) - }() - return conn.Do(ctx, command, args...) -} - -// Close closes the redis connection pool, which will release all connections reserved by this pool. -// It is commonly not necessary to call Close manually. -func (r *Redis) Close(ctx context.Context) (err error) { - if err = r.client.Close(); err != nil { - err = gerror.Wrap(err, `Redis Client Close failed`) - } - return -} - -// Conn retrieves and returns a connection object for continuous operations. -// Note that you should call Close function manually if you do not use this connection any further. -func (r *Redis) Conn(ctx context.Context) (gredis.Conn, error) { - return &Conn{ - redis: r, - }, nil + r.AdapterOperation = r + return r } func fillWithDefaultConfiguration(config *gredis.Config) { diff --git a/contrib/nosql/redis/redis_group_generic.go b/contrib/nosql/redis/redis_group_generic.go index bac0c94eaf9..cdb11256bf5 100644 --- a/contrib/nosql/redis/redis_group_generic.go +++ b/contrib/nosql/redis/redis_group_generic.go @@ -18,13 +18,13 @@ import ( // GroupGeneric provides generic functions of redis. type GroupGeneric struct { - redis *Redis + Operation gredis.AdapterOperation } // GroupGeneric creates and returns GroupGeneric. func (r *Redis) GroupGeneric() gredis.IGroupGeneric { return GroupGeneric{ - redis: r, + Operation: r.AdapterOperation, } } @@ -45,7 +45,7 @@ func (r GroupGeneric) Copy(ctx context.Context, source, destination string, opti if len(option) > 0 { usedOption = option[0] } - v, err := r.redis.Do(ctx, "Copy", mustMergeOptionToArgs( + v, err := r.Operation.Do(ctx, "Copy", mustMergeOptionToArgs( []interface{}{source, destination}, usedOption, )...) return v.Int64(), err @@ -59,7 +59,7 @@ func (r GroupGeneric) Copy(ctx context.Context, source, destination string, opti // // https://redis.io/commands/exists/ func (r GroupGeneric) Exists(ctx context.Context, keys ...string) (int64, error) { - v, err := r.redis.Do(ctx, "Exists", gconv.Interfaces(keys)...) + v, err := r.Operation.Do(ctx, "Exists", gconv.Interfaces(keys)...) return v.Int64(), err } @@ -70,7 +70,7 @@ func (r GroupGeneric) Exists(ctx context.Context, keys ...string) (int64, error) // // https://redis.io/commands/type/ func (r GroupGeneric) Type(ctx context.Context, key string) (string, error) { - v, err := r.redis.Do(ctx, "Type", key) + v, err := r.Operation.Do(ctx, "Type", key) return v.String(), err } @@ -83,7 +83,7 @@ func (r GroupGeneric) Type(ctx context.Context, key string) (string, error) { // // https://redis.io/commands/unlink/ func (r GroupGeneric) Unlink(ctx context.Context, keys ...string) (int64, error) { - v, err := r.redis.Do(ctx, "Unlink", gconv.Interfaces(keys)...) + v, err := r.Operation.Do(ctx, "Unlink", gconv.Interfaces(keys)...) return v.Int64(), err } @@ -96,7 +96,7 @@ func (r GroupGeneric) Unlink(ctx context.Context, keys ...string) (int64, error) // // https://redis.io/commands/rename/ func (r GroupGeneric) Rename(ctx context.Context, key, newKey string) error { - _, err := r.redis.Do(ctx, "Rename", key, newKey) + _, err := r.Operation.Do(ctx, "Rename", key, newKey) return err } @@ -111,7 +111,7 @@ func (r GroupGeneric) Rename(ctx context.Context, key, newKey string) error { // // https://redis.io/commands/renamenx/ func (r GroupGeneric) RenameNX(ctx context.Context, key, newKey string) (int64, error) { - v, err := r.redis.Do(ctx, "RenameNX", key, newKey) + v, err := r.Operation.Do(ctx, "RenameNX", key, newKey) return v.Int64(), err } @@ -126,7 +126,7 @@ func (r GroupGeneric) RenameNX(ctx context.Context, key, newKey string) (int64, // // https://redis.io/commands/move/ func (r GroupGeneric) Move(ctx context.Context, key string, db int) (int64, error) { - v, err := r.redis.Do(ctx, "Move", key, db) + v, err := r.Operation.Do(ctx, "Move", key, db) return v.Int64(), err } @@ -137,7 +137,7 @@ func (r GroupGeneric) Move(ctx context.Context, key string, db int) (int64, erro // // https://redis.io/commands/del/ func (r GroupGeneric) Del(ctx context.Context, keys ...string) (int64, error) { - v, err := r.redis.Do(ctx, "Del", gconv.Interfaces(keys)...) + v, err := r.Operation.Do(ctx, "Del", gconv.Interfaces(keys)...) return v.Int64(), err } @@ -147,7 +147,7 @@ func (r GroupGeneric) Del(ctx context.Context, keys ...string) (int64, error) { // // https://redis.io/commands/randomkey/ func (r GroupGeneric) RandomKey(ctx context.Context) (string, error) { - v, err := r.redis.Do(ctx, "RandomKey") + v, err := r.Operation.Do(ctx, "RandomKey") return v.String(), err } @@ -155,7 +155,7 @@ func (r GroupGeneric) RandomKey(ctx context.Context) (string, error) { // // https://redis.io/commands/dbsize/ func (r GroupGeneric) DBSize(ctx context.Context) (int64, error) { - v, err := r.redis.Do(ctx, "DBSize") + v, err := r.Operation.Do(ctx, "DBSize") return v.Int64(), err } @@ -166,7 +166,7 @@ func (r GroupGeneric) DBSize(ctx context.Context) (int64, error) { // // https://redis.io/commands/keys/ func (r GroupGeneric) Keys(ctx context.Context, pattern string) ([]string, error) { - v, err := r.redis.Do(ctx, "Keys", pattern) + v, err := r.Operation.Do(ctx, "Keys", pattern) return v.Strings(), err } @@ -174,7 +174,7 @@ func (r GroupGeneric) Keys(ctx context.Context, pattern string) ([]string, error // // https://redis.io/commands/flushdb/ func (r GroupGeneric) FlushDB(ctx context.Context, option ...gredis.FlushOp) error { - _, err := r.redis.Do(ctx, "FlushDB", gconv.Interfaces(option)...) + _, err := r.Operation.Do(ctx, "FlushDB", gconv.Interfaces(option)...) return err } @@ -191,7 +191,7 @@ func (r GroupGeneric) FlushDB(ctx context.Context, option ...gredis.FlushOp) err // // https://redis.io/commands/flushall/ func (r GroupGeneric) FlushAll(ctx context.Context, option ...gredis.FlushOp) error { - _, err := r.redis.Do(ctx, "FlushAll", gconv.Interfaces(option)...) + _, err := r.Operation.Do(ctx, "FlushAll", gconv.Interfaces(option)...) return err } @@ -208,7 +208,7 @@ func (r GroupGeneric) Expire(ctx context.Context, key string, seconds int64, opt if len(option) > 0 { usedOption = option[0] } - v, err := r.redis.Do(ctx, "Expire", mustMergeOptionToArgs( + v, err := r.Operation.Do(ctx, "Expire", mustMergeOptionToArgs( []interface{}{key, seconds}, usedOption, )...) return v.Int64(), err @@ -229,7 +229,7 @@ func (r GroupGeneric) ExpireAt(ctx context.Context, key string, time time.Time, if len(option) > 0 { usedOption = option[0] } - v, err := r.redis.Do(ctx, "ExpireAt", mustMergeOptionToArgs( + v, err := r.Operation.Do(ctx, "ExpireAt", mustMergeOptionToArgs( []interface{}{key, gtime.New(time).Timestamp()}, usedOption, )...) return v.Int64(), err @@ -243,7 +243,7 @@ func (r GroupGeneric) ExpireAt(ctx context.Context, key string, time time.Time, // // https://redis.io/commands/expiretime/ func (r GroupGeneric) ExpireTime(ctx context.Context, key string) (*gvar.Var, error) { - return r.redis.Do(ctx, "ExpireTime", key) + return r.Operation.Do(ctx, "ExpireTime", key) } // TTL returns the remaining time to live of a key that has a timeout. @@ -263,7 +263,7 @@ func (r GroupGeneric) ExpireTime(ctx context.Context, key string) (*gvar.Var, er // // https://redis.io/commands/ttl/ func (r GroupGeneric) TTL(ctx context.Context, key string) (int64, error) { - v, err := r.redis.Do(ctx, "TTL", key) + v, err := r.Operation.Do(ctx, "TTL", key) return v.Int64(), err } @@ -276,7 +276,7 @@ func (r GroupGeneric) TTL(ctx context.Context, key string) (int64, error) { // // https://redis.io/commands/persist/ func (r GroupGeneric) Persist(ctx context.Context, key string) (int64, error) { - v, err := r.redis.Do(ctx, "Persist", key) + v, err := r.Operation.Do(ctx, "Persist", key) return v.Int64(), err } @@ -293,7 +293,7 @@ func (r GroupGeneric) PExpire(ctx context.Context, key string, milliseconds int6 if len(option) > 0 { usedOption = option[0] } - v, err := r.redis.Do(ctx, "PExpire", mustMergeOptionToArgs( + v, err := r.Operation.Do(ctx, "PExpire", mustMergeOptionToArgs( []interface{}{key, milliseconds}, usedOption, )...) return v.Int64(), err @@ -308,7 +308,7 @@ func (r GroupGeneric) PExpireAt(ctx context.Context, key string, time time.Time, if len(option) > 0 { usedOption = option[0] } - v, err := r.redis.Do(ctx, "PExpireAt", mustMergeOptionToArgs( + v, err := r.Operation.Do(ctx, "PExpireAt", mustMergeOptionToArgs( []interface{}{key, gtime.New(time).TimestampMilli()}, usedOption, )...) return v.Int64(), err @@ -322,7 +322,7 @@ func (r GroupGeneric) PExpireAt(ctx context.Context, key string, time time.Time, // // https://redis.io/commands/pexpiretime/ func (r GroupGeneric) PExpireTime(ctx context.Context, key string) (*gvar.Var, error) { - return r.redis.Do(ctx, "PExpireTime", key) + return r.Operation.Do(ctx, "PExpireTime", key) } // PTTL like TTL this command returns the remaining time to live of a key that has an expired set, @@ -336,6 +336,6 @@ func (r GroupGeneric) PExpireTime(ctx context.Context, key string) (*gvar.Var, e // // https://redis.io/commands/pttl/ func (r GroupGeneric) PTTL(ctx context.Context, key string) (int64, error) { - v, err := r.redis.Do(ctx, "PTTL", key) + v, err := r.Operation.Do(ctx, "PTTL", key) return v.Int64(), err } diff --git a/contrib/nosql/redis/redis_group_hash.go b/contrib/nosql/redis/redis_group_hash.go index 7967321290e..75b3147430c 100644 --- a/contrib/nosql/redis/redis_group_hash.go +++ b/contrib/nosql/redis/redis_group_hash.go @@ -16,13 +16,13 @@ import ( // GroupHash is the redis group object for hash operations. type GroupHash struct { - redis *Redis + Operation gredis.AdapterOperation } // GroupHash creates and returns a redis group object for hash operations. func (r *Redis) GroupHash() gredis.IGroupHash { return GroupHash{ - redis: r, + Operation: r.AdapterOperation, } } @@ -38,7 +38,7 @@ func (r GroupHash) HSet(ctx context.Context, key string, fields map[string]inter for k, v := range fields { s = append(s, k, v) } - v, err := r.redis.Do(ctx, "HSet", s...) + v, err := r.Operation.Do(ctx, "HSet", s...) return v.Int64(), err } @@ -52,7 +52,7 @@ func (r GroupHash) HSet(ctx context.Context, key string, fields map[string]inter // // https://redis.io/commands/hsetnx/ func (r GroupHash) HSetNX(ctx context.Context, key, field string, value interface{}) (int64, error) { - v, err := r.redis.Do(ctx, "HSetNX", key, field, value) + v, err := r.Operation.Do(ctx, "HSetNX", key, field, value) return v.Int64(), err } @@ -62,7 +62,7 @@ func (r GroupHash) HSetNX(ctx context.Context, key, field string, value interfac // // https://redis.io/commands/hget/ func (r GroupHash) HGet(ctx context.Context, key, field string) (*gvar.Var, error) { - v, err := r.redis.Do(ctx, "HGet", key, field) + v, err := r.Operation.Do(ctx, "HGet", key, field) return v, err } @@ -74,7 +74,7 @@ func (r GroupHash) HGet(ctx context.Context, key, field string) (*gvar.Var, erro // // https://redis.io/commands/hstrlen/ func (r GroupHash) HStrLen(ctx context.Context, key, field string) (int64, error) { - v, err := r.redis.Do(ctx, "HSTRLEN", key, field) + v, err := r.Operation.Do(ctx, "HSTRLEN", key, field) return v.Int64(), err } @@ -86,7 +86,7 @@ func (r GroupHash) HStrLen(ctx context.Context, key, field string) (int64, error // // https://redis.io/commands/hexists/ func (r GroupHash) HExists(ctx context.Context, key, field string) (int64, error) { - v, err := r.redis.Do(ctx, "HExists", key, field) + v, err := r.Operation.Do(ctx, "HExists", key, field) return v.Int64(), err } @@ -98,7 +98,7 @@ func (r GroupHash) HExists(ctx context.Context, key, field string) (int64, error // // https://redis.io/commands/hdel/ func (r GroupHash) HDel(ctx context.Context, key string, fields ...string) (int64, error) { - v, err := r.redis.Do(ctx, "HDel", append([]interface{}{key}, gconv.Interfaces(fields)...)...) + v, err := r.Operation.Do(ctx, "HDel", append([]interface{}{key}, gconv.Interfaces(fields)...)...) return v.Int64(), err } @@ -106,7 +106,7 @@ func (r GroupHash) HDel(ctx context.Context, key string, fields ...string) (int6 // // https://redis.io/commands/hlen/ func (r GroupHash) HLen(ctx context.Context, key string) (int64, error) { - v, err := r.redis.Do(ctx, "HLen", key) + v, err := r.Operation.Do(ctx, "HLen", key) return v.Int64(), err } @@ -118,7 +118,7 @@ func (r GroupHash) HLen(ctx context.Context, key string) (int64, error) { // // https://redis.io/commands/hincrby/ func (r GroupHash) HIncrBy(ctx context.Context, key, field string, increment int64) (int64, error) { - v, err := r.redis.Do(ctx, "HIncrBy", key, field, increment) + v, err := r.Operation.Do(ctx, "HIncrBy", key, field, increment) return v.Int64(), err } @@ -138,7 +138,7 @@ func (r GroupHash) HIncrBy(ctx context.Context, key, field string, increment int // // https://redis.io/commands/hincrbyfloat/ func (r GroupHash) HIncrByFloat(ctx context.Context, key, field string, increment float64) (float64, error) { - v, err := r.redis.Do(ctx, "HIncrByFloat", key, field, increment) + v, err := r.Operation.Do(ctx, "HIncrByFloat", key, field, increment) return v.Float64(), err } @@ -152,7 +152,7 @@ func (r GroupHash) HMSet(ctx context.Context, key string, fields map[string]inte for k, v := range fields { s = append(s, k, v) } - _, err := r.redis.Do(ctx, "HMSet", s...) + _, err := r.Operation.Do(ctx, "HMSet", s...) return err } @@ -163,7 +163,7 @@ func (r GroupHash) HMSet(ctx context.Context, key string, fields map[string]inte // // https://redis.io/commands/hmget/ func (r GroupHash) HMGet(ctx context.Context, key string, fields ...string) (gvar.Vars, error) { - v, err := r.redis.Do(ctx, "HMGet", append([]interface{}{key}, gconv.Interfaces(fields)...)...) + v, err := r.Operation.Do(ctx, "HMGet", append([]interface{}{key}, gconv.Interfaces(fields)...)...) return v.Vars(), err } @@ -171,7 +171,7 @@ func (r GroupHash) HMGet(ctx context.Context, key string, fields ...string) (gva // // https://redis.io/commands/hkeys/ func (r GroupHash) HKeys(ctx context.Context, key string) ([]string, error) { - v, err := r.redis.Do(ctx, "HKeys", key) + v, err := r.Operation.Do(ctx, "HKeys", key) return v.Strings(), err } @@ -179,7 +179,7 @@ func (r GroupHash) HKeys(ctx context.Context, key string) ([]string, error) { // // https://redis.io/commands/hvals/ func (r GroupHash) HVals(ctx context.Context, key string) (gvar.Vars, error) { - v, err := r.redis.Do(ctx, "HVals", key) + v, err := r.Operation.Do(ctx, "HVals", key) return v.Vars(), err } @@ -189,6 +189,6 @@ func (r GroupHash) HVals(ctx context.Context, key string) (gvar.Vars, error) { // // https://redis.io/commands/hgetall/ func (r GroupHash) HGetAll(ctx context.Context, key string) (*gvar.Var, error) { - v, err := r.redis.Do(ctx, "HGetAll", key) + v, err := r.Operation.Do(ctx, "HGetAll", key) return v, err } diff --git a/contrib/nosql/redis/redis_group_list.go b/contrib/nosql/redis/redis_group_list.go index 829b5d84a7a..6767e723fbe 100644 --- a/contrib/nosql/redis/redis_group_list.go +++ b/contrib/nosql/redis/redis_group_list.go @@ -16,13 +16,13 @@ import ( // GroupList is the redis group list object. type GroupList struct { - redis *Redis + Operation gredis.AdapterOperation } // GroupList creates and returns a redis group object for list operations. func (r *Redis) GroupList() gredis.IGroupList { return GroupList{ - redis: r, + Operation: r.AdapterOperation, } } @@ -35,7 +35,7 @@ func (r *Redis) GroupList() gredis.IGroupList { // // https://redis.io/commands/lpush/ func (r GroupList) LPush(ctx context.Context, key string, values ...interface{}) (int64, error) { - v, err := r.redis.Do(ctx, "LPush", append([]interface{}{key}, values...)...) + v, err := r.Operation.Do(ctx, "LPush", append([]interface{}{key}, values...)...) return v.Int64(), err } @@ -48,7 +48,7 @@ func (r GroupList) LPush(ctx context.Context, key string, values ...interface{}) // // https://redis.io/commands/lpushx func (r GroupList) LPushX(ctx context.Context, key string, element interface{}, elements ...interface{}) (int64, error) { - v, err := r.redis.Do(ctx, "LPushX", append([]interface{}{key, element}, elements...)...) + v, err := r.Operation.Do(ctx, "LPushX", append([]interface{}{key, element}, elements...)...) return v.Int64(), err } @@ -67,7 +67,7 @@ func (r GroupList) LPushX(ctx context.Context, key string, element interface{}, // // https://redis.io/commands/rpush func (r GroupList) RPush(ctx context.Context, key string, values ...interface{}) (int64, error) { - v, err := r.redis.Do(ctx, "RPush", append([]interface{}{key}, values...)...) + v, err := r.Operation.Do(ctx, "RPush", append([]interface{}{key}, values...)...) return v.Int64(), err } @@ -81,7 +81,7 @@ func (r GroupList) RPush(ctx context.Context, key string, values ...interface{}) // // https://redis.io/commands/rpushx func (r GroupList) RPushX(ctx context.Context, key string, value interface{}) (int64, error) { - v, err := r.redis.Do(ctx, "RPushX", key, value) + v, err := r.Operation.Do(ctx, "RPushX", key, value) return v.Int64(), err } @@ -103,9 +103,9 @@ func (r GroupList) RPushX(ctx context.Context, key string, value interface{}) (i // https://redis.io/commands/lpop func (r GroupList) LPop(ctx context.Context, key string, count ...int) (*gvar.Var, error) { if len(count) > 0 { - return r.redis.Do(ctx, "LPop", key, count[0]) + return r.Operation.Do(ctx, "LPop", key, count[0]) } - return r.redis.Do(ctx, "LPop", key) + return r.Operation.Do(ctx, "LPop", key) } // RPop remove and returns the last element of the list stored at key. @@ -126,9 +126,9 @@ func (r GroupList) LPop(ctx context.Context, key string, count ...int) (*gvar.Va // https://redis.io/commands/rpop func (r GroupList) RPop(ctx context.Context, key string, count ...int) (*gvar.Var, error) { if len(count) > 0 { - return r.redis.Do(ctx, "RPop", key, count[0]) + return r.Operation.Do(ctx, "RPop", key, count[0]) } - return r.redis.Do(ctx, "RPop", key) + return r.Operation.Do(ctx, "RPop", key) } // LRem removes the first count occurrences of elements equal to value from the list stored at key. @@ -137,7 +137,7 @@ func (r GroupList) RPop(ctx context.Context, key string, count ...int) (*gvar.Va // // https://redis.io/commands/lrem/ func (r GroupList) LRem(ctx context.Context, key string, count int64, value interface{}) (int64, error) { - v, err := r.redis.Do(ctx, "LRem", key, count, value) + v, err := r.Operation.Do(ctx, "LRem", key, count, value) return v.Int64(), err } @@ -148,7 +148,7 @@ func (r GroupList) LRem(ctx context.Context, key string, count int64, value inte // // https://redis.io/commands/llen func (r GroupList) LLen(ctx context.Context, key string) (int64, error) { - v, err := r.redis.Do(ctx, "LLen", key) + v, err := r.Operation.Do(ctx, "LLen", key) return v.Int64(), err } @@ -163,7 +163,7 @@ func (r GroupList) LLen(ctx context.Context, key string) (int64, error) { // // https://redis.io/commands/lindex func (r GroupList) LIndex(ctx context.Context, key string, index int64) (*gvar.Var, error) { - return r.redis.Do(ctx, "LIndex", key, index) + return r.Operation.Do(ctx, "LIndex", key, index) } // LInsert inserts element in the list stored at key either before or after the reference value pivot. @@ -174,7 +174,7 @@ func (r GroupList) LIndex(ctx context.Context, key string, index int64) (*gvar.V // // https://redis.io/commands/linsert/ func (r GroupList) LInsert(ctx context.Context, key string, op gredis.LInsertOp, pivot, value interface{}) (int64, error) { - v, err := r.redis.Do(ctx, "LInsert", key, string(op), pivot, value) + v, err := r.Operation.Do(ctx, "LInsert", key, string(op), pivot, value) return v.Int64(), err } @@ -184,7 +184,7 @@ func (r GroupList) LInsert(ctx context.Context, key string, op gredis.LInsertOp, // // https://redis.io/commands/lset/ func (r GroupList) LSet(ctx context.Context, key string, index int64, value interface{}) (*gvar.Var, error) { - return r.redis.Do(ctx, "LSet", key, index, value) + return r.Operation.Do(ctx, "LSet", key, index, value) } // LRange returns the specified elements of the list stored at key. @@ -196,7 +196,7 @@ func (r GroupList) LSet(ctx context.Context, key string, index int64, value inte // // https://redis.io/commands/lrange/ func (r GroupList) LRange(ctx context.Context, key string, start, stop int64) (gvar.Vars, error) { - v, err := r.redis.Do(ctx, "LRange", key, start, stop) + v, err := r.Operation.Do(ctx, "LRange", key, start, stop) return v.Vars(), err } @@ -206,7 +206,7 @@ func (r GroupList) LRange(ctx context.Context, key string, start, stop int64) (g // // https://redis.io/commands/ltrim/ func (r GroupList) LTrim(ctx context.Context, key string, start, stop int64) error { - _, err := r.redis.Do(ctx, "LTrim", key, start, stop) + _, err := r.Operation.Do(ctx, "LTrim", key, start, stop) return err } @@ -221,7 +221,7 @@ func (r GroupList) LTrim(ctx context.Context, key string, start, stop int64) err // // https://redis.io/commands/blpop/ func (r GroupList) BLPop(ctx context.Context, timeout int64, keys ...string) (gvar.Vars, error) { - v, err := r.redis.Do(ctx, "BLPop", append(gconv.Interfaces(keys), timeout)...) + v, err := r.Operation.Do(ctx, "BLPop", append(gconv.Interfaces(keys), timeout)...) return v.Vars(), err } @@ -235,7 +235,7 @@ func (r GroupList) BLPop(ctx context.Context, timeout int64, keys ...string) (gv // // https://redis.io/commands/brpop/ func (r GroupList) BRPop(ctx context.Context, timeout int64, keys ...string) (gvar.Vars, error) { - v, err := r.redis.Do(ctx, "BRPop", append(gconv.Interfaces(keys), timeout)...) + v, err := r.Operation.Do(ctx, "BRPop", append(gconv.Interfaces(keys), timeout)...) return v.Vars(), err } @@ -244,7 +244,7 @@ func (r GroupList) BRPop(ctx context.Context, timeout int64, keys ...string) (gv // // https://redis.io/commands/rpoplpush/ func (r GroupList) RPopLPush(ctx context.Context, source, destination string) (*gvar.Var, error) { - return r.redis.Do(ctx, "RPopLPush", source, destination) + return r.Operation.Do(ctx, "RPopLPush", source, destination) } // BRPopLPush is the blocking variant of RPopLPush. @@ -259,5 +259,5 @@ func (r GroupList) RPopLPush(ctx context.Context, source, destination string) (* // // https://redis.io/commands/brpoplpush/ func (r GroupList) BRPopLPush(ctx context.Context, source, destination string, timeout int64) (*gvar.Var, error) { - return r.redis.Do(ctx, "BRPopLPush", source, destination, timeout) + return r.Operation.Do(ctx, "BRPopLPush", source, destination, timeout) } diff --git a/contrib/nosql/redis/redis_group_pubsub.go b/contrib/nosql/redis/redis_group_pubsub.go index bef48b27436..1badd05e179 100644 --- a/contrib/nosql/redis/redis_group_pubsub.go +++ b/contrib/nosql/redis/redis_group_pubsub.go @@ -14,13 +14,13 @@ import ( // GroupPubSub provides pub/sub functions for redis. type GroupPubSub struct { - redis *Redis + Operation gredis.AdapterOperation } // GroupPubSub creates and returns GroupPubSub. func (r *Redis) GroupPubSub() gredis.IGroupPubSub { return GroupPubSub{ - redis: r, + Operation: r.AdapterOperation, } } @@ -36,7 +36,7 @@ func (r *Redis) GroupPubSub() gredis.IGroupPubSub { // // https://redis.io/commands/publish/ func (r GroupPubSub) Publish(ctx context.Context, channel string, message interface{}) (int64, error) { - v, err := r.redis.Do(ctx, "Publish", channel, message) + v, err := r.Operation.Do(ctx, "Publish", channel, message) return v.Int64(), err } @@ -46,7 +46,7 @@ func (r GroupPubSub) Publish(ctx context.Context, channel string, message interf func (r GroupPubSub) Subscribe( ctx context.Context, channel string, channels ...string, ) (gredis.Conn, []*gredis.Subscription, error) { - conn, err := r.redis.Conn(ctx) + conn, err := r.Operation.Conn(ctx) if err != nil { return nil, nil, err } @@ -70,7 +70,7 @@ func (r GroupPubSub) Subscribe( func (r GroupPubSub) PSubscribe( ctx context.Context, pattern string, patterns ...string, ) (gredis.Conn, []*gredis.Subscription, error) { - conn, err := r.redis.Conn(ctx) + conn, err := r.Operation.Conn(ctx) if err != nil { return nil, nil, err } diff --git a/contrib/nosql/redis/redis_group_script.go b/contrib/nosql/redis/redis_group_script.go index 8a38309cca2..a074748dfa9 100644 --- a/contrib/nosql/redis/redis_group_script.go +++ b/contrib/nosql/redis/redis_group_script.go @@ -16,13 +16,13 @@ import ( // GroupScript provides script functions for redis. type GroupScript struct { - redis *Redis + Operation gredis.AdapterOperation } // GroupScript creates and returns GroupScript. func (r *Redis) GroupScript() gredis.IGroupScript { return GroupScript{ - redis: r, + Operation: r.AdapterOperation, } } @@ -33,7 +33,7 @@ func (r GroupScript) Eval(ctx context.Context, script string, numKeys int64, key var s = []interface{}{script, numKeys} s = append(s, gconv.Interfaces(keys)...) s = append(s, args...) - v, err := r.redis.Do(ctx, "Eval", s...) + v, err := r.Operation.Do(ctx, "Eval", s...) return v, err } @@ -47,7 +47,7 @@ func (r GroupScript) EvalSha(ctx context.Context, sha1 string, numKeys int64, ke var s = []interface{}{sha1, numKeys} s = append(s, gconv.Interfaces(keys)...) s = append(s, args...) - v, err := r.redis.Do(ctx, "EvalSha", s...) + v, err := r.Operation.Do(ctx, "EvalSha", s...) return v, err } @@ -57,7 +57,7 @@ func (r GroupScript) EvalSha(ctx context.Context, sha1 string, numKeys int64, ke // // https://redis.io/commands/script-load/ func (r GroupScript) ScriptLoad(ctx context.Context, script string) (string, error) { - v, err := r.redis.Do(ctx, "Script", "Load", script) + v, err := r.Operation.Do(ctx, "Script", "Load", script) return v.String(), err } @@ -75,7 +75,7 @@ func (r GroupScript) ScriptExists(ctx context.Context, sha1 string, sha1s ...str ) s = append(s, "Exists") s = append(s, sha1Array...) - result, err := r.redis.Do(ctx, "Script", s...) + result, err := r.Operation.Do(ctx, "Script", s...) var ( m = make(map[string]bool) resultArray = result.Vars() @@ -99,7 +99,7 @@ func (r GroupScript) ScriptFlush(ctx context.Context, option ...gredis.ScriptFlu s = append(s, mustMergeOptionToArgs( []interface{}{}, usedOption, )...) - _, err := r.redis.Do(ctx, "Script", s...) + _, err := r.Operation.Do(ctx, "Script", s...) return err } @@ -108,6 +108,6 @@ func (r GroupScript) ScriptFlush(ctx context.Context, option ...gredis.ScriptFlu // // https://redis.io/commands/script-kill/ func (r GroupScript) ScriptKill(ctx context.Context) error { - _, err := r.redis.Do(ctx, "Script", "Kill") + _, err := r.Operation.Do(ctx, "Script", "Kill") return err } diff --git a/contrib/nosql/redis/redis_group_set.go b/contrib/nosql/redis/redis_group_set.go index a46bd457eab..631f2d9ff07 100644 --- a/contrib/nosql/redis/redis_group_set.go +++ b/contrib/nosql/redis/redis_group_set.go @@ -16,13 +16,13 @@ import ( // GroupSet provides set functions for redis. type GroupSet struct { - redis *Redis + Operation gredis.AdapterOperation } // GroupSet creates and returns GroupSet. func (r *Redis) GroupSet() gredis.IGroupSet { return GroupSet{ - redis: r, + Operation: r.AdapterOperation, } } @@ -40,7 +40,7 @@ func (r GroupSet) SAdd(ctx context.Context, key string, member interface{}, memb var s = []interface{}{key} s = append(s, member) s = append(s, members...) - v, err := r.redis.Do(ctx, "SAdd", s...) + v, err := r.Operation.Do(ctx, "SAdd", s...) return v.Int64(), err } @@ -52,7 +52,7 @@ func (r GroupSet) SAdd(ctx context.Context, key string, member interface{}, memb // // https://redis.io/commands/sismember/ func (r GroupSet) SIsMember(ctx context.Context, key string, member interface{}) (int64, error) { - v, err := r.redis.Do(ctx, "SIsMember", key, member) + v, err := r.Operation.Do(ctx, "SIsMember", key, member) return v.Int64(), err } @@ -73,7 +73,7 @@ func (r GroupSet) SIsMember(ctx context.Context, key string, member interface{}) func (r GroupSet) SPop(ctx context.Context, key string, count ...int) (*gvar.Var, error) { var s = []interface{}{key} s = append(s, gconv.Interfaces(count)...) - v, err := r.redis.Do(ctx, "SPop", s...) + v, err := r.Operation.Do(ctx, "SPop", s...) return v, err } @@ -95,7 +95,7 @@ func (r GroupSet) SPop(ctx context.Context, key string, count ...int) (*gvar.Var func (r GroupSet) SRandMember(ctx context.Context, key string, count ...int) (*gvar.Var, error) { var s = []interface{}{key} s = append(s, gconv.Interfaces(count)...) - v, err := r.redis.Do(ctx, "SRandMember", s...) + v, err := r.Operation.Do(ctx, "SRandMember", s...) return v, err } @@ -112,7 +112,7 @@ func (r GroupSet) SRem(ctx context.Context, key string, member interface{}, memb var s = []interface{}{key} s = append(s, member) s = append(s, members...) - v, err := r.redis.Do(ctx, "SRem", s...) + v, err := r.Operation.Do(ctx, "SRem", s...) return v.Int64(), err } @@ -131,7 +131,7 @@ func (r GroupSet) SRem(ctx context.Context, key string, member interface{}, memb // // https://redis.io/commands/smove/ func (r GroupSet) SMove(ctx context.Context, source, destination string, member interface{}) (int64, error) { - v, err := r.redis.Do(ctx, "SMove", source, destination, member) + v, err := r.Operation.Do(ctx, "SMove", source, destination, member) return v.Int64(), err } @@ -141,7 +141,7 @@ func (r GroupSet) SMove(ctx context.Context, source, destination string, member // // https://redis.io/commands/scard/ func (r GroupSet) SCard(ctx context.Context, key string) (int64, error) { - v, err := r.redis.Do(ctx, "SCard", key) + v, err := r.Operation.Do(ctx, "SCard", key) return v.Int64(), err } @@ -152,7 +152,7 @@ func (r GroupSet) SCard(ctx context.Context, key string) (int64, error) { // // https://redis.io/commands/smembers/ func (r GroupSet) SMembers(ctx context.Context, key string) (gvar.Vars, error) { - v, err := r.redis.Do(ctx, "SMembers", key) + v, err := r.Operation.Do(ctx, "SMembers", key) return v.Vars(), err } @@ -167,7 +167,7 @@ func (r GroupSet) SMembers(ctx context.Context, key string) (gvar.Vars, error) { func (r GroupSet) SMIsMember(ctx context.Context, key, member interface{}, members ...interface{}) ([]int, error) { var s = []interface{}{key, member} s = append(s, members...) - v, err := r.redis.Do(ctx, "SMIsMember", s...) + v, err := r.Operation.Do(ctx, "SMIsMember", s...) return v.Ints(), err } @@ -179,7 +179,7 @@ func (r GroupSet) SMIsMember(ctx context.Context, key, member interface{}, membe func (r GroupSet) SInter(ctx context.Context, key string, keys ...string) (gvar.Vars, error) { var s = []interface{}{key} s = append(s, gconv.Interfaces(keys)...) - v, err := r.redis.Do(ctx, "SInter", s...) + v, err := r.Operation.Do(ctx, "SInter", s...) return v.Vars(), err } @@ -194,7 +194,7 @@ func (r GroupSet) SInter(ctx context.Context, key string, keys ...string) (gvar. func (r GroupSet) SInterStore(ctx context.Context, destination string, key string, keys ...string) (int64, error) { var s = []interface{}{destination, key} s = append(s, gconv.Interfaces(keys)...) - v, err := r.redis.Do(ctx, "SInterStore", s...) + v, err := r.Operation.Do(ctx, "SInterStore", s...) return v.Int64(), err } @@ -206,7 +206,7 @@ func (r GroupSet) SInterStore(ctx context.Context, destination string, key strin func (r GroupSet) SUnion(ctx context.Context, key string, keys ...string) (gvar.Vars, error) { var s = []interface{}{key} s = append(s, gconv.Interfaces(keys)...) - v, err := r.redis.Do(ctx, "SUnion", s...) + v, err := r.Operation.Do(ctx, "SUnion", s...) return v.Vars(), err } @@ -220,7 +220,7 @@ func (r GroupSet) SUnion(ctx context.Context, key string, keys ...string) (gvar. func (r GroupSet) SUnionStore(ctx context.Context, destination, key string, keys ...string) (int64, error) { var s = []interface{}{destination, key} s = append(s, gconv.Interfaces(keys)...) - v, err := r.redis.Do(ctx, "SUnionStore", s...) + v, err := r.Operation.Do(ctx, "SUnionStore", s...) return v.Int64(), err } @@ -233,7 +233,7 @@ func (r GroupSet) SUnionStore(ctx context.Context, destination, key string, keys func (r GroupSet) SDiff(ctx context.Context, key string, keys ...string) (gvar.Vars, error) { var s = []interface{}{key} s = append(s, gconv.Interfaces(keys)...) - v, err := r.redis.Do(ctx, "SDiff", s...) + v, err := r.Operation.Do(ctx, "SDiff", s...) return v.Vars(), err } @@ -247,6 +247,6 @@ func (r GroupSet) SDiff(ctx context.Context, key string, keys ...string) (gvar.V func (r GroupSet) SDiffStore(ctx context.Context, destination string, key string, keys ...string) (int64, error) { var s = []interface{}{destination, key} s = append(s, gconv.Interfaces(keys)...) - v, err := r.redis.Do(ctx, "SDiffStore", s...) + v, err := r.Operation.Do(ctx, "SDiffStore", s...) return v.Int64(), err } diff --git a/contrib/nosql/redis/redis_group_sorted_set.go b/contrib/nosql/redis/redis_group_sorted_set.go index dd9e4b7f15e..667118a231f 100644 --- a/contrib/nosql/redis/redis_group_sorted_set.go +++ b/contrib/nosql/redis/redis_group_sorted_set.go @@ -15,13 +15,13 @@ import ( // GroupSortedSet provides sorted set functions for redis. type GroupSortedSet struct { - redis *Redis + Operation gredis.AdapterOperation } // GroupSortedSet creates and returns GroupSortedSet. func (r *Redis) GroupSortedSet() gredis.IGroupSortedSet { return GroupSortedSet{ - redis: r, + Operation: r.AdapterOperation, } } @@ -55,7 +55,7 @@ func (r GroupSortedSet) ZAdd( for _, item := range members { s = append(s, item.Score, item.Member) } - v, err := r.redis.Do(ctx, "ZAdd", s...) + v, err := r.Operation.Do(ctx, "ZAdd", s...) return v, err } @@ -67,7 +67,7 @@ func (r GroupSortedSet) ZAdd( // // https://redis.io/commands/zscore/ func (r GroupSortedSet) ZScore(ctx context.Context, key string, member interface{}) (float64, error) { - v, err := r.redis.Do(ctx, "ZScore", key, member) + v, err := r.Operation.Do(ctx, "ZScore", key, member) return v.Float64(), err } @@ -84,7 +84,7 @@ func (r GroupSortedSet) ZScore(ctx context.Context, key string, member interface // // https://redis.io/commands/zincrby/ func (r GroupSortedSet) ZIncrBy(ctx context.Context, key string, increment float64, member interface{}) (float64, error) { - v, err := r.redis.Do(ctx, "ZIncrBy", key, increment, member) + v, err := r.Operation.Do(ctx, "ZIncrBy", key, increment, member) return v.Float64(), err } @@ -94,7 +94,7 @@ func (r GroupSortedSet) ZIncrBy(ctx context.Context, key string, increment float // // https://redis.io/commands/zcard/ func (r GroupSortedSet) ZCard(ctx context.Context, key string) (int64, error) { - v, err := r.redis.Do(ctx, "ZCard", key) + v, err := r.Operation.Do(ctx, "ZCard", key) return v.Int64(), err } @@ -109,7 +109,7 @@ func (r GroupSortedSet) ZCard(ctx context.Context, key string) (int64, error) { // // https://redis.io/commands/zcount/ func (r GroupSortedSet) ZCount(ctx context.Context, key string, min, max string) (int64, error) { - v, err := r.redis.Do(ctx, "ZCount", key, min, max) + v, err := r.Operation.Do(ctx, "ZCount", key, min, max) return v.Int64(), err } @@ -124,7 +124,7 @@ func (r GroupSortedSet) ZRange(ctx context.Context, key string, start, stop int6 if len(option) > 0 { usedOption = option[0] } - v, err := r.redis.Do(ctx, "ZRange", mustMergeOptionToArgs( + v, err := r.Operation.Do(ctx, "ZRange", mustMergeOptionToArgs( []interface{}{key, start, stop}, usedOption, )...) return v.Vars(), err @@ -144,7 +144,7 @@ func (r GroupSortedSet) ZRevRange(ctx context.Context, key string, start, stop i if len(option) > 0 { usedOption = option[0] } - return r.redis.Do(ctx, "ZRevRange", mustMergeOptionToArgs( + return r.Operation.Do(ctx, "ZRevRange", mustMergeOptionToArgs( []interface{}{key, start, stop}, usedOption, )...) } @@ -160,7 +160,7 @@ func (r GroupSortedSet) ZRevRange(ctx context.Context, key string, start, stop i // // https://redis.io/commands/zrank/ func (r GroupSortedSet) ZRank(ctx context.Context, key string, member interface{}) (int64, error) { - v, err := r.redis.Do(ctx, "ZRank", key, member) + v, err := r.Operation.Do(ctx, "ZRank", key, member) return v.Int64(), err } @@ -175,7 +175,7 @@ func (r GroupSortedSet) ZRank(ctx context.Context, key string, member interface{ // // https://redis.io/commands/zrevrank/ func (r GroupSortedSet) ZRevRank(ctx context.Context, key string, member interface{}) (int64, error) { - v, err := r.redis.Do(ctx, "ZRevRank", key, member) + v, err := r.Operation.Do(ctx, "ZRevRank", key, member) return v.Int64(), err } @@ -191,7 +191,7 @@ func (r GroupSortedSet) ZRem(ctx context.Context, key string, member interface{} var s = []interface{}{key} s = append(s, member) s = append(s, members...) - v, err := r.redis.Do(ctx, "ZRem", s...) + v, err := r.Operation.Do(ctx, "ZRem", s...) return v.Int64(), err } @@ -206,7 +206,7 @@ func (r GroupSortedSet) ZRem(ctx context.Context, key string, member interface{} // // https://redis.io/commands/zremrangebyrank/ func (r GroupSortedSet) ZRemRangeByRank(ctx context.Context, key string, start, stop int64) (int64, error) { - v, err := r.redis.Do(ctx, "ZRemRangeByRank", key, start, stop) + v, err := r.Operation.Do(ctx, "ZRemRangeByRank", key, start, stop) return v.Int64(), err } @@ -217,7 +217,7 @@ func (r GroupSortedSet) ZRemRangeByRank(ctx context.Context, key string, start, // // https://redis.io/commands/zremrangebyscore/ func (r GroupSortedSet) ZRemRangeByScore(ctx context.Context, key string, min, max string) (int64, error) { - v, err := r.redis.Do(ctx, "ZRemRangeByScore", key, min, max) + v, err := r.Operation.Do(ctx, "ZRemRangeByScore", key, min, max) return v.Int64(), err } @@ -232,7 +232,7 @@ func (r GroupSortedSet) ZRemRangeByScore(ctx context.Context, key string, min, m // // https://redis.io/commands/zremrangebylex/ func (r GroupSortedSet) ZRemRangeByLex(ctx context.Context, key string, min, max string) (int64, error) { - v, err := r.redis.Do(ctx, "ZRemRangeByLex", key, min, max) + v, err := r.Operation.Do(ctx, "ZRemRangeByLex", key, min, max) return v.Int64(), err } @@ -249,6 +249,6 @@ func (r GroupSortedSet) ZRemRangeByLex(ctx context.Context, key string, min, max // // https://redis.io/commands/zlexcount/ func (r GroupSortedSet) ZLexCount(ctx context.Context, key, min, max string) (int64, error) { - v, err := r.redis.Do(ctx, "ZLexCount", key, min, max) + v, err := r.Operation.Do(ctx, "ZLexCount", key, min, max) return v.Int64(), err } diff --git a/contrib/nosql/redis/redis_group_string.go b/contrib/nosql/redis/redis_group_string.go index 0fd714af368..1cac4ad054e 100644 --- a/contrib/nosql/redis/redis_group_string.go +++ b/contrib/nosql/redis/redis_group_string.go @@ -16,13 +16,13 @@ import ( // GroupString is the function group manager for string operations. type GroupString struct { - redis *Redis + Operation gredis.AdapterOperation } // GroupString is the redis group object for string operations. func (r *Redis) GroupString() gredis.IGroupString { return GroupString{ - redis: r, + Operation: r.AdapterOperation, } } @@ -36,7 +36,7 @@ func (r GroupString) Set(ctx context.Context, key string, value interface{}, opt if len(option) > 0 { usedOption = option[0] } - return r.redis.Do(ctx, "Set", mustMergeOptionToArgs( + return r.Operation.Do(ctx, "Set", mustMergeOptionToArgs( []interface{}{key, value}, usedOption, )...) } @@ -52,7 +52,7 @@ func (r GroupString) Set(ctx context.Context, key string, value interface{}, opt // // https://redis.io/commands/setnx/ func (r GroupString) SetNX(ctx context.Context, key string, value interface{}) (bool, error) { - v, err := r.redis.Do(ctx, "SetNX", key, value) + v, err := r.Operation.Do(ctx, "SetNX", key, value) return v.Bool(), err } @@ -70,7 +70,7 @@ func (r GroupString) SetNX(ctx context.Context, key string, value interface{}) ( // // https://redis.io/commands/setex/ func (r GroupString) SetEX(ctx context.Context, key string, value interface{}, ttlInSeconds int64) error { - _, err := r.redis.Do(ctx, "SetEX", key, ttlInSeconds, value) + _, err := r.Operation.Do(ctx, "SetEX", key, ttlInSeconds, value) return err } @@ -79,7 +79,7 @@ func (r GroupString) SetEX(ctx context.Context, key string, value interface{}, t // // https://redis.io/commands/get/ func (r GroupString) Get(ctx context.Context, key string) (*gvar.Var, error) { - return r.redis.Do(ctx, "Get", key) + return r.Operation.Do(ctx, "Get", key) } // GetDel gets the value of key and delete the key. @@ -88,7 +88,7 @@ func (r GroupString) Get(ctx context.Context, key string) (*gvar.Var, error) { // // https://redis.io/commands/getdel/ func (r GroupString) GetDel(ctx context.Context, key string) (*gvar.Var, error) { - return r.redis.Do(ctx, "GetDel", key) + return r.Operation.Do(ctx, "GetDel", key) } // GetEX is similar to GET, but is a write command with additional options. @@ -99,7 +99,7 @@ func (r GroupString) GetEX(ctx context.Context, key string, option ...gredis.Get if len(option) > 0 { usedOption = option[0] } - return r.redis.Do(ctx, "GetEX", mustMergeOptionToArgs( + return r.Operation.Do(ctx, "GetEX", mustMergeOptionToArgs( []interface{}{key}, usedOption, )...) } @@ -110,7 +110,7 @@ func (r GroupString) GetEX(ctx context.Context, key string, option ...gredis.Get // // https://redis.io/commands/getset/ func (r GroupString) GetSet(ctx context.Context, key string, value interface{}) (*gvar.Var, error) { - return r.redis.Do(ctx, "GetSet", key, value) + return r.Operation.Do(ctx, "GetSet", key, value) } // StrLen returns the length of the string value stored at key. @@ -120,7 +120,7 @@ func (r GroupString) GetSet(ctx context.Context, key string, value interface{}) // // https://redis.io/commands/strlen/ func (r GroupString) StrLen(ctx context.Context, key string) (int64, error) { - v, err := r.redis.Do(ctx, "StrLen", key) + v, err := r.Operation.Do(ctx, "StrLen", key) return v.Int64(), err } @@ -130,7 +130,7 @@ func (r GroupString) StrLen(ctx context.Context, key string) (int64, error) { // // https://redis.io/commands/append/ func (r GroupString) Append(ctx context.Context, key string, value string) (int64, error) { - v, err := r.redis.Do(ctx, "Append", key, value) + v, err := r.Operation.Do(ctx, "Append", key, value) return v.Int64(), err } @@ -143,7 +143,7 @@ func (r GroupString) Append(ctx context.Context, key string, value string) (int6 // // https://redis.io/commands/setrange/ func (r GroupString) SetRange(ctx context.Context, key string, offset int64, value string) (int64, error) { - v, err := r.redis.Do(ctx, "SetRange", key, offset, value) + v, err := r.Operation.Do(ctx, "SetRange", key, offset, value) return v.Int64(), err } @@ -155,7 +155,7 @@ func (r GroupString) SetRange(ctx context.Context, key string, offset int64, val // // https://redis.io/commands/getrange/ func (r GroupString) GetRange(ctx context.Context, key string, start, end int64) (string, error) { - v, err := r.redis.Do(ctx, "GetRange", key, start, end) + v, err := r.Operation.Do(ctx, "GetRange", key, start, end) return v.String(), err } @@ -166,7 +166,7 @@ func (r GroupString) GetRange(ctx context.Context, key string, start, end int64) // // https://redis.io/commands/incr/ func (r GroupString) Incr(ctx context.Context, key string) (int64, error) { - v, err := r.redis.Do(ctx, "Incr", key) + v, err := r.Operation.Do(ctx, "Incr", key) return v.Int64(), err } @@ -178,7 +178,7 @@ func (r GroupString) Incr(ctx context.Context, key string) (int64, error) { // // https://redis.io/commands/incrby/ func (r GroupString) IncrBy(ctx context.Context, key string, increment int64) (int64, error) { - v, err := r.redis.Do(ctx, "IncrBy", key, increment) + v, err := r.Operation.Do(ctx, "IncrBy", key, increment) return v.Int64(), err } @@ -186,7 +186,7 @@ func (r GroupString) IncrBy(ctx context.Context, key string, increment int64) (i // // https://redis.io/commands/incrbyfloat/ func (r GroupString) IncrByFloat(ctx context.Context, key string, increment float64) (float64, error) { - v, err := r.redis.Do(ctx, "IncrByFloat", key, increment) + v, err := r.Operation.Do(ctx, "IncrByFloat", key, increment) return v.Float64(), err } @@ -194,7 +194,7 @@ func (r GroupString) IncrByFloat(ctx context.Context, key string, increment floa // // https://redis.io/commands/decr/ func (r GroupString) Decr(ctx context.Context, key string) (int64, error) { - v, err := r.redis.Do(ctx, "Decr", key) + v, err := r.Operation.Do(ctx, "Decr", key) return v.Int64(), err } @@ -202,7 +202,7 @@ func (r GroupString) Decr(ctx context.Context, key string) (int64, error) { // // https://redis.io/commands/decrby/ func (r GroupString) DecrBy(ctx context.Context, key string, decrement int64) (int64, error) { - v, err := r.redis.Do(ctx, "DecrBy", key, decrement) + v, err := r.Operation.Do(ctx, "DecrBy", key, decrement) return v.Int64(), err } @@ -219,7 +219,7 @@ func (r GroupString) MSet(ctx context.Context, keyValueMap map[string]interface{ for k, v := range keyValueMap { args = append(args, k, v) } - _, err := r.redis.Do(ctx, "MSet", args...) + _, err := r.Operation.Do(ctx, "MSet", args...) return err } @@ -233,7 +233,7 @@ func (r GroupString) MSetNX(ctx context.Context, keyValueMap map[string]interfac for k, v := range keyValueMap { args = append(args, k, v) } - v, err := r.redis.Do(ctx, "MSetNX", args...) + v, err := r.Operation.Do(ctx, "MSetNX", args...) return v.Bool(), err } @@ -242,7 +242,7 @@ func (r GroupString) MSetNX(ctx context.Context, keyValueMap map[string]interfac // https://redis.io/commands/mget/ func (r GroupString) MGet(ctx context.Context, keys ...string) (map[string]*gvar.Var, error) { var result = make(map[string]*gvar.Var) - v, err := r.redis.Do(ctx, "MGet", gconv.Interfaces(keys)...) + v, err := r.Operation.Do(ctx, "MGet", gconv.Interfaces(keys)...) if err == nil { values := v.Vars() for i, key := range keys { diff --git a/contrib/nosql/redis/redis_operation.go b/contrib/nosql/redis/redis_operation.go new file mode 100644 index 00000000000..191ca866f6b --- /dev/null +++ b/contrib/nosql/redis/redis_operation.go @@ -0,0 +1,45 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +package redis + +import ( + "context" + + "github.com/gogf/gf/v2/container/gvar" + "github.com/gogf/gf/v2/database/gredis" + "github.com/gogf/gf/v2/errors/gerror" +) + +// Do send a command to the server and returns the received reply. +// It uses json.Marshal for struct/slice/map type values before committing them to redis. +func (r *Redis) Do(ctx context.Context, command string, args ...interface{}) (*gvar.Var, error) { + conn, err := r.Conn(ctx) + if err != nil { + return nil, err + } + defer func() { + _ = conn.Close(ctx) + }() + return conn.Do(ctx, command, args...) +} + +// Close closes the redis connection pool, which will release all connections reserved by this pool. +// It is commonly not necessary to call Close manually. +func (r *Redis) Close(ctx context.Context) (err error) { + if err = r.client.Close(); err != nil { + err = gerror.Wrap(err, `Operation Client Close failed`) + } + return +} + +// Conn retrieves and returns a connection object for continuous operations. +// Note that you should call Close function manually if you do not use this connection any further. +func (r *Redis) Conn(ctx context.Context) (gredis.Conn, error) { + return &Conn{ + redis: r, + }, nil +} diff --git a/database/gredis/gredis_adapter.go b/database/gredis/gredis_adapter.go index ad63bdbe913..c941ab0f816 100644 --- a/database/gredis/gredis_adapter.go +++ b/database/gredis/gredis_adapter.go @@ -15,7 +15,24 @@ import ( // Adapter is an interface for universal redis operations. type Adapter interface { AdapterGroup + AdapterOperation +} + +// AdapterGroup is an interface managing group operations for redis. +type AdapterGroup interface { + GroupGeneric() IGroupGeneric + GroupHash() IGroupHash + GroupList() IGroupList + GroupPubSub() IGroupPubSub + GroupScript() IGroupScript + GroupSet() IGroupSet + GroupSortedSet() IGroupSortedSet + GroupString() IGroupString +} +// AdapterOperation is the core operation functions for redis. +// These functions can be easily overwritten by custom implements. +type AdapterOperation interface { // Do send a command to the server and returns the received reply. // It uses json.Marshal for struct/slice/map type values before committing them to redis. Do(ctx context.Context, command string, args ...interface{}) (*gvar.Var, error) @@ -40,18 +57,6 @@ type Conn interface { Close(ctx context.Context) (err error) } -// AdapterGroup is an interface managing group operations for redis. -type AdapterGroup interface { - GroupGeneric() IGroupGeneric - GroupHash() IGroupHash - GroupList() IGroupList - GroupPubSub() IGroupPubSub - GroupScript() IGroupScript - GroupSet() IGroupSet - GroupSortedSet() IGroupSortedSet - GroupString() IGroupString -} - // ConnCommand is an interface managing some operations bound to certain connection. type ConnCommand interface { // Subscribe subscribes the client to the specified channels. diff --git a/example/nosql/redis/adapter/main.go b/example/nosql/redis/adapter/main.go new file mode 100644 index 00000000000..96b7cc827ab --- /dev/null +++ b/example/nosql/redis/adapter/main.go @@ -0,0 +1,52 @@ +package main + +import ( + "context" + "fmt" + + "github.com/gogf/gf/contrib/nosql/redis/v2" + + "github.com/gogf/gf/v2/container/gvar" + "github.com/gogf/gf/v2/database/gredis" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/os/gctx" +) + +var ( + ctx = gctx.New() + group = "cache" + config = gredis.Config{ + Address: "127.0.0.1:6379", + Db: 1, + } +) + +// MyRedis description +type MyRedis struct { + *redis.Redis +} + +// Do implements and overwrites the underlying function Do from Adapter. +func (r *MyRedis) Do(ctx context.Context, command string, args ...interface{}) (*gvar.Var, error) { + fmt.Println("MyRedis Do:", command, args) + return r.Redis.Do(ctx, command, args...) +} + +func main() { + gredis.RegisterAdapterFunc(func(config *gredis.Config) gredis.Adapter { + r := &MyRedis{redis.New(config)} + r.AdapterOperation = r // This is necessary. + return r + }) + gredis.SetConfig(&config, group) + + _, err := g.Redis(group).Set(ctx, "key", "value") + if err != nil { + g.Log().Fatal(ctx, err) + } + value, err := g.Redis(group).Get(ctx, "key") + if err != nil { + g.Log().Fatal(ctx, err) + } + fmt.Println(value.String()) +} From 4876ae0e2b269f51cb42d27ce498a425e4a2e52a Mon Sep 17 00:00:00 2001 From: cy <710058301@qq.com> Date: Tue, 2 Jan 2024 20:10:57 +0800 Subject: [PATCH 40/52] fix:gz files are compressed repeatedly every time tick (#3236) --- os/glog/glog_logger_rotate.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/os/glog/glog_logger_rotate.go b/os/glog/glog_logger_rotate.go index 61192df5ba1..4df261d1a53 100644 --- a/os/glog/glog_logger_rotate.go +++ b/os/glog/glog_logger_rotate.go @@ -153,7 +153,7 @@ func (l *Logger) rotateChecksTimely(ctx context.Context) { ) for _, file := range files { // ignore backup file - if gregex.IsMatchString(`.+\.\d{20}\.log`, gfile.Basename(file)) { + if gregex.IsMatchString(`.+\.\d{20}\.log`, gfile.Basename(file)) || gfile.ExtName(file) == "gz" { continue } // ignore not matching file From 6abd8bd864646a449fb06aa6ab600e4ee3e4fe8e Mon Sep 17 00:00:00 2001 From: John Guo Date: Tue, 2 Jan 2024 20:16:51 +0800 Subject: [PATCH 41/52] comments update for package gstr (#3233) --- container/garray/garray_normal_int.go | 18 ++++++++-- container/gqueue/gqueue_z_unit_test.go | 6 ++-- os/gfile/gfile.go | 28 +++++++++------ text/gstr/gstr_array.go | 3 ++ text/gstr/gstr_case.go | 29 ++++++++++++++- text/gstr/gstr_convert.go | 28 ++++++++++++--- text/gstr/gstr_create.go | 3 ++ text/gstr/gstr_sub.go | 50 ++++++++++++++++++++++---- 8 files changed, 139 insertions(+), 26 deletions(-) diff --git a/container/garray/garray_normal_int.go b/container/garray/garray_normal_int.go index a1473317018..16e59a71c94 100644 --- a/container/garray/garray_normal_int.go +++ b/container/garray/garray_normal_int.go @@ -173,7 +173,11 @@ func (a *IntArray) InsertBefore(index int, values ...int) error { a.mu.Lock() defer a.mu.Unlock() if index < 0 || index >= len(a.array) { - return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array)) + return gerror.NewCodef( + gcode.CodeInvalidParameter, + "index %d out of array range %d", + index, len(a.array), + ) } rear := append([]int{}, a.array[index:]...) a.array = append(a.array[0:index], values...) @@ -186,7 +190,11 @@ func (a *IntArray) InsertAfter(index int, values ...int) error { a.mu.Lock() defer a.mu.Unlock() if index < 0 || index >= len(a.array) { - return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array)) + return gerror.NewCodef( + gcode.CodeInvalidParameter, + "index %d out of array range %d", + index, len(a.array), + ) } rear := append([]int{}, a.array[index+1:]...) a.array = append(a.array[0:index+1], values...) @@ -583,7 +591,11 @@ func (a *IntArray) Fill(startIndex int, num int, value int) error { a.mu.Lock() defer a.mu.Unlock() if startIndex < 0 || startIndex > len(a.array) { - return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", startIndex, len(a.array)) + return gerror.NewCodef( + gcode.CodeInvalidParameter, + "index %d out of array range %d", + startIndex, len(a.array), + ) } for i := startIndex; i < startIndex+num; i++ { if i > len(a.array)-1 { diff --git a/container/gqueue/gqueue_z_unit_test.go b/container/gqueue/gqueue_z_unit_test.go index 95ca6761f09..cf87f7a48bb 100644 --- a/container/gqueue/gqueue_z_unit_test.go +++ b/container/gqueue/gqueue_z_unit_test.go @@ -75,7 +75,8 @@ func TestQueue_Close(t *testing.T) { q1 := gqueue.New() q1.Push(1) q1.Push(2) - time.Sleep(time.Millisecond) + // wait sync to channel + time.Sleep(10 * time.Millisecond) t.Assert(q1.Len(), 2) q1.Close() }) @@ -83,7 +84,8 @@ func TestQueue_Close(t *testing.T) { q1 := gqueue.New(2) q1.Push(1) q1.Push(2) - time.Sleep(time.Millisecond) + // wait sync to channel + time.Sleep(10 * time.Millisecond) t.Assert(q1.Len(), 2) q1.Close() }) diff --git a/os/gfile/gfile.go b/os/gfile/gfile.go index 3c9db89e55f..7222ed900fb 100644 --- a/os/gfile/gfile.go +++ b/os/gfile/gfile.go @@ -352,17 +352,19 @@ func SelfDir() string { // Trailing path separators are removed before extracting the last element. // If the path is empty, Base returns ".". // If the path consists entirely of separators, Basename returns a single separator. +// // Example: -// /var/www/file.js -> file.js -// file.js -> file.js +// Basename("/var/www/file.js") -> file.js +// Basename("file.js") -> file.js func Basename(path string) string { return filepath.Base(path) } // Name returns the last element of path without file extension. +// // Example: -// /var/www/file.js -> file -// file.js -> file +// Name("/var/www/file.js") -> file +// Name("file.js") -> file func Name(path string) string { base := filepath.Base(path) if i := strings.LastIndexByte(base, '.'); i != -1 { @@ -378,6 +380,10 @@ func Name(path string) string { // If the `path` is ".", Dir treats the path as current working directory. // If the `path` consists entirely of separators, Dir returns a single separator. // The returned path does not end in a separator unless it is the root directory. +// +// Example: +// Dir("/var/www/file.js") -> "/var/www" +// Dir("file.js") -> "." func Dir(path string) string { if path == "." { return filepath.Dir(RealPath(path)) @@ -416,9 +422,10 @@ func IsEmpty(path string) bool { // in the final element of path; it is empty if there is // no dot. // Note: the result contains symbol '.'. -// Eg: -// main.go => .go -// api.json => .json +// +// Example: +// Ext("main.go") => .go +// Ext("api.json") => .json func Ext(path string) string { ext := filepath.Ext(path) if p := strings.IndexByte(ext, '?'); p != -1 { @@ -429,9 +436,10 @@ func Ext(path string) string { // ExtName is like function Ext, which returns the file name extension used by path, // but the result does not contain symbol '.'. -// Eg: -// main.go => go -// api.json => json +// +// Example: +// ExtName("main.go") => go +// ExtName("api.json") => json func ExtName(path string) string { return strings.TrimLeft(Ext(path), ".") } diff --git a/text/gstr/gstr_array.go b/text/gstr/gstr_array.go index 1e467023731..c4c0f78e09b 100644 --- a/text/gstr/gstr_array.go +++ b/text/gstr/gstr_array.go @@ -24,6 +24,9 @@ func InArray(a []string, s string) bool { } // PrefixArray adds `prefix` string for each item of `array`. +// +// Example: +// PrefixArray(["a","b"], "gf_") -> ["gf_a", "gf_b"] func PrefixArray(array []string, prefix string) { for k, v := range array { array[k] = prefix + v diff --git a/text/gstr/gstr_case.go b/text/gstr/gstr_case.go index 714f44a5a7f..252db6195bb 100644 --- a/text/gstr/gstr_case.go +++ b/text/gstr/gstr_case.go @@ -104,11 +104,17 @@ func CaseConvert(s string, caseType CaseType) string { } // CaseCamel converts a string to CamelCase. +// +// Example: +// CaseCamel("any_kind_of_string") -> AnyKindOfString func CaseCamel(s string) string { return toCamelInitCase(s, true) } // CaseCamelLower converts a string to lowerCamelCase. +// +// Example: +// CaseCamelLower("any_kind_of_string") -> anyKindOfString func CaseCamelLower(s string) string { if s == "" { return s @@ -120,17 +126,26 @@ func CaseCamelLower(s string) string { } // CaseSnake converts a string to snake_case. +// +// Example: +// CaseSnake("AnyKindOfString") -> any_kind_of_string func CaseSnake(s string) string { return CaseDelimited(s, '_') } // CaseSnakeScreaming converts a string to SNAKE_CASE_SCREAMING. +// +// Example: +// CaseSnakeScreaming("AnyKindOfString") -> ANY_KIND_OF_STRING func CaseSnakeScreaming(s string) string { return CaseDelimitedScreaming(s, '_', true) } // CaseSnakeFirstUpper converts a string like "RGBCodeMd5" to "rgb_code_md5". // TODO for efficiency should change regexp to traversing string in future. +// +// Example: +// CaseSnakeFirstUpper("RGBCodeMd5") -> rgb_code_md5 func CaseSnakeFirstUpper(word string, underscore ...string) string { replace := "_" if len(underscore) > 0 { @@ -157,22 +172,34 @@ func CaseSnakeFirstUpper(word string, underscore ...string) string { return TrimLeft(word, replace) } -// CaseKebab converts a string to kebab-case +// CaseKebab converts a string to kebab-case. +// +// Example: +// CaseKebab("AnyKindOfString") -> any-kind-of-string func CaseKebab(s string) string { return CaseDelimited(s, '-') } // CaseKebabScreaming converts a string to KEBAB-CASE-SCREAMING. +// +// Example: +// CaseKebab("AnyKindOfString") -> ANY-KIND-OF-STRING func CaseKebabScreaming(s string) string { return CaseDelimitedScreaming(s, '-', true) } // CaseDelimited converts a string to snake.case.delimited. +// +// Example: +// CaseDelimited("AnyKindOfString", '.') -> any.kind.of.string func CaseDelimited(s string, del byte) string { return CaseDelimitedScreaming(s, del, false) } // CaseDelimitedScreaming converts a string to DELIMITED.SCREAMING.CASE or delimited.screaming.case. +// +// Example: +// CaseDelimitedScreaming("AnyKindOfString", '.') -> ANY.KIND.OF.STRING func CaseDelimitedScreaming(s string, del uint8, screaming bool) string { s = addWordBoundariesToNumbers(s) s = strings.Trim(s, " ") diff --git a/text/gstr/gstr_convert.go b/text/gstr/gstr_convert.go index fc29f11cd84..4bf221b31cf 100644 --- a/text/gstr/gstr_convert.go +++ b/text/gstr/gstr_convert.go @@ -24,18 +24,26 @@ var ( ) // Chr return the ascii string of a number(0-255). +// +// Example: +// Chr(65) -> "A" func Chr(ascii int) string { return string([]byte{byte(ascii % 256)}) } // Ord converts the first byte of a string to a value between 0 and 255. +// +// Example: +// Chr("A") -> 65 func Ord(char string) int { return int(char[0]) } // OctStr converts string container octal string to its original string, // for example, to Chinese string. -// Eg: `\346\200\241` -> 怡 +// +// Example: +// OctStr("\346\200\241") -> 怡 func OctStr(str string) string { return octReg.ReplaceAllStringFunc( str, @@ -47,6 +55,9 @@ func OctStr(str string) string { } // Reverse returns a string which is the reverse of `str`. +// +// Example: +// Reverse("123456") -> "654321" func Reverse(str string) string { runes := []rune(str) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { @@ -56,10 +67,14 @@ func Reverse(str string) string { } // NumberFormat formats a number with grouped thousands. -// `decimals`: Sets the number of decimal points. -// `decPoint`: Sets the separator for the decimal point. -// `thousandsSep`: Sets the thousands' separator. +// Parameter `decimals`: Sets the number of decimal points. +// Parameter `decPoint`: Sets the separator for the decimal point. +// Parameter `thousandsSep`: Sets the thousands' separator. // See http://php.net/manual/en/function.number-format.php. +// +// Example: +// NumberFormat(1234.56, 2, ".", "") -> 1234,56 +// NumberFormat(1234.56, 2, ",", " ") -> 1 234,56 func NumberFormat(number float64, decimals int, decPoint, thousandsSep string) string { neg := false if number < 0 { @@ -103,6 +118,11 @@ func NumberFormat(number float64, decimals int, decPoint, thousandsSep string) s // Shuffle randomly shuffles a string. // It considers parameter `str` as unicode string. +// +// Example: +// Shuffle("123456") -> "325164" +// Shuffle("123456") -> "231546" +// ... func Shuffle(str string) string { runes := []rune(str) s := make([]rune, len(runes)) diff --git a/text/gstr/gstr_create.go b/text/gstr/gstr_create.go index 8e5ff31294a..047463ae9b5 100644 --- a/text/gstr/gstr_create.go +++ b/text/gstr/gstr_create.go @@ -9,6 +9,9 @@ package gstr import "strings" // Repeat returns a new string consisting of multiplier copies of the string input. +// +// Example: +// Repeat("a", 3) -> "aaa" func Repeat(input string, multiplier int) string { return strings.Repeat(input, multiplier) } diff --git a/text/gstr/gstr_sub.go b/text/gstr/gstr_sub.go index a3f4a702422..847d21979cd 100644 --- a/text/gstr/gstr_sub.go +++ b/text/gstr/gstr_sub.go @@ -10,8 +10,12 @@ import "strings" // Str returns part of `haystack` string starting from and including // the first occurrence of `needle` to the end of `haystack`. -// See http://php.net/manual/en/function.strstr.php. -// Eg: Str("12345", "3") => "345" +// +// This function performs exactly as function SubStr, but to implement the same function +// as PHP: http://php.net/manual/en/function.strstr.php. +// +// Example: +// Str("av.mp4", ".") -> ".mp4" func Str(haystack string, needle string) string { if needle == "" { return "" @@ -25,7 +29,12 @@ func Str(haystack string, needle string) string { // StrEx returns part of `haystack` string starting from and excluding // the first occurrence of `needle` to the end of `haystack`. -// Eg: StrEx("12345", "3") => "45" +// +// This function performs exactly as function SubStrEx, but to implement the same function +// as PHP: http://php.net/manual/en/function.strstr.php. +// +// Example: +// StrEx("av.mp4", ".") -> "mp4" func StrEx(haystack string, needle string) string { if s := Str(haystack, needle); s != "" { return s[1:] @@ -35,7 +44,9 @@ func StrEx(haystack string, needle string) string { // StrTill returns part of `haystack` string ending to and including // the first occurrence of `needle` from the start of `haystack`. -// Eg: StrTill("12345", "3") => "123" +// +// Example: +// StrTill("av.mp4", ".") -> "av." func StrTill(haystack string, needle string) string { pos := strings.Index(haystack, needle) if pos == NotFoundIndex || pos == 0 { @@ -46,7 +57,9 @@ func StrTill(haystack string, needle string) string { // StrTillEx returns part of `haystack` string ending to and excluding // the first occurrence of `needle` from the start of `haystack`. -// Eg: StrTillEx("12345", "3") => "12" +// +// Example: +// StrTillEx("av.mp4", ".") -> "av" func StrTillEx(haystack string, needle string) string { pos := strings.Index(haystack, needle) if pos == NotFoundIndex || pos == 0 { @@ -57,7 +70,9 @@ func StrTillEx(haystack string, needle string) string { // SubStr returns a portion of string `str` specified by the `start` and `length` parameters. // The parameter `length` is optional, it uses the length of `str` in default. -// Eg: SubStr("12345", 1, 2) => "23" +// +// Example: +// SubStr("123456", 1, 2) -> "23" func SubStr(str string, start int, length ...int) (substr string) { strLength := len(str) if start < 0 { @@ -96,6 +111,9 @@ func SubStr(str string, start int, length ...int) (substr string) { // SubStrRune returns a portion of string `str` specified by the `start` and `length` parameters. // SubStrRune considers parameter `str` as unicode string. // The parameter `length` is optional, it uses the length of `str` in default. +// +// Example: +// SubStrRune("一起学习吧!", 2, 2) -> "学习" func SubStrRune(str string, start int, length ...int) (substr string) { // Converting to []rune to support unicode. var ( @@ -137,6 +155,10 @@ func SubStrRune(str string, start int, length ...int) (substr string) { // StrLimit returns a portion of string `str` specified by `length` parameters, if the length // of `str` is greater than `length`, then the `suffix` will be appended to the result string. +// +// Example: +// StrLimit("123456", 3) -> "123..." +// StrLimit("123456", 3, "~") -> "123~" func StrLimit(str string, length int, suffix ...string) string { if len(str) < length { return str @@ -151,6 +173,10 @@ func StrLimit(str string, length int, suffix ...string) string { // StrLimitRune returns a portion of string `str` specified by `length` parameters, if the length // of `str` is greater than `length`, then the `suffix` will be appended to the result string. // StrLimitRune considers parameter `str` as unicode string. +// +// Example: +// StrLimitRune("一起学习吧!", 2) -> "一起..." +// StrLimitRune("一起学习吧!", 2, "~") -> "一起~" func StrLimitRune(str string, length int, suffix ...string) string { runes := []rune(str) if len(runes) < length { @@ -165,6 +191,9 @@ func StrLimitRune(str string, length int, suffix ...string) string { // SubStrFrom returns a portion of string `str` starting from first occurrence of and including `need` // to the end of `str`. +// +// Example: +// SubStrFrom("av.mp4", ".") -> ".mp4" func SubStrFrom(str string, need string) (substr string) { pos := Pos(str, need) if pos < 0 { @@ -175,6 +204,9 @@ func SubStrFrom(str string, need string) (substr string) { // SubStrFromEx returns a portion of string `str` starting from first occurrence of and excluding `need` // to the end of `str`. +// +// Example: +// SubStrFromEx("av.mp4", ".") -> "mp4" func SubStrFromEx(str string, need string) (substr string) { pos := Pos(str, need) if pos < 0 { @@ -185,6 +217,9 @@ func SubStrFromEx(str string, need string) (substr string) { // SubStrFromR returns a portion of string `str` starting from last occurrence of and including `need` // to the end of `str`. +// +// Example: +// SubStrFromR("/dev/vda", "/") -> "/vda" func SubStrFromR(str string, need string) (substr string) { pos := PosR(str, need) if pos < 0 { @@ -195,6 +230,9 @@ func SubStrFromR(str string, need string) (substr string) { // SubStrFromREx returns a portion of string `str` starting from last occurrence of and excluding `need` // to the end of `str`. +// +// Example: +// SubStrFromREx("/dev/vda", "/") -> "vda" func SubStrFromREx(str string, need string) (substr string) { pos := PosR(str, need) if pos < 0 { From 1e21b61a19c452768d48a3323a39694a0706fd3e Mon Sep 17 00:00:00 2001 From: John Guo Date: Tue, 2 Jan 2024 20:17:54 +0800 Subject: [PATCH 42/52] fix typo flie -> file (#3228) --- 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 | 8 +++---- os/gfile/gfile_z_example_replace_test.go | 12 +++++------ os/gfile/gfile_z_example_scan_test.go | 26 +++++++++++------------ os/gfile/gfile_z_example_search_test.go | 4 ++-- os/gfile/gfile_z_example_size_test.go | 6 +++--- 7 files changed, 40 insertions(+), 40 deletions(-) diff --git a/os/gfile/gfile_z_example_cache_test.go b/os/gfile/gfile_z_example_cache_test.go index a729dce461e..0c2a7dff073 100644 --- a/os/gfile/gfile_z_example_cache_test.go +++ b/os/gfile/gfile_z_example_cache_test.go @@ -16,7 +16,7 @@ import ( func ExampleGetContentsWithCache() { // init var ( - fileName = "gflie_example.txt" + fileName = "gfile_example.txt" 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 5d9ebb81e17..c8310a8a0aa 100644 --- a/os/gfile/gfile_z_example_contents_test.go +++ b/os/gfile/gfile_z_example_contents_test.go @@ -15,7 +15,7 @@ import ( func ExampleGetContents() { // init var ( - fileName = "gflie_example.txt" + fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) @@ -34,7 +34,7 @@ func ExampleGetContents() { func ExampleGetBytes() { // init var ( - fileName = "gflie_example.txt" + fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) @@ -53,7 +53,7 @@ func ExampleGetBytes() { func ExamplePutContents() { // init var ( - fileName = "gflie_example.txt" + fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) @@ -72,7 +72,7 @@ func ExamplePutContents() { func ExamplePutBytes() { // init var ( - fileName = "gflie_example.txt" + fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) @@ -90,7 +90,7 @@ func ExamplePutBytes() { func ExamplePutContentsAppend() { // init var ( - fileName = "gflie_example.txt" + fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) @@ -116,7 +116,7 @@ func ExamplePutContentsAppend() { func ExamplePutBytesAppend() { // init var ( - fileName = "gflie_example.txt" + fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) @@ -141,7 +141,7 @@ func ExamplePutBytesAppend() { func ExampleGetNextCharOffsetByPath() { // init var ( - fileName = "gflie_example.txt" + fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) @@ -160,7 +160,7 @@ func ExampleGetNextCharOffsetByPath() { func ExampleGetBytesTilCharByPath() { // init var ( - fileName = "gflie_example.txt" + fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) @@ -178,7 +178,7 @@ func ExampleGetBytesTilCharByPath() { func ExampleGetBytesByTwoOffsetsByPath() { // init var ( - fileName = "gflie_example.txt" + fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) @@ -196,7 +196,7 @@ func ExampleGetBytesByTwoOffsetsByPath() { func ExampleReadLines() { // init var ( - fileName = "gflie_example.txt" + fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) @@ -219,7 +219,7 @@ func ExampleReadLines() { func ExampleReadLinesBytes() { // init var ( - fileName = "gflie_example.txt" + fileName = "gfile_example.txt" 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 6136990cd1b..9276029c67f 100644 --- a/os/gfile/gfile_z_example_copy_test.go +++ b/os/gfile/gfile_z_example_copy_test.go @@ -15,12 +15,12 @@ import ( func ExampleCopy() { // init var ( - srcFileName = "gflie_example.txt" + srcFileName = "gfile_example.txt" srcTempDir = gfile.Temp("gfile_example_copy_src") srcTempFile = gfile.Join(srcTempDir, srcFileName) // copy file - dstFileName = "gflie_example_copy.txt" + dstFileName = "gfile_example_copy.txt" dstTempFile = gfile.Join(srcTempDir, dstFileName) // copy dir @@ -47,6 +47,6 @@ func ExampleCopy() { // Output: // goframe example copy - // gflie_example.txt - // gflie_example_copy.txt + // gfile_example.txt + // gfile_example_copy.txt } diff --git a/os/gfile/gfile_z_example_replace_test.go b/os/gfile/gfile_z_example_replace_test.go index 0f9e654fa1d..2c1a13d9a5f 100644 --- a/os/gfile/gfile_z_example_replace_test.go +++ b/os/gfile/gfile_z_example_replace_test.go @@ -16,7 +16,7 @@ import ( func ExampleReplaceFile() { // init var ( - fileName = "gflie_example.txt" + fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_replace") tempFile = gfile.Join(tempDir, fileName) ) @@ -40,7 +40,7 @@ func ExampleReplaceFile() { func ExampleReplaceFileFunc() { // init var ( - fileName = "gflie_example.txt" + fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_replace") tempFile = gfile.Join(tempDir, fileName) ) @@ -68,7 +68,7 @@ func ExampleReplaceFileFunc() { func ExampleReplaceDir() { // init var ( - fileName = "gflie_example.txt" + fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_replace") tempFile = gfile.Join(tempDir, fileName) ) @@ -80,7 +80,7 @@ func ExampleReplaceDir() { fmt.Println(gfile.GetContents(tempFile)) // It replaces content of all files under specified directory recursively. - gfile.ReplaceDir("content", "replace word", tempDir, "gflie_example.txt", true) + gfile.ReplaceDir("content", "replace word", tempDir, "gfile_example.txt", true) // read contents fmt.Println(gfile.GetContents(tempFile)) @@ -93,7 +93,7 @@ func ExampleReplaceDir() { func ExampleReplaceDirFunc() { // init var ( - fileName = "gflie_example.txt" + fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_replace") tempFile = gfile.Join(tempDir, fileName) ) @@ -109,7 +109,7 @@ func ExampleReplaceDirFunc() { // Replace with regular match reg, _ := regexp.Compile(`\d{3}`) return reg.ReplaceAllString(content, "[num]") - }, tempDir, "gflie_example.txt", true) + }, tempDir, "gfile_example.txt", true) fmt.Println(gfile.GetContents(tempFile)) diff --git a/os/gfile/gfile_z_example_scan_test.go b/os/gfile/gfile_z_example_scan_test.go index 386f3c08028..063f6a5194d 100644 --- a/os/gfile/gfile_z_example_scan_test.go +++ b/os/gfile/gfile_z_example_scan_test.go @@ -15,7 +15,7 @@ import ( func ExampleScanDir() { // init var ( - fileName = "gflie_example.txt" + fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_scan_dir") tempFile = gfile.Join(tempDir, fileName) @@ -34,15 +34,15 @@ func ExampleScanDir() { } // Output: - // gflie_example.txt + // gfile_example.txt // sub_dir - // gflie_example.txt + // gfile_example.txt } func ExampleScanDirFile() { // init var ( - fileName = "gflie_example.txt" + fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_scan_dir_file") tempFile = gfile.Join(tempDir, fileName) @@ -61,14 +61,14 @@ func ExampleScanDirFile() { } // Output: - // gflie_example.txt - // gflie_example.txt + // gfile_example.txt + // gfile_example.txt } func ExampleScanDirFunc() { // init var ( - fileName = "gflie_example.txt" + fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_scan_dir_func") tempFile = gfile.Join(tempDir, fileName) @@ -83,7 +83,7 @@ func ExampleScanDirFunc() { // scans directory recursively list, _ := gfile.ScanDirFunc(tempDir, "*", true, func(path string) string { // ignores some files - if gfile.Basename(path) == "gflie_example.txt" { + if gfile.Basename(path) == "gfile_example.txt" { return "" } return path @@ -99,11 +99,11 @@ func ExampleScanDirFunc() { func ExampleScanDirFileFunc() { // init var ( - fileName = "gflie_example.txt" + fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_scan_dir_file_func") tempFile = gfile.Join(tempDir, fileName) - fileName1 = "gflie_example_ignores.txt" + fileName1 = "gfile_example_ignores.txt" tempFile1 = gfile.Join(tempDir, fileName1) tempSubDir = gfile.Join(tempDir, "sub_dir") @@ -118,7 +118,7 @@ func ExampleScanDirFileFunc() { // scans directory recursively exclusive of directories list, _ := gfile.ScanDirFileFunc(tempDir, "*.txt", true, func(path string) string { // ignores some files - if gfile.Basename(path) == "gflie_example_ignores.txt" { + if gfile.Basename(path) == "gfile_example_ignores.txt" { return "" } return path @@ -128,6 +128,6 @@ func ExampleScanDirFileFunc() { } // Output: - // gflie_example.txt - // gflie_example.txt + // gfile_example.txt + // gfile_example.txt } diff --git a/os/gfile/gfile_z_example_search_test.go b/os/gfile/gfile_z_example_search_test.go index 8a93bc6d048..c24138bf87d 100644 --- a/os/gfile/gfile_z_example_search_test.go +++ b/os/gfile/gfile_z_example_search_test.go @@ -15,7 +15,7 @@ import ( func ExampleSearch() { // init var ( - fileName = "gflie_example.txt" + fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_search") tempFile = gfile.Join(tempDir, fileName) ) @@ -28,5 +28,5 @@ func ExampleSearch() { fmt.Println(gfile.Basename(realPath)) // Output: - // gflie_example.txt + // gfile_example.txt } diff --git a/os/gfile/gfile_z_example_size_test.go b/os/gfile/gfile_z_example_size_test.go index 6ddcd29adf5..6e7d14cab6f 100644 --- a/os/gfile/gfile_z_example_size_test.go +++ b/os/gfile/gfile_z_example_size_test.go @@ -15,7 +15,7 @@ import ( func ExampleSize() { // init var ( - fileName = "gflie_example.txt" + fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_size") tempFile = gfile.Join(tempDir, fileName) ) @@ -31,7 +31,7 @@ func ExampleSize() { func ExampleSizeFormat() { // init var ( - fileName = "gflie_example.txt" + fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_size") tempFile = gfile.Join(tempDir, fileName) ) @@ -47,7 +47,7 @@ func ExampleSizeFormat() { func ExampleReadableSize() { // init var ( - fileName = "gflie_example.txt" + fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_size") tempFile = gfile.Join(tempDir, fileName) ) From 22fcfdf755b5003244f59e22b87add4fda57cbca Mon Sep 17 00:00:00 2001 From: John Guo Date: Tue, 2 Jan 2024 20:19:05 +0800 Subject: [PATCH 43/52] add configuration support for logger of `grpcx.Server` (#3223) --- contrib/rpc/grpcx/grpcx_grpc_server_config.go | 21 +++++++++++++- .../grpcx_unit_z_grpc_server_config_test.go | 29 +++++++++++++++++++ .../grpcx/testdata/configuration/config.yaml | 14 +++++++++ os/glog/glog_logger_chaining.go | 3 ++ 4 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 contrib/rpc/grpcx/testdata/configuration/config.yaml diff --git a/contrib/rpc/grpcx/grpcx_grpc_server_config.go b/contrib/rpc/grpcx/grpcx_grpc_server_config.go index f5e7c878ef1..f88d8ddf410 100644 --- a/contrib/rpc/grpcx/grpcx_grpc_server_config.go +++ b/contrib/rpc/grpcx/grpcx_grpc_server_config.go @@ -8,6 +8,7 @@ package grpcx import ( "context" + "fmt" "google.golang.org/grpc" @@ -75,8 +76,26 @@ func (s modServer) NewConfig() *GrpcServerConfig { // Reading configuration file and updating the configured keys. if g.Cfg().Available(ctx) { // Server attributes configuration. - if err = g.Cfg().MustGet(ctx, configNodeNameGrpcServer).Struct(&config); err != nil { + serverConfigMap := g.Cfg().MustGet(ctx, configNodeNameGrpcServer).Map() + if len(serverConfigMap) == 0 { + return config + } + if err = gconv.Struct(serverConfigMap, &config); err != nil { g.Log().Error(ctx, err) + return config + } + // Server logger configuration checks. + serverLoggerConfigMap := g.Cfg().MustGet( + ctx, + fmt.Sprintf(`%s.logger`, configNodeNameGrpcServer), + ).Map() + if len(serverLoggerConfigMap) == 0 && len(serverConfigMap) > 0 { + serverLoggerConfigMap = gconv.Map(serverConfigMap["logger"]) + } + if len(serverLoggerConfigMap) > 0 { + if err = config.Logger.SetConfigWithMap(serverLoggerConfigMap); err != nil { + panic(err) + } } } return config diff --git a/contrib/rpc/grpcx/grpcx_unit_z_grpc_server_config_test.go b/contrib/rpc/grpcx/grpcx_unit_z_grpc_server_config_test.go index 21ace494f1f..fd4f7c27816 100644 --- a/contrib/rpc/grpcx/grpcx_unit_z_grpc_server_config_test.go +++ b/contrib/rpc/grpcx/grpcx_unit_z_grpc_server_config_test.go @@ -7,9 +7,13 @@ package grpcx import ( + "fmt" "testing" "time" + "github.com/gogf/gf/v2/debug/gdebug" + "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/text/gstr" ) @@ -70,3 +74,28 @@ func Test_Grpcx_Grpc_Server_Config(t *testing.T) { } }) } + +func Test_Grpcx_Grpc_Server_Config_Logger(t *testing.T) { + var ( + pwd = gfile.Pwd() + configDir = gfile.Join(gdebug.CallerDirectory(), "testdata", "configuration") + ) + gtest.C(t, func(t *gtest.T) { + err := gfile.Chdir(configDir) + t.AssertNil(err) + defer gfile.Chdir(pwd) + + s := Server.New() + s.Start() + time.Sleep(time.Millisecond * 100) + defer s.Stop() + + var ( + logFilePath = fmt.Sprintf("/tmp/log/%s.log", gtime.Now().Format("Y-m-d")) + logFileContent = gfile.GetContents(logFilePath) + ) + t.Assert(gfile.Exists(logFilePath), true) + t.Assert(gstr.Contains(logFileContent, "TestLogger "), true) + }) + +} diff --git a/contrib/rpc/grpcx/testdata/configuration/config.yaml b/contrib/rpc/grpcx/testdata/configuration/config.yaml new file mode 100644 index 00000000000..199541bef7e --- /dev/null +++ b/contrib/rpc/grpcx/testdata/configuration/config.yaml @@ -0,0 +1,14 @@ +grpc: + name: "demo" # 服务名称 + address: ":8000" # 自定义服务监听地址 + logPath: "./log" # 日志存储目录路径 + logStdout: true # 日志是否输出到终端 + errorLogEnabled: true # 是否开启错误日志记录 + accessLogEnabled: true # 是否开启访问日志记录 + errorStack: true # 当产生错误时,是否记录错误堆栈 + logger: + path: "/tmp/log/" # 日志文件路径。默认为空,表示关闭,仅输出到终端 + file: "{Y-m-d}.log" # 日志文件格式。默认为"{Y-m-d}.log" + prefix: "TestLogger" # 日志内容输出前缀。默认为空 + level: "all" # 日志输出级别 + stdout: false # 日志是否同时输出到终端。默认true \ No newline at end of file diff --git a/os/glog/glog_logger_chaining.go b/os/glog/glog_logger_chaining.go index 29ebade2f0d..72a90fadeb9 100644 --- a/os/glog/glog_logger_chaining.go +++ b/os/glog/glog_logger_chaining.go @@ -65,6 +65,9 @@ func (l *Logger) Cat(category string) *Logger { // File is a chaining function, // which sets file name `pattern` for the current logging content output. func (l *Logger) File(file string) *Logger { + if file == "" { + return l + } logger := (*Logger)(nil) if l.parent == nil { logger = l.Clone() From e1f2666499014718979554d785f03eb6efa64536 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B5=B7=E4=BA=AE?= <739476267@qq.com> Date: Tue, 2 Jan 2024 20:19:40 +0800 Subject: [PATCH 44/52] add example for serve file (#3193) --- example/httpserver/serve_file/main.go | 45 +++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 example/httpserver/serve_file/main.go diff --git a/example/httpserver/serve_file/main.go b/example/httpserver/serve_file/main.go new file mode 100644 index 00000000000..0b8e1372b3f --- /dev/null +++ b/example/httpserver/serve_file/main.go @@ -0,0 +1,45 @@ +package main + +import ( + "net/http" + "strings" + + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/net/ghttp" +) + +// pathMap is used for URL mapping +var pathMap = map[string]string{ + "/aaa/": "/tmp/", +} + +// ServeFile serves the file to the response. +func ServeFile(r *ghttp.Request) { + truePath := r.URL.Path + hasPrefix := false + // Replace the path prefix. + for k, v := range pathMap { + if strings.HasPrefix(truePath, k) { + truePath = strings.Replace(truePath, k, v, 1) // Replace only once. + hasPrefix = true + break + } + } + + if !hasPrefix { + r.Response.WriteStatus(http.StatusForbidden) + return + } + + r.Response.ServeFile(truePath) +} + +func main() { + s := g.Server() + s.Use(ghttp.MiddlewareHandlerResponse) + s.BindHandler("/*", ServeFile) + s.SetPort(8080) + s.Run() +} + +// http://127.0.0.1:8080/aaa/main.go From 335ccb32afe8b869d41c6d5dfa3af3c6114e2c30 Mon Sep 17 00:00:00 2001 From: oldme <45782393+oldme-git@users.noreply.github.com> Date: Tue, 2 Jan 2024 20:42:14 +0800 Subject: [PATCH 45/52] Update Github issue template (#3234) --- .github/ISSUE_TEMPLATE.MD | 38 ----------------- .github/ISSUE_TEMPLATE/bug-report.md | 41 +++++++++++++++++++ .github/ISSUE_TEMPLATE/enhancement-request.md | 16 ++++++++ .github/ISSUE_TEMPLATE/feature-request.md | 19 +++++++++ .github/ISSUE_TEMPLATE/question.md | 11 +++++ 5 files changed, 87 insertions(+), 38 deletions(-) delete mode 100644 .github/ISSUE_TEMPLATE.MD create mode 100644 .github/ISSUE_TEMPLATE/bug-report.md create mode 100644 .github/ISSUE_TEMPLATE/enhancement-request.md create mode 100644 .github/ISSUE_TEMPLATE/feature-request.md create mode 100644 .github/ISSUE_TEMPLATE/question.md diff --git a/.github/ISSUE_TEMPLATE.MD b/.github/ISSUE_TEMPLATE.MD deleted file mode 100644 index 540e46b4bd9..00000000000 --- a/.github/ISSUE_TEMPLATE.MD +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - -### 1. What version of `Go` and system type/arch are you using? - - - -### 2. What version of `GoFrame` are you using? - - - -### 3. Can this issue be re-produced with the latest release? - - - -### 4. What did you do? - - - - -### 5. What did you expect to see? - - - -### 6. What did you see instead? - - - diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md new file mode 100644 index 00000000000..4fa1cfa1265 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug-report.md @@ -0,0 +1,41 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: bug +assignees: '' + +--- + + + + + + + + +**What version of `Go` and system type/arch are you using?** + + + +**What version of `GoFrame` are you using?** + + + +**Can this bug be re-produced with the latest release?** + + +**What did you do?** + + + +**What did you expect to see?** + + +**What did you see instead?** diff --git a/.github/ISSUE_TEMPLATE/enhancement-request.md b/.github/ISSUE_TEMPLATE/enhancement-request.md new file mode 100644 index 00000000000..83fc3ba52b8 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/enhancement-request.md @@ -0,0 +1,16 @@ +--- +name: Enhancement request +about: Enhance an idea for this project +title: '' +labels: enhancement +assignees: '' + +--- + +**Package that You wish to enhance** + + +**Enhancement description** + + +**Additional** diff --git a/.github/ISSUE_TEMPLATE/feature-request.md b/.github/ISSUE_TEMPLATE/feature-request.md new file mode 100644 index 00000000000..5d76856327c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature-request.md @@ -0,0 +1,19 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: feature +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** + + +**Describe the solution you'd like** + + +**Describe alternatives you've considered** + + +**Additional** diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md new file mode 100644 index 00000000000..e0d8ad97090 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/question.md @@ -0,0 +1,11 @@ +--- +name: Question +about: I want to ask a question +title: '' +labels: question +assignees: '' + +--- + + +**What do you want to ask** From 8af1eb693e4561e501c90df65594739fa88a9a27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B5=B7=E4=BA=AE?= <739476267@qq.com> Date: Wed, 3 Jan 2024 19:49:06 +0800 Subject: [PATCH 46/52] Update README.MD (#3243) --- README.MD | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.MD b/README.MD index 85ed14b3dc2..3951a6d7275 100644 --- a/README.MD +++ b/README.MD @@ -7,16 +7,16 @@ [![GoFrame CI](https://github.com/gogf/gf/actions/workflows/ci-main.yml/badge.svg)](https://github.com/gogf/gf/actions/workflows/ci-main.yml) [![Go Report Card](https://goreportcard.com/badge/github.com/gogf/gf/v2)](https://goreportcard.com/report/github.com/gogf/gf/v2) [![Code Coverage](https://codecov.io/gh/gogf/gf/branch/master/graph/badge.svg)](https://codecov.io/gh/gogf/gf) -[![Production Ready](https://img.shields.io/badge/production-ready-blue.svg)](https://github.com/gogf/gf) +[![Production Ready](https://img.shields.io/badge/production-ready-blue.svg?style=flat)](https://github.com/gogf/gf) [![License](https://img.shields.io/github/license/gogf/gf.svg?style=flat)](https://github.com/gogf/gf) -[![Release](https://img.shields.io/github/v/release/gogf/gf)](https://github.com/gogf/gf/releases) -[![GitHub pull requests](https://img.shields.io/github/issues-pr/gogf/gf)](https://github.com/gogf/gf/pulls) -[![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed/gogf/gf)](https://github.com/gogf/gf/pulls?q=is%3Apr+is%3Aclosed) -[![GitHub issues](https://img.shields.io/github/issues/gogf/gf)](https://github.com/gogf/gf/issues) -[![GitHub closed issues](https://img.shields.io/github/issues-closed/gogf/gf)](https://github.com/gogf/gf/issues?q=is%3Aissue+is%3Aclosed) -![Stars](https://img.shields.io/github/stars/gogf/gf) -![Forks](https://img.shields.io/github/forks/gogf/gf) +[![Release](https://img.shields.io/github/v/release/gogf/gf?style=flat)](https://github.com/gogf/gf/releases) +[![GitHub pull requests](https://img.shields.io/github/issues-pr/gogf/gf?style=flat)](https://github.com/gogf/gf/pulls) +[![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed/gogf/gf?style=flat)](https://github.com/gogf/gf/pulls?q=is%3Apr+is%3Aclosed) +[![GitHub issues](https://img.shields.io/github/issues/gogf/gf?style=flat)](https://github.com/gogf/gf/issues) +[![GitHub closed issues](https://img.shields.io/github/issues-closed/gogf/gf?style=flat)](https://github.com/gogf/gf/issues?q=is%3Aissue+is%3Aclosed) +![Stars](https://img.shields.io/github/stars/gogf/gf?style=flat) +![Forks](https://img.shields.io/github/forks/gogf/gf?style=flat) From 5a017984817fd1292232ebc455765c5b919992cf Mon Sep 17 00:00:00 2001 From: Gin Date: Wed, 3 Jan 2024 20:03:19 +0800 Subject: [PATCH 47/52] fix: memory leak when gcache.NewAdapterMemory with lru (#3241) --- os/gcache/gcache_adapter_memory.go | 3 +++ os/gcache/gcache_cache.go | 5 ----- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/os/gcache/gcache_adapter_memory.go b/os/gcache/gcache_adapter_memory.go index 707b04bd90d..9502b549137 100644 --- a/os/gcache/gcache_adapter_memory.go +++ b/os/gcache/gcache_adapter_memory.go @@ -67,6 +67,9 @@ func NewAdapterMemory(lruCap ...int) Adapter { c.cap = lruCap[0] c.lru = newMemCacheLru(c) } + // Here may be a "timer leak" if adapter is manually changed from memory adapter. + // Do not worry about this, as adapter is less changed, and it does nothing if it's not used. + gtimer.AddSingleton(context.Background(), time.Second, c.syncEventAndClearExpired) return c } diff --git a/os/gcache/gcache_cache.go b/os/gcache/gcache_cache.go index 9a039457c66..bd3d2ac4b3e 100644 --- a/os/gcache/gcache_cache.go +++ b/os/gcache/gcache_cache.go @@ -8,9 +8,7 @@ package gcache import ( "context" - "time" - "github.com/gogf/gf/v2/os/gtimer" "github.com/gogf/gf/v2/util/gconv" ) @@ -29,9 +27,6 @@ func New(lruCap ...int) *Cache { c := &Cache{ localAdapter: memAdapter, } - // Here may be a "timer leak" if adapter is manually changed from memory adapter. - // Do not worry about this, as adapter is less changed, and it does nothing if it's not used. - gtimer.AddSingleton(context.Background(), time.Second, memAdapter.(*AdapterMemory).syncEventAndClearExpired) return c } From 4f4d2c2f8e3c43711fe922f807fa4223becd524d Mon Sep 17 00:00:00 2001 From: John Guo Date: Sat, 6 Jan 2024 13:03:49 +0800 Subject: [PATCH 48/52] add `MiddlewareNeverDoneCtx` for package `ghttp` (#3250) --- net/ghttp/ghttp_middleware_never_done_ctx.go | 13 +++ .../ghttp_z_unit_feature_request_ctx_test.go | 90 +++++++++++++++++++ os/gctx/gctx_never_done.go | 6 +- 3 files changed, 108 insertions(+), 1 deletion(-) create mode 100644 net/ghttp/ghttp_middleware_never_done_ctx.go diff --git a/net/ghttp/ghttp_middleware_never_done_ctx.go b/net/ghttp/ghttp_middleware_never_done_ctx.go new file mode 100644 index 00000000000..9f6cee44713 --- /dev/null +++ b/net/ghttp/ghttp_middleware_never_done_ctx.go @@ -0,0 +1,13 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +package ghttp + +// MiddlewareNeverDoneCtx sets the context never done for current process. +func MiddlewareNeverDoneCtx(r *Request) { + r.SetCtx(r.GetNeverDoneCtx()) + r.Middleware.Next() +} diff --git a/net/ghttp/ghttp_z_unit_feature_request_ctx_test.go b/net/ghttp/ghttp_z_unit_feature_request_ctx_test.go index 823d1d2fc7e..642e50901e8 100644 --- a/net/ghttp/ghttp_z_unit_feature_request_ctx_test.go +++ b/net/ghttp/ghttp_z_unit_feature_request_ctx_test.go @@ -13,6 +13,7 @@ import ( "testing" "time" + "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/encoding/gbase64" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" @@ -345,3 +346,92 @@ func Test_Request_Form(t *testing.T) { }), "john") }) } + +func Test_Request_NeverDoneCtx_Done(t *testing.T) { + var array = garray.New(true) + s := g.Server(guid.S()) + s.BindHandler("/done", func(r *ghttp.Request) { + var ( + ctx = r.Context() + ticker = time.NewTimer(time.Millisecond * 1500) + ) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + array.Append(1) + return + case <-ticker.C: + array.Append(1) + return + } + } + }) + s.SetDumpRouterMap(false) + s.Start() + defer s.Shutdown() + + time.Sleep(100 * time.Millisecond) + + c := g.Client() + c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", s.GetListenedPort())) + gtest.C(t, func(t *gtest.T) { + ctx, cancel := context.WithTimeout(context.Background(), time.Second*30) + go func() { + result := c.GetContent(ctx, "/done") + fmt.Println(result) + }() + time.Sleep(time.Millisecond * 100) + + t.Assert(array.Len(), 0) + cancel() + + time.Sleep(time.Millisecond * 500) + t.Assert(array.Len(), 1) + }) +} + +func Test_Request_NeverDoneCtx_NeverDone(t *testing.T) { + var array = garray.New(true) + s := g.Server(guid.S()) + s.Use(ghttp.MiddlewareNeverDoneCtx) + s.BindHandler("/never-done", func(r *ghttp.Request) { + var ( + ctx = r.Context() + ticker = time.NewTimer(time.Millisecond * 1500) + ) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + array.Append(1) + return + case <-ticker.C: + array.Append(1) + return + } + } + }) + s.SetDumpRouterMap(false) + s.Start() + defer s.Shutdown() + + time.Sleep(100 * time.Millisecond) + + c := g.Client() + c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", s.GetListenedPort())) + gtest.C(t, func(t *gtest.T) { + ctx, cancel := context.WithTimeout(context.Background(), time.Second*30) + go func() { + result := c.GetContent(ctx, "/never-done") + fmt.Println(result) + }() + time.Sleep(time.Millisecond * 100) + + t.Assert(array.Len(), 0) + cancel() + + time.Sleep(time.Millisecond * 1500) + t.Assert(array.Len(), 1) + }) +} diff --git a/os/gctx/gctx_never_done.go b/os/gctx/gctx_never_done.go index 8d08e53a1bb..2e28c7809dc 100644 --- a/os/gctx/gctx_never_done.go +++ b/os/gctx/gctx_never_done.go @@ -32,7 +32,11 @@ func (c *neverDoneCtx) Err() error { } // NeverDone wraps and returns a new context object that will be never done, -// which forbids the context manually done, to make the context can be propagated to asynchronous goroutines. +// which forbids the context manually done, to make the context can be propagated +// to asynchronous goroutines. +// +// Note that, it does not affect the closing (canceling) of the parent context, +// as it is a wrapper for its parent, which only affects the next context handling. func NeverDone(ctx context.Context) context.Context { return &neverDoneCtx{ctx} } From 42e3c5f39a04db7c10226eea28277a31543d68ee Mon Sep 17 00:00:00 2001 From: oldme <45782393+oldme-git@users.noreply.github.com> Date: Thu, 11 Jan 2024 22:14:22 +0800 Subject: [PATCH 49/52] fix #3253 (#3255) --- encoding/gjson/gjson_z_unit_test.go | 15 +++++++++++++++ internal/utils/utils_reflect.go | 26 ++++++++++++++++++++++++++ internal/utils/utils_z_unit_test.go | 24 ++++++++++++++++++++++++ util/gconv/gconv_map.go | 2 +- 4 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 internal/utils/utils_reflect.go diff --git a/encoding/gjson/gjson_z_unit_test.go b/encoding/gjson/gjson_z_unit_test.go index 55faf5d0490..9bb6958e5b6 100644 --- a/encoding/gjson/gjson_z_unit_test.go +++ b/encoding/gjson/gjson_z_unit_test.go @@ -53,6 +53,21 @@ func Test_New(t *testing.T) { t.Assert(j.Get("k2"), "v2") t.Assert(j.Get("k3"), nil) }) + // https://github.com/gogf/gf/issues/3253 + gtest.C(t, func(t *gtest.T) { + type TestStruct struct { + Result []map[string]string `json:"result"` + } + ts := &TestStruct{ + Result: []map[string]string{ + { + "Name": "gf", + "Role": "", + }, + }, + } + gjson.New(ts) + }) } func Test_Valid(t *testing.T) { diff --git a/internal/utils/utils_reflect.go b/internal/utils/utils_reflect.go new file mode 100644 index 00000000000..c217e407b7b --- /dev/null +++ b/internal/utils/utils_reflect.go @@ -0,0 +1,26 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +package utils + +import ( + "reflect" +) + +// CanCallIsNil Can reflect.Value call reflect.Value.IsNil. +// It can avoid reflect.Value.IsNil panics. +func CanCallIsNil(v interface{}) bool { + rv, ok := v.(reflect.Value) + if !ok { + return false + } + switch rv.Kind() { + case reflect.Interface, reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer: + return true + default: + return false + } +} diff --git a/internal/utils/utils_z_unit_test.go b/internal/utils/utils_z_unit_test.go index 95077e7abc0..259091d5fd0 100644 --- a/internal/utils/utils_z_unit_test.go +++ b/internal/utils/utils_z_unit_test.go @@ -8,7 +8,9 @@ package utils_test import ( "io" + "reflect" "testing" + "unsafe" "github.com/gogf/gf/v2/internal/utils" "github.com/gogf/gf/v2/test/gtest" @@ -71,3 +73,25 @@ func Test_RemoveSymbols(t *testing.T) { t.Assert(utils.RemoveSymbols(`-a-b我._a c1!@#$%^&*是()_+:帅";'.,哥'01`), `ab我ac1是帅哥01`) }) } + +func Test_CanCallIsNil(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + var ( + iValue = "gf" + iChan = make(chan struct{}) + iFunc = func() {} + iMap = map[string]struct{}{} + iPtr = &iValue + iSlice = make([]struct{}, 0) + iUnsafePointer = unsafe.Pointer(&iValue) + ) + + t.Assert(utils.CanCallIsNil(reflect.ValueOf(iValue)), false) + t.Assert(utils.CanCallIsNil(reflect.ValueOf(iChan)), true) + t.Assert(utils.CanCallIsNil(reflect.ValueOf(iFunc)), true) + t.Assert(utils.CanCallIsNil(reflect.ValueOf(iMap)), true) + t.Assert(utils.CanCallIsNil(reflect.ValueOf(iPtr)), true) + t.Assert(utils.CanCallIsNil(reflect.ValueOf(iSlice)), true) + t.Assert(utils.CanCallIsNil(reflect.ValueOf(iUnsafePointer)), true) + }) +} diff --git a/util/gconv/gconv_map.go b/util/gconv/gconv_map.go index 7d52fcda3e2..33470ebd0c6 100644 --- a/util/gconv/gconv_map.go +++ b/util/gconv/gconv_map.go @@ -303,7 +303,7 @@ func doMapConvertForMapOrStructValue(in doMapConvertForMapOrStructValueInput) in ) switch { case mapKeyValue.IsZero(): - if mapKeyValue.IsNil() { + if utils.CanCallIsNil(mapKeyValue) && mapKeyValue.IsNil() { // quick check for nil value. mapValue = nil } else { From ca242ff40157cce4e90abd45297fe6b0b387c6cb Mon Sep 17 00:00:00 2001 From: oldme <45782393+oldme-git@users.noreply.github.com> Date: Thu, 11 Jan 2024 22:15:22 +0800 Subject: [PATCH 50/52] fix #3251 (#3254) --- net/ghttp/ghttp_server_pprof.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/net/ghttp/ghttp_server_pprof.go b/net/ghttp/ghttp_server_pprof.go index 632feb6c885..eb37f46261a 100644 --- a/net/ghttp/ghttp_server_pprof.go +++ b/net/ghttp/ghttp_server_pprof.go @@ -26,7 +26,7 @@ const ( // StartPProfServer starts and runs a new server for pprof. func StartPProfServer(port int, pattern ...string) { s := GetServer(defaultPProfServerName) - s.EnablePProf() + s.EnablePProf(pattern...) s.SetPort(port) s.Run() } From 4b8eaac73fd0407777fe0a74eb328c041d07da43 Mon Sep 17 00:00:00 2001 From: John Guo Date: Mon, 15 Jan 2024 20:33:30 +0800 Subject: [PATCH 51/52] fix issue #3232 (#3247) --- cmd/gf/internal/cmd/cmd_build.go | 144 ++++++++++------- cmd/gf/internal/cmd/cmd_z_unit_build_test.go | 151 ++++++++++++++++++ .../cmd/testdata/build/multiple/multiple.go | 5 + .../cmd/testdata/build/single/main.go | 5 + .../internal/cmd/testdata/build/varmap/go.mod | 12 ++ .../internal/cmd/testdata/build/varmap/go.sum | 27 ++++ .../cmd/testdata/build/varmap/main.go | 13 ++ os/gcmd/gcmd_parser.go | 12 ++ 8 files changed, 308 insertions(+), 61 deletions(-) create mode 100644 cmd/gf/internal/cmd/cmd_z_unit_build_test.go create mode 100644 cmd/gf/internal/cmd/testdata/build/multiple/multiple.go create mode 100644 cmd/gf/internal/cmd/testdata/build/single/main.go create mode 100644 cmd/gf/internal/cmd/testdata/build/varmap/go.mod create mode 100644 cmd/gf/internal/cmd/testdata/build/varmap/go.sum create mode 100644 cmd/gf/internal/cmd/testdata/build/varmap/main.go diff --git a/cmd/gf/internal/cmd/cmd_build.go b/cmd/gf/internal/cmd/cmd_build.go index 2a0564026e4..edb7c382e96 100644 --- a/cmd/gf/internal/cmd/cmd_build.go +++ b/cmd/gf/internal/cmd/cmd_build.go @@ -44,8 +44,9 @@ type cBuild struct { } const ( - cBuildBrief = `cross-building go project for lots of platforms` - cBuildEg = ` + cBuildDefaultFile = "main.go" + cBuildBrief = `cross-building go project for lots of platforms` + cBuildEg = ` gf build main.go gf build main.go --ps public,template gf build main.go --cgo @@ -123,7 +124,7 @@ type cBuildInput struct { Arch string `short:"a" name:"arch" brief:"output binary architecture, multiple arch separated with ','"` System string `short:"s" name:"system" brief:"output binary system, multiple os separated with ','"` Output string `short:"o" name:"output" brief:"output binary path, used when building single binary file"` - Path string `short:"p" name:"path" brief:"output binary directory path, default is './temp'" d:"./temp"` + Path string `short:"p" name:"path" brief:"output binary directory path, default is '.'" d:"."` Extra string `short:"e" name:"extra" brief:"extra custom \"go build\" options"` Mod string `short:"m" name:"mod" brief:"like \"-mod\" option of \"go build\", use \"-m none\" to disable go module"` Cgo bool `short:"c" name:"cgo" brief:"enable or disable cgo feature, it's disabled in default" orphan:"true"` @@ -152,12 +153,13 @@ func (c cBuild) Index(ctx context.Context, in cBuildInput) (out *cBuildOutput, e var ( parser = gcmd.ParserFromCtx(ctx) - file = parser.GetArg(2).String() + file = in.File ) - if len(file) < 1 { + if file == "" { + file = parser.GetArg(2).String() // Check and use the main.go file. - if gfile.Exists("main.go") { - file = "main.go" + if gfile.Exists(cBuildDefaultFile) { + file = cBuildDefaultFile } else { mlog.Fatal("build file path is empty or main.go not found in current working directory") } @@ -239,13 +241,7 @@ func (c cBuild) Index(ctx context.Context, in cBuildInput) (out *cBuildOutput, e } else { genv.MustSet("CGO_ENABLED", "0") } - var ( - cmd = "" - ext = "" - ) for system, item := range platformMap { - cmd = "" - ext = "" if len(customSystems) > 0 && customSystems[0] != "all" && !gstr.InArray(customSystems, system) { continue } @@ -258,58 +254,22 @@ func (c cBuild) Index(ctx context.Context, in cBuildInput) (out *cBuildOutput, e // For example: // `gf build` // `gf build -o main.exe` - if runtime.GOOS == "windows" { - ext = ".exe" - } - var outputPath string - if len(in.Output) > 0 { - outputPath = "-o " + in.Output - } else { - outputPath = "-o " + in.Name + ext - } - cmd = fmt.Sprintf( - `go build %s -ldflags "%s" %s %s`, - outputPath, ldFlags, in.Extra, file, + c.doBinaryBuild( + ctx, file, + in.Output, in.Path, + runtime.GOOS, runtime.GOARCH, in.Name, ldFlags, in.Extra, + in.ExitWhenError, + true, ) } else { - // Cross-building, output the compiled binary to specified path. - if system == "windows" { - ext = ".exe" - } - genv.MustSet("GOOS", system) - genv.MustSet("GOARCH", arch) - - var outputPath string - if len(in.Output) > 0 { - outputPath = "-o " + in.Output - } else { - outputPath = fmt.Sprintf( - "-o %s/%s/%s%s", - in.Path, system+"_"+arch, in.Name, ext, - ) - } - cmd = fmt.Sprintf( - `go build %s -ldflags "%s" %s%s`, - outputPath, ldFlags, in.Extra, file, + c.doBinaryBuild( + ctx, file, + in.Output, in.Path, + system, arch, in.Name, ldFlags, in.Extra, + in.ExitWhenError, + false, ) } - mlog.Debug(fmt.Sprintf("build for GOOS=%s GOARCH=%s", system, arch)) - mlog.Debug(cmd) - // It's not necessary printing the complete command string. - cmdShow, _ := gregex.ReplaceString(`\s+(-ldflags ".+?")\s+`, " ", cmd) - mlog.Print(cmdShow) - if result, err := gproc.ShellExec(ctx, cmd); err != nil { - mlog.Printf( - "failed to build, os:%s, arch:%s, error:\n%s\n\n%s\n", - system, arch, gstr.Trim(result), - `you may use command option "--debug" to enable debug info and check the details`, - ) - if in.ExitWhenError { - os.Exit(1) - } - } else { - mlog.Debug(gstr.Trim(result)) - } // single binary building. if len(customSystems) == 0 && len(customArches) == 0 { goto buildDone @@ -322,6 +282,68 @@ buildDone: return } +func (c cBuild) doBinaryBuild( + ctx context.Context, + filePath string, + outputPath, dirPath string, + system, arch, name, ldFlags, extra string, + exitWhenError bool, + singleBuild bool, +) { + var ( + cmd string + ext string + ) + // Cross-building, output the compiled binary to specified path. + if system == "windows" { + ext = ".exe" + } + genv.MustSet("GOOS", system) + genv.MustSet("GOARCH", arch) + + if outputPath != "" { + outputPath = "-o " + outputPath + } else { + if dirPath == "" { + dirPath = "." + } else { + dirPath = gstr.TrimRight(dirPath, "/") + } + if singleBuild { + outputPath = fmt.Sprintf( + "-o %s/%s%s", + dirPath, name, ext, + ) + } else { + outputPath = fmt.Sprintf( + "-o %s/%s/%s%s", + dirPath, system+"_"+arch, name, ext, + ) + } + } + cmd = fmt.Sprintf( + `go build %s -ldflags "%s" %s%s`, + outputPath, ldFlags, extra, filePath, + ) + mlog.Debug(fmt.Sprintf("build for GOOS=%s GOARCH=%s", system, arch)) + mlog.Debug(cmd) + // It's not necessary printing the complete command string, filtering ldFlags. + cmdShow, _ := gregex.ReplaceString(`\s+(-ldflags ".+?")\s+`, " ", cmd) + mlog.Print(cmdShow) + if result, err := gproc.ShellExec(ctx, cmd); err != nil { + mlog.Printf( + "failed to build, os:%s, arch:%s, error:\n%s\n\n%s\n", + system, arch, gstr.Trim(result), + `you may use command option "--debug" to enable debug info and check the details`, + ) + if exitWhenError { + os.Exit(1) + } + } else { + mlog.Debug(gstr.Trim(result)) + } +} + // getBuildInVarStr retrieves and returns the custom build-in variables in configuration // file as json. func (c cBuild) getBuildInVarStr(ctx context.Context, in cBuildInput) string { diff --git a/cmd/gf/internal/cmd/cmd_z_unit_build_test.go b/cmd/gf/internal/cmd/cmd_z_unit_build_test.go new file mode 100644 index 00000000000..33925969189 --- /dev/null +++ b/cmd/gf/internal/cmd/cmd_z_unit_build_test.go @@ -0,0 +1,151 @@ +// Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +package cmd + +import ( + "testing" + + "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/os/gproc" + "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/text/gstr" +) + +func Test_Build_Single(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + var ( + buildPath = gtest.DataPath(`build`, `single`) + pwd = gfile.Pwd() + binaryName = `t.test` + binaryPath = gtest.DataPath(`build`, `single`, binaryName) + f = cBuild{} + ) + defer gfile.Chdir(pwd) + defer gfile.Remove(binaryPath) + err := gfile.Chdir(buildPath) + t.AssertNil(err) + + t.Assert(gfile.Exists(binaryPath), false) + _, err = f.Index(ctx, cBuildInput{ + File: cBuildDefaultFile, + Name: binaryName, + }) + t.AssertNil(err) + t.Assert(gfile.Exists(binaryPath), true) + }) +} + +func Test_Build_Single_Output(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + var ( + buildPath = gtest.DataPath(`build`, `single`) + pwd = gfile.Pwd() + binaryName = `tt` + binaryDirPath = gtest.DataPath(`build`, `single`, `tt`) + binaryPath = gtest.DataPath(`build`, `single`, `tt`, binaryName) + f = cBuild{} + ) + defer gfile.Chdir(pwd) + defer gfile.Remove(binaryDirPath) + err := gfile.Chdir(buildPath) + t.AssertNil(err) + + t.Assert(gfile.Exists(binaryPath), false) + _, err = f.Index(ctx, cBuildInput{ + Output: "./tt/tt", + }) + t.AssertNil(err) + t.Assert(gfile.Exists(binaryPath), true) + }) +} + +func Test_Build_Single_Path(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + var ( + buildPath = gtest.DataPath(`build`, `single`) + pwd = gfile.Pwd() + dirName = "ttt" + binaryName = `main` + binaryDirPath = gtest.DataPath(`build`, `single`, dirName) + binaryPath = gtest.DataPath(`build`, `single`, dirName, binaryName) + f = cBuild{} + ) + defer gfile.Chdir(pwd) + defer gfile.Remove(binaryDirPath) + err := gfile.Chdir(buildPath) + t.AssertNil(err) + + t.Assert(gfile.Exists(binaryPath), false) + _, err = f.Index(ctx, cBuildInput{ + Path: "ttt", + }) + t.AssertNil(err) + t.Assert(gfile.Exists(binaryPath), true) + }) +} + +func Test_Build_Single_VarMap(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + var ( + buildPath = gtest.DataPath(`build`, `varmap`) + pwd = gfile.Pwd() + binaryName = `main` + binaryPath = gtest.DataPath(`build`, `varmap`, binaryName) + f = cBuild{} + ) + defer gfile.Chdir(pwd) + defer gfile.Remove(binaryPath) + err := gfile.Chdir(buildPath) + t.AssertNil(err) + + t.Assert(gfile.Exists(binaryPath), false) + _, err = f.Index(ctx, cBuildInput{ + VarMap: map[string]interface{}{ + "a": "1", + "b": "2", + }, + }) + t.AssertNil(err) + t.Assert(gfile.Exists(binaryPath), true) + + result, err := gproc.ShellExec(ctx, binaryPath) + t.AssertNil(err) + t.Assert(gstr.Contains(result, `a: 1`), true) + t.Assert(gstr.Contains(result, `b: 2`), true) + }) +} + +func Test_Build_Multiple(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + var ( + buildPath = gtest.DataPath(`build`, `multiple`) + pwd = gfile.Pwd() + binaryDirPath = gtest.DataPath(`build`, `multiple`, `temp`) + binaryPathLinux = gtest.DataPath(`build`, `multiple`, `temp`, `v1.1`, `linux_amd64`, `ttt`) + binaryPathWindows = gtest.DataPath(`build`, `multiple`, `temp`, `v1.1`, `windows_amd64`, `ttt.exe`) + f = cBuild{} + ) + defer gfile.Chdir(pwd) + defer gfile.Remove(binaryDirPath) + err := gfile.Chdir(buildPath) + t.AssertNil(err) + + t.Assert(gfile.Exists(binaryPathLinux), false) + t.Assert(gfile.Exists(binaryPathWindows), false) + _, err = f.Index(ctx, cBuildInput{ + File: "multiple.go", + Name: "ttt", + Version: "v1.1", + Arch: "amd64", + System: "linux, windows", + Path: "temp", + }) + t.AssertNil(err) + t.Assert(gfile.Exists(binaryPathLinux), true) + t.Assert(gfile.Exists(binaryPathWindows), true) + }) +} diff --git a/cmd/gf/internal/cmd/testdata/build/multiple/multiple.go b/cmd/gf/internal/cmd/testdata/build/multiple/multiple.go new file mode 100644 index 00000000000..79058077776 --- /dev/null +++ b/cmd/gf/internal/cmd/testdata/build/multiple/multiple.go @@ -0,0 +1,5 @@ +package main + +func main() { + +} diff --git a/cmd/gf/internal/cmd/testdata/build/single/main.go b/cmd/gf/internal/cmd/testdata/build/single/main.go new file mode 100644 index 00000000000..79058077776 --- /dev/null +++ b/cmd/gf/internal/cmd/testdata/build/single/main.go @@ -0,0 +1,5 @@ +package main + +func main() { + +} diff --git a/cmd/gf/internal/cmd/testdata/build/varmap/go.mod b/cmd/gf/internal/cmd/testdata/build/varmap/go.mod new file mode 100644 index 00000000000..74572920486 --- /dev/null +++ b/cmd/gf/internal/cmd/testdata/build/varmap/go.mod @@ -0,0 +1,12 @@ +module github.com/gogf/gf/cmd/gf/cmd/gf/testdata/vardump/v2 + +go 1.18 + +require github.com/gogf/gf/v2 v2.6.1 + +require ( + go.opentelemetry.io/otel v1.14.0 // indirect + go.opentelemetry.io/otel/trace v1.14.0 // indirect +) + +replace github.com/gogf/gf/v2 => ../../../../../../../ diff --git a/cmd/gf/internal/cmd/testdata/build/varmap/go.sum b/cmd/gf/internal/cmd/testdata/build/varmap/go.sum new file mode 100644 index 00000000000..56cf07dd733 --- /dev/null +++ b/cmd/gf/internal/cmd/testdata/build/varmap/go.sum @@ -0,0 +1,27 @@ +github.com/BurntSushi/toml v1.2.0 h1:Rt8g24XnyGTyglgET/PRUNlrUeu9F5L+7FilkXfZgs0= +github.com/clbanning/mxj/v2 v2.7.0 h1:WA/La7UGCanFe5NpHF0Q3DNtnCsVoxbPKuyBNHWRyME= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= +github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= +github.com/grokify/html-strip-tags-go v0.0.1 h1:0fThFwLbW7P/kOiTBs03FsJSV9RM2M/Q/MOnCQxKMo0= +github.com/magiconair/properties v1.8.6 h1:5ibWZ6iY0NctNGWo87LalDlEZ6R41TqbbDamhfG/Qzo= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= +github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/rivo/uniseg v0.4.4 h1:8TfxU8dW6PdqD27gjM8MVNuicgxIjxpm4K7x4jp8sis= +github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= +go.opentelemetry.io/otel v1.14.0 h1:/79Huy8wbf5DnIPhemGB+zEPVwnN6fuQybr/SRXa6hM= +go.opentelemetry.io/otel v1.14.0/go.mod h1:o4buv+dJzx8rohcUeRmWUZhqupFvzWis188WlggnNeU= +go.opentelemetry.io/otel/sdk v1.14.0 h1:PDCppFRDq8A1jL9v6KMI6dYesaq+DFcDZvjsoGvxGzY= +go.opentelemetry.io/otel/trace v1.14.0 h1:wp2Mmvj41tDsyAJXiWDWpfNsOiIyd38fy85pyKcFq/M= +go.opentelemetry.io/otel/trace v1.14.0/go.mod h1:8avnQLK+CG77yNLUae4ea2JDQ6iT+gozhnZjy/rw9G8= +golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= +golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= +golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/cmd/gf/internal/cmd/testdata/build/varmap/main.go b/cmd/gf/internal/cmd/testdata/build/varmap/main.go new file mode 100644 index 00000000000..788a885cddf --- /dev/null +++ b/cmd/gf/internal/cmd/testdata/build/varmap/main.go @@ -0,0 +1,13 @@ +package main + +import ( + "fmt" + + "github.com/gogf/gf/v2/os/gbuild" +) + +func main() { + for k, v := range gbuild.Data() { + fmt.Printf("%s: %v\n", k, v) + } +} diff --git a/os/gcmd/gcmd_parser.go b/os/gcmd/gcmd_parser.go index 40689732874..49cbcca8502 100644 --- a/os/gcmd/gcmd_parser.go +++ b/os/gcmd/gcmd_parser.go @@ -200,6 +200,9 @@ func (p *Parser) setOptionValue(name, value string) { // GetOpt returns the option value named `name` as gvar.Var. func (p *Parser) GetOpt(name string, def ...interface{}) *gvar.Var { + if p == nil { + return nil + } if v, ok := p.parsedOptions[name]; ok { return gvar.New(v) } @@ -211,11 +214,17 @@ func (p *Parser) GetOpt(name string, def ...interface{}) *gvar.Var { // GetOptAll returns all parsed options. func (p *Parser) GetOptAll() map[string]string { + if p == nil { + return nil + } return p.parsedOptions } // GetArg returns the argument at `index` as gvar.Var. func (p *Parser) GetArg(index int, def ...string) *gvar.Var { + if p == nil { + return nil + } if index >= 0 && index < len(p.parsedArgs) { return gvar.New(p.parsedArgs[index]) } @@ -227,6 +236,9 @@ func (p *Parser) GetArg(index int, def ...string) *gvar.Var { // GetArgAll returns all parsed arguments. func (p *Parser) GetArgAll() []string { + if p == nil { + return nil + } return p.parsedArgs } From 905913f7bebffded5b58ba0cccb21329d41242e7 Mon Sep 17 00:00:00 2001 From: loveyfore Date: Mon, 15 Jan 2024 20:35:14 +0800 Subject: [PATCH 52/52] =?UTF-8?q?Fix=20gf=20gen=20service=20bug.=20Fix=20t?= =?UTF-8?q?he=20issue=20of=20significant=20differences=20in=20the=20genera?= =?UTF-8?q?ted=20code=20every=20=E2=80=A6=20(#3260)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/gf/internal/cmd/genservice/genservice.go | 2 +- .../cmd/genservice/genservice_calculate.go | 16 ++++++------ .../cmd/genservice/genservice_generate.go | 25 ++++++++++++------- 3 files changed, 26 insertions(+), 17 deletions(-) diff --git a/cmd/gf/internal/cmd/genservice/genservice.go b/cmd/gf/internal/cmd/genservice/genservice.go index e1ef5dc74ce..c15a70433c5 100644 --- a/cmd/gf/internal/cmd/genservice/genservice.go +++ b/cmd/gf/internal/cmd/genservice/genservice.go @@ -174,7 +174,7 @@ func (c CGenService) Service(ctx context.Context, in CGenServiceInput) (out *CGe // Parse single logic package folder. var ( // StructName => FunctionDefinitions - srcPkgInterfaceMap = make(map[string]*garray.StrArray) + srcPkgInterfaceMap = gmap.NewListMap() srcImportedPackages = garray.NewSortedStrArray().SetUnique(true) importAliasToPathMap = gmap.NewStrStrMap() // for conflict imports check. alias => import path(with `"`) importPathToAliasMap = gmap.NewStrStrMap() // for conflict imports check. import path(with `"`) => alias diff --git a/cmd/gf/internal/cmd/genservice/genservice_calculate.go b/cmd/gf/internal/cmd/genservice/genservice_calculate.go index 68fe746184e..089b7a93c1f 100644 --- a/cmd/gf/internal/cmd/genservice/genservice_calculate.go +++ b/cmd/gf/internal/cmd/genservice/genservice_calculate.go @@ -8,6 +8,7 @@ package genservice import ( "fmt" + "github.com/gogf/gf/v2/container/gmap" "go/parser" "go/token" @@ -99,10 +100,9 @@ func (c CGenService) calculateCodeCommented(in CGenServiceInput, fileContent str } func (c CGenService) calculateInterfaceFunctions( - in CGenServiceInput, fileContent string, srcPkgInterfaceMap map[string]*garray.StrArray, + in CGenServiceInput, fileContent string, srcPkgInterfaceMap *gmap.ListMap, ) (err error) { var ( - ok bool matches [][]string srcPkgInterfaceFuncArray *garray.StrArray ) @@ -142,9 +142,11 @@ func (c CGenService) calculateInterfaceFunctions( continue } structName = gstr.CaseCamel(structMatch[1]) - if srcPkgInterfaceFuncArray, ok = srcPkgInterfaceMap[structName]; !ok { - srcPkgInterfaceMap[structName] = garray.NewStrArray() - srcPkgInterfaceFuncArray = srcPkgInterfaceMap[structName] + if !srcPkgInterfaceMap.Contains(structName) { + srcPkgInterfaceFuncArray = garray.NewStrArray() + srcPkgInterfaceMap.Set(structName, srcPkgInterfaceFuncArray) + } else { + srcPkgInterfaceFuncArray = srcPkgInterfaceMap.Get(structName).(*garray.StrArray) } srcPkgInterfaceFuncArray.Append(functionHead) } @@ -165,8 +167,8 @@ func (c CGenService) calculateInterfaceFunctions( continue } structName = gstr.CaseCamel(structMatch[1]) - if srcPkgInterfaceFuncArray, ok = srcPkgInterfaceMap[structName]; !ok { - srcPkgInterfaceMap[structName] = garray.NewStrArray() + if !srcPkgInterfaceMap.Contains(structName) { + srcPkgInterfaceMap.Set(structName, garray.NewStrArray()) } } return nil diff --git a/cmd/gf/internal/cmd/genservice/genservice_generate.go b/cmd/gf/internal/cmd/genservice/genservice_generate.go index 5b040782bbc..4753de7e849 100644 --- a/cmd/gf/internal/cmd/genservice/genservice_generate.go +++ b/cmd/gf/internal/cmd/genservice/genservice_generate.go @@ -10,6 +10,7 @@ import ( "fmt" "github.com/gogf/gf/v2/container/garray" + "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/text/gregex" @@ -23,7 +24,7 @@ import ( type generateServiceFilesInput struct { CGenServiceInput DstFilePath string // Absolute file path for generated service go file. - SrcStructFunctions map[string]*garray.StrArray + SrcStructFunctions *gmap.ListMap SrcImportedPackages []string SrcPackageName string DstPackageName string @@ -46,7 +47,8 @@ func (c CGenService) generateServiceFile(in generateServiceFilesInput) (ok bool, // Type definitions. generatedContent += "type(" generatedContent += "\n" - for structName, funcArray := range in.SrcStructFunctions { + in.SrcStructFunctions.Iterator(func(key, value interface{}) bool { + structName, funcArray := key.(string), value.(*garray.StrArray) allFuncArray.Append(funcArray.Slice()...) // Add comments to a method. for index, funcName := range funcArray.Slice() { @@ -60,7 +62,8 @@ func (c CGenService) generateServiceFile(in generateServiceFilesInput) (ok bool, "{FuncDefinition}": funcArray.Join("\n\t"), })) generatedContent += "\n" - } + return true + }) generatedContent += ")" generatedContent += "\n" @@ -70,17 +73,19 @@ func (c CGenService) generateServiceFile(in generateServiceFilesInput) (ok bool, generatingInterfaceCheck string ) // Variable definitions. - for structName := range in.SrcStructFunctions { + in.SrcStructFunctions.Iterator(func(key, value interface{}) bool { + structName := key.(string) generatingInterfaceCheck = fmt.Sprintf(`[^\w\d]+%s.I%s[^\w\d]`, in.DstPackageName, structName) if gregex.IsMatchString(generatingInterfaceCheck, generatedContent) { - continue + return true } variableContent += gstr.Trim(gstr.ReplaceByMap(consts.TemplateGenServiceContentVariable, g.MapStrStr{ "{StructName}": structName, "{InterfaceName}": "I" + structName, })) variableContent += "\n" - } + return true + }) if variableContent != "" { generatedContent += "var(" generatedContent += "\n" @@ -89,17 +94,19 @@ func (c CGenService) generateServiceFile(in generateServiceFilesInput) (ok bool, generatedContent += "\n" } // Variable register function definitions. - for structName := range in.SrcStructFunctions { + in.SrcStructFunctions.Iterator(func(key, value interface{}) bool { + structName := key.(string) generatingInterfaceCheck = fmt.Sprintf(`[^\w\d]+%s.I%s[^\w\d]`, in.DstPackageName, structName) if gregex.IsMatchString(generatingInterfaceCheck, generatedContent) { - continue + return true } generatedContent += gstr.Trim(gstr.ReplaceByMap(consts.TemplateGenServiceContentRegister, g.MapStrStr{ "{StructName}": structName, "{InterfaceName}": "I" + structName, })) generatedContent += "\n\n" - } + return true + }) // Replace empty braces that have new line. generatedContent, _ = gregex.ReplaceString(`{[\s\t]+}`, `{}`, generatedContent)