diff --git a/.example/database/gdb/mysql/config.toml b/.example/database/gdb/mysql/config.toml index beea9dcb5..0ea384859 100644 --- a/.example/database/gdb/mysql/config.toml +++ b/.example/database/gdb/mysql/config.toml @@ -4,7 +4,7 @@ [database.logger] Level = "all" Stdout = true - CtxKeys = ["Trace-Id"] + CtxKeys = ["RequestId"] [database.default] link = "mysql:root:12345678@tcp(127.0.0.1:3306)/test" debug = true diff --git a/.example/database/gdb/mysql/config/gdb.go b/.example/database/gdb/mysql/config/gdb.go index 6fb30486b..75e92e9d1 100644 --- a/.example/database/gdb/mysql/config/gdb.go +++ b/.example/database/gdb/mysql/config/gdb.go @@ -2,6 +2,7 @@ package main import ( "github.com/gogf/gf/database/gdb" + "github.com/gogf/gf/os/gctx" "sync" "time" ) @@ -24,13 +25,16 @@ func init() { } func main() { - wg := sync.WaitGroup{} + var ( + wg = sync.WaitGroup{} + ctx = gctx.New() + ) for i := 0; i < 100000; i++ { wg.Add(1) go func() { defer wg.Done() time.Sleep(10 * time.Second) - db.Table("user").Where("id=1").All() + db.Ctx(ctx).Model("user").Where("id=1").All() }() } wg.Wait() diff --git a/.example/database/gdb/mysql/gdb_all.go b/.example/database/gdb/mysql/gdb_all.go index 74830ee48..355424f03 100644 --- a/.example/database/gdb/mysql/gdb_all.go +++ b/.example/database/gdb/mysql/gdb_all.go @@ -3,26 +3,22 @@ package main import ( "fmt" "github.com/gogf/gf/frame/g" + "github.com/gogf/gf/os/gctx" ) func main() { - db := g.DB() + var ( + db = g.DB() + ctx = gctx.New() + ) // 开启调试模式,以便于记录所有执行的SQL db.SetDebug(true) - r, e := db.GetAll("SELECT * from `user` where id in(?)", g.Slice{}) + r, e := db.Ctx(ctx).GetAll("SELECT * from `user` where id in(?)", g.Slice{}) if e != nil { fmt.Println(e) } if r != nil { fmt.Println(r) } - return - //r, e := db.Table("user").Where("id in(?)", g.Slice{}).All() - //if e != nil { - // fmt.Println(e) - //} - //if r != nil { - // fmt.Println(r.List()) - //} } diff --git a/.example/database/gdb/mysql/gdb_args_slice.go b/.example/database/gdb/mysql/gdb_args_slice.go index ceebe23d1..68c346dc9 100644 --- a/.example/database/gdb/mysql/gdb_args_slice.go +++ b/.example/database/gdb/mysql/gdb_args_slice.go @@ -2,12 +2,18 @@ package main import ( "github.com/gogf/gf/frame/g" + "github.com/gogf/gf/os/gctx" ) func main() { - db := g.DB() + var ( + db = g.DB() + ctx = gctx.New() + ) - db.Table("user").Where("nickname like ? and passport like ?", g.Slice{"T3", "t3"}).OrderBy("id asc").All() + db.Ctx(ctx).Model("user"). + Where("nickname like ? and passport like ?", g.Slice{"T3", "t3"}). + OrderAsc("id").All() conditions := g.Map{ "nickname like ?": "%T%", @@ -16,8 +22,8 @@ func main() { "create_time > ?": 0, "id in(?)": g.Slice{1, 2, 3}, } - db.Table("user").Where(conditions).OrderBy("id asc").All() + db.Ctx(ctx).Model("user").Where(conditions).OrderAsc("id").All() var params []interface{} - db.Table("user").Where("1=1", params).OrderBy("id asc").All() + db.Ctx(ctx).Model("user").Where("1=1", params).OrderAsc("id").All() } diff --git a/.example/database/gdb/mysql/gdb_batch_insert.go b/.example/database/gdb/mysql/gdb_batch_insert.go index 171bb9fb4..62c8a2e38 100644 --- a/.example/database/gdb/mysql/gdb_batch_insert.go +++ b/.example/database/gdb/mysql/gdb_batch_insert.go @@ -3,10 +3,14 @@ package main import ( "fmt" "github.com/gogf/gf/frame/g" + "github.com/gogf/gf/os/gctx" ) func main() { - db := g.DB() + var ( + db = g.DB() + ctx = gctx.New() + ) db.SetDebug(true) list := make(g.List, 0) for i := 0; i < 100; i++ { @@ -14,7 +18,7 @@ func main() { "name": fmt.Sprintf(`name_%d`, i), }) } - r, e := db.Table("user").Data(list).Batch(2).Insert() + r, e := db.Ctx(ctx).Model("user").Data(list).Batch(2).Insert() if e != nil { panic(e) } diff --git a/.example/database/gdb/mysql/gdb_binary.go b/.example/database/gdb/mysql/gdb_binary.go index f3d234736..eeba8987e 100644 --- a/.example/database/gdb/mysql/gdb_binary.go +++ b/.example/database/gdb/mysql/gdb_binary.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "github.com/gogf/gf/os/gctx" "github.com/gogf/gf/crypto/gaes" "github.com/gogf/gf/database/gdb" @@ -19,6 +20,9 @@ func main() { Role: "master", Charset: "utf8", }) + var ( + ctx = gctx.New() + ) db, err := gdb.New() if err != nil { panic(err) @@ -33,7 +37,7 @@ func main() { } // 写入 - r, err := db.Table("user").Data(g.Map{ + r, err := db.Ctx(ctx).Model("user").Data(g.Map{ "uid": 1, "name": encryptedName, }).Save() @@ -43,9 +47,9 @@ func main() { fmt.Println(r.RowsAffected()) // 查询 - one, err := db.Table("user").Where("name=?", encryptedName).One() + one, err := db.Ctx(ctx).Model("user").Where("name=?", encryptedName).One() if err != nil { fmt.Println(err) } - fmt.Println(one.ToMap()) + fmt.Println(one.Map()) } diff --git a/.example/database/gdb/mysql/gdb_bit.go b/.example/database/gdb/mysql/gdb_bit.go index b7da01292..ce2c729e0 100644 --- a/.example/database/gdb/mysql/gdb_bit.go +++ b/.example/database/gdb/mysql/gdb_bit.go @@ -2,19 +2,23 @@ package main import ( "fmt" + "github.com/gogf/gf/os/gctx" "github.com/gogf/gf/frame/g" ) func main() { - db := g.DB() + var ( + db = g.DB() + ctx = gctx.New() + ) db.SetDebug(true) - r, e := db.Table("test").All() + r, e := db.Ctx(ctx).Model("test").All() if e != nil { panic(e) } if r != nil { - fmt.Println(r.ToList()) + fmt.Println(r.List()) } } diff --git a/.example/database/gdb/mysql/gdb_cache.go b/.example/database/gdb/mysql/gdb_cache.go index cefc858da..90f812ff2 100644 --- a/.example/database/gdb/mysql/gdb_cache.go +++ b/.example/database/gdb/mysql/gdb_cache.go @@ -2,6 +2,7 @@ package main import ( "github.com/gogf/gf/database/gdb" + "github.com/gogf/gf/os/gctx" "github.com/gogf/gf/util/gutil" "time" ) @@ -17,6 +18,9 @@ func main() { Role: "master", Charset: "utf8", }) + var ( + ctx = gctx.New() + ) db, err := gdb.New() if err != nil { panic(err) @@ -27,7 +31,7 @@ func main() { // 执行2次查询并将查询结果缓存3秒,并可执行缓存名称(可选) for i := 0; i < 3; i++ { - r, _ := db.Table("user").Cache(3000*time.Second).Where("id=?", 1).One() + r, _ := db.Ctx(ctx).Model("user").Cache(3000*time.Second).Where("id=?", 1).One() gutil.Dump(r.Map()) } diff --git a/.example/database/gdb/mysql/gdb_complecated.go b/.example/database/gdb/mysql/gdb_complecated.go index 0f8a9906f..eeaddebe3 100644 --- a/.example/database/gdb/mysql/gdb_complecated.go +++ b/.example/database/gdb/mysql/gdb_complecated.go @@ -6,7 +6,7 @@ import ( func main() { // error! - r, err := g.DB().Table("user").Where(g.Map{ + r, err := g.DB().Model("user").Where(g.Map{ "or": g.Map{ "nickname": "jim", "create_time > ": "2019-10-01", diff --git a/.example/database/gdb/mysql/gdb_config.go b/.example/database/gdb/mysql/gdb_config.go index cb88e2d89..4f6a809a3 100644 --- a/.example/database/gdb/mysql/gdb_config.go +++ b/.example/database/gdb/mysql/gdb_config.go @@ -7,7 +7,7 @@ import ( ) func main() { - if r, err := g.DB().Table("user").Where("uid=?", 1).One(); err == nil { + if r, err := g.DB().Model("user").Where("uid=?", 1).One(); err == nil { fmt.Println(r["uid"].Int()) fmt.Println(r["name"].String()) } else { diff --git a/.example/database/gdb/mysql/gdb_config2.go b/.example/database/gdb/mysql/gdb_config2.go index dfe80bc19..ca6fb4ebd 100644 --- a/.example/database/gdb/mysql/gdb_config2.go +++ b/.example/database/gdb/mysql/gdb_config2.go @@ -8,7 +8,7 @@ import ( func main() { g.Config().SetFileName("config2.toml") - if r, err := g.DB().Table("user").Where("uid=?", 1).One(); err == nil { + if r, err := g.DB().Model("user").Where("uid=?", 1).One(); err == nil { fmt.Println(r["uid"].Int()) fmt.Println(r["name"].String()) } else { diff --git a/.example/database/gdb/mysql/gdb_config3.go b/.example/database/gdb/mysql/gdb_config3.go index 11a531d55..576e622fd 100644 --- a/.example/database/gdb/mysql/gdb_config3.go +++ b/.example/database/gdb/mysql/gdb_config3.go @@ -8,14 +8,14 @@ import ( func main() { g.Config().SetFileName("config3.toml") - if r, err := g.DB().Table("user").Where("uid=?", 1).One(); err == nil { + if r, err := g.DB().Model("user").Where("uid=?", 1).One(); err == nil { fmt.Println(r["uid"].Int()) fmt.Println(r["name"].String()) } else { fmt.Println(err) } - if r, err := g.DB("user").Table("user").Where("uid=?", 1).One(); err == nil { + if r, err := g.DB("user").Model("user").Where("uid=?", 1).One(); err == nil { fmt.Println(r["uid"].Int()) fmt.Println(r["name"].String()) } else { diff --git a/.example/database/gdb/mysql/gdb_ctx.go b/.example/database/gdb/mysql/gdb_ctx.go index c296b59ba..0572f08c2 100644 --- a/.example/database/gdb/mysql/gdb_ctx.go +++ b/.example/database/gdb/mysql/gdb_ctx.go @@ -6,7 +6,7 @@ import ( ) func main() { - ctx := context.WithValue(context.Background(), "Trace-Id", "123456789") + ctx := context.WithValue(context.Background(), "RequestId", "123456789") _, err := g.DB().Ctx(ctx).Query("SELECT 1") if err != nil { panic(err) diff --git a/.example/database/gdb/mysql/gdb_ctx_model.go b/.example/database/gdb/mysql/gdb_ctx_model.go index ba7b83c02..fec1663f0 100644 --- a/.example/database/gdb/mysql/gdb_ctx_model.go +++ b/.example/database/gdb/mysql/gdb_ctx_model.go @@ -6,7 +6,7 @@ import ( ) func main() { - ctx := context.WithValue(context.Background(), "Trace-Id", "123456789") + ctx := context.WithValue(context.Background(), "RequestId", "123456789") _, err := g.DB().Model("user").Ctx(ctx).All() if err != nil { panic(err) diff --git a/.example/database/gdb/mysql/gdb_datetime.go b/.example/database/gdb/mysql/gdb_datetime.go index 440e70f1f..1a4677bb9 100644 --- a/.example/database/gdb/mysql/gdb_datetime.go +++ b/.example/database/gdb/mysql/gdb_datetime.go @@ -2,23 +2,20 @@ package main import ( "fmt" + "github.com/gogf/gf/os/gctx" "github.com/gogf/gf/frame/g" "github.com/gogf/gf/os/gtime" ) func main() { - db := g.Database() + var ( + db = g.DB() + ctx = gctx.New() + ) db.SetDebug(true) - //r, err := db.Table("user").Data("create_time", gtime.Now().String()).Insert() - //if err == nil { - // fmt.Println(r.LastInsertId()) - //} else { - // panic(err) - //} - - r, err := db.Table("user").Data(g.Map{ + r, err := db.Ctx(ctx).Model("user").Data(g.Map{ "name": "john", "create_time": gtime.Now().String(), }).Insert() diff --git a/.example/database/gdb/mysql/gdb_debug1.go b/.example/database/gdb/mysql/gdb_debug1.go index 9a3bc10e3..ecbceffe3 100644 --- a/.example/database/gdb/mysql/gdb_debug1.go +++ b/.example/database/gdb/mysql/gdb_debug1.go @@ -3,6 +3,7 @@ package main import ( "github.com/gogf/gf/database/gdb" "github.com/gogf/gf/frame/g" + "github.com/gogf/gf/os/gctx" "github.com/gogf/gf/os/glog" ) @@ -17,6 +18,9 @@ func main() { Role: "master", Charset: "utf8", }) + var ( + ctx = gctx.New() + ) db, err := gdb.New() if err != nil { panic(err) @@ -27,11 +31,11 @@ func main() { // 执行3条SQL查询 for i := 1; i <= 3; i++ { - db.Table("user").Where("uid=?", i).One() + db.Ctx(ctx).Model("user").Where("uid=?", i).One() } // 构造一条错误查询 - db.Table("user").Where("no_such_field=?", "just_test").One() + db.Model("user").Where("no_such_field=?", "just_test").One() - db.Table("user").Data(g.Map{"name": "smith"}).Where("uid=?", 1).Save() + db.Ctx(ctx).Model("user").Data(g.Map{"name": "smith"}).Where("uid=?", 1).Save() } diff --git a/.example/database/gdb/mysql/gdb_debug2.go b/.example/database/gdb/mysql/gdb_debug2.go index 0ed29c2a7..2480dc420 100644 --- a/.example/database/gdb/mysql/gdb_debug2.go +++ b/.example/database/gdb/mysql/gdb_debug2.go @@ -2,17 +2,21 @@ package main import ( "github.com/gogf/gf/frame/g" + "github.com/gogf/gf/os/gctx" ) func main() { - db := g.DB() + var ( + db = g.DB() + ctx = gctx.New() + ) // 执行3条SQL查询 for i := 1; i <= 3; i++ { - db.Table("user").Where("id=?", i).One() + db.Ctx(ctx).Model("user").Where("id=?", i).One() } // 构造一条错误查询 - db.Table("user").Where("no_such_field=?", "just_test").One() + db.Ctx(ctx).Model("user").Where("no_such_field=?", "just_test").One() - db.Table("user").Data(g.Map{"name": "smith"}).Where("uid=?", 1).Save() + db.Ctx(ctx).Model("user").Data(g.Map{"name": "smith"}).Where("uid=?", 1).Save() } diff --git a/.example/database/gdb/mysql/gdb_insert.go b/.example/database/gdb/mysql/gdb_insert.go index a6afa8491..61a0bd35b 100644 --- a/.example/database/gdb/mysql/gdb_insert.go +++ b/.example/database/gdb/mysql/gdb_insert.go @@ -18,7 +18,7 @@ func main() { db.SetDebug(true) - r, e := db.Table("user").Data(g.Map{ + r, e := db.Model("user").Data(g.Map{ "create_at": "now()", }).Unscoped().Insert() if e != nil { diff --git a/.example/database/gdb/mysql/gdb_issue_278.go b/.example/database/gdb/mysql/gdb_issue_278.go index 2f18da921..160b9f317 100644 --- a/.example/database/gdb/mysql/gdb_issue_278.go +++ b/.example/database/gdb/mysql/gdb_issue_278.go @@ -8,7 +8,7 @@ import ( var ( tableName = "orders" - dao = g.DB().Table(tableName).Safe() + dao = g.DB().Model(tableName).Safe() ) type OrderServiceEntity struct { diff --git a/.example/database/gdb/mysql/gdb_json_xml.go b/.example/database/gdb/mysql/gdb_json_xml.go index 7a273b884..8be1b9163 100644 --- a/.example/database/gdb/mysql/gdb_json_xml.go +++ b/.example/database/gdb/mysql/gdb_json_xml.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "github.com/gogf/gf/os/gctx" "github.com/gogf/gf/database/gdb" "github.com/gogf/gf/encoding/gparser" @@ -19,19 +20,22 @@ func main() { Role: "master", Charset: "utf8", }) - db := g.DB() - one, err := db.Table("user").Where("id=?", 1).One() + var ( + db = g.DB() + ctx = gctx.New() + ) + one, err := db.Ctx(ctx).Model("user").Where("id=?", 1).One() if err != nil { panic(err) } // 使用内置方法转换为json/xml - fmt.Println(one.ToJson()) - fmt.Println(one.ToXml()) + fmt.Println(one.Json()) + fmt.Println(one.Xml()) // 自定义方法方法转换为json/xml - jsonContent, _ := gparser.VarToJson(one.ToMap()) + jsonContent, _ := gparser.VarToJson(one.Map()) fmt.Println(string(jsonContent)) - xmlContent, _ := gparser.VarToXml(one.ToMap()) + xmlContent, _ := gparser.VarToXml(one.Map()) fmt.Println(string(xmlContent)) } diff --git a/.example/database/gdb/mysql/gdb_pool.go b/.example/database/gdb/mysql/gdb_pool.go index 0a435d618..dcfdd063a 100644 --- a/.example/database/gdb/mysql/gdb_pool.go +++ b/.example/database/gdb/mysql/gdb_pool.go @@ -1,20 +1,24 @@ package main import ( + "github.com/gogf/gf/os/gctx" "time" "github.com/gogf/gf/frame/g" ) func main() { - db := g.DB() + var ( + db = g.DB() + ctx = gctx.New() + ) // 开启调试模式,以便于记录所有执行的SQL db.SetDebug(true) for { for i := 0; i < 10; i++ { - go db.Table("user").All() + go db.Ctx(ctx).Model("user").All() } time.Sleep(time.Millisecond * 100) } diff --git a/.example/database/gdb/mysql/gdb_reconnect.go b/.example/database/gdb/mysql/gdb_reconnect.go index 18d53ef14..fbbb594d9 100644 --- a/.example/database/gdb/mysql/gdb_reconnect.go +++ b/.example/database/gdb/mysql/gdb_reconnect.go @@ -3,14 +3,18 @@ package main import ( "fmt" "github.com/gogf/gf/frame/g" + "github.com/gogf/gf/os/gctx" "time" ) func main() { - db := g.DB() + var ( + db = g.DB() + ctx = gctx.New() + ) db.SetDebug(true) for { - r, err := db.Table("user").All() + r, err := db.Ctx(ctx).Model("user").All() fmt.Println(err) fmt.Println(r) time.Sleep(time.Second * 10) diff --git a/.example/database/gdb/mysql/gdb_struct.go b/.example/database/gdb/mysql/gdb_struct.go index 6aa5b8830..dfe401475 100644 --- a/.example/database/gdb/mysql/gdb_struct.go +++ b/.example/database/gdb/mysql/gdb_struct.go @@ -17,7 +17,7 @@ func main() { } user := (*User)(nil) fmt.Println(user) - err := db.Table("test").Where("id=1").Struct(&user) + err := db.Model("test").Where("id=1").Scan(&user) fmt.Println(err) fmt.Println(user) } diff --git a/.example/database/gdb/mysql/gdb_tables.go b/.example/database/gdb/mysql/gdb_tables.go index 8dbf2d222..6c84b9e1a 100644 --- a/.example/database/gdb/mysql/gdb_tables.go +++ b/.example/database/gdb/mysql/gdb_tables.go @@ -2,13 +2,17 @@ package main import ( "github.com/gogf/gf/frame/g" + "github.com/gogf/gf/os/gctx" ) func main() { - db := g.DB() + var ( + db = g.DB() + ctx = gctx.New() + ) db.SetDebug(true) - tables, err := db.Tables() + tables, err := db.Tables(ctx) if err != nil { panic(err) } diff --git a/.example/database/gdb/mysql/gdb_tables_fields.go b/.example/database/gdb/mysql/gdb_tables_fields.go index 3f5409b95..fe6e412b5 100644 --- a/.example/database/gdb/mysql/gdb_tables_fields.go +++ b/.example/database/gdb/mysql/gdb_tables_fields.go @@ -2,20 +2,24 @@ package main import ( "github.com/gogf/gf/frame/g" + "github.com/gogf/gf/os/gctx" ) func main() { - db := g.DB() + var ( + db = g.DB() + ctx = gctx.New() + ) db.SetDebug(true) - tables, e := db.Tables() + tables, e := db.Tables(ctx) if e != nil { panic(e) } if tables != nil { g.Dump(tables) for _, table := range tables { - fields, err := db.TableFields(table) + fields, err := db.TableFields(ctx, table) if err != nil { panic(err) } diff --git a/.example/database/gdb/mysql/gdb_transaction_closure.go b/.example/database/gdb/mysql/gdb_transaction_closure.go index aa05d48d4..9d38aef51 100644 --- a/.example/database/gdb/mysql/gdb_transaction_closure.go +++ b/.example/database/gdb/mysql/gdb_transaction_closure.go @@ -1,26 +1,29 @@ package main import ( + "context" "github.com/gogf/gf/database/gdb" "github.com/gogf/gf/frame/g" + "github.com/gogf/gf/os/gctx" ) func main() { var ( err error db = g.DB() + ctx = gctx.New() table = "user" ) - if err = db.Transaction(func(tx *gdb.TX) error { + if err = db.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error { // Nested transaction 1. - if err = tx.Transaction(func(tx *gdb.TX) error { + if err = tx.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error { _, err = tx.Model(table).Data(g.Map{"id": 1, "name": "john"}).Insert() return err }); err != nil { return err } // Nested transaction 2, panic. - if err = tx.Transaction(func(tx *gdb.TX) error { + if err = tx.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error { _, err = tx.Model(table).Data(g.Map{"id": 2, "name": "smith"}).Insert() // Create a panic that can make this transaction rollback automatically. panic("error") diff --git a/.example/database/gdb/mysql/gdb_update_field.go b/.example/database/gdb/mysql/gdb_update_field.go index c824f4176..9b420db20 100644 --- a/.example/database/gdb/mysql/gdb_update_field.go +++ b/.example/database/gdb/mysql/gdb_update_field.go @@ -12,7 +12,7 @@ import ( func main() { db := g.DB() table := "medicine_clinics_upload_yinchuan" - list, err := db.Table(table).All() + list, err := db.Model(table).All() if err != nil && err != sql.ErrNoRows { panic(err) } diff --git a/.example/database/gdb/mysql/gdb_update_union.go b/.example/database/gdb/mysql/gdb_update_union.go index a0e14b7c0..cf51e548a 100644 --- a/.example/database/gdb/mysql/gdb_update_union.go +++ b/.example/database/gdb/mysql/gdb_update_union.go @@ -9,7 +9,7 @@ import ( func main() { db := g.DB() db.SetDebug(true) - result, err := db.Table("pw_passageway m,pw_template t").Data("t.status", 99).Where("m.templateId=t.id AND m.status = 0").Update() + result, err := db.Model("pw_passageway m,pw_template t").Data("t.status", 99).Where("m.templateId=t.id AND m.status = 0").Update() if err != nil { panic(err) } diff --git a/.example/database/gdb/mysql/gdb_value.go b/.example/database/gdb/mysql/gdb_value.go index 3ba996e67..3909df5d5 100644 --- a/.example/database/gdb/mysql/gdb_value.go +++ b/.example/database/gdb/mysql/gdb_value.go @@ -6,7 +6,7 @@ import ( ) func main() { - one, err := g.DB().Table("carlist c"). + one, err := g.Model("carlist c"). LeftJoin("cardetail d", "c.postid=d.carid"). Where("c.postid", "142039140032006"). Fields("c.*,d.*").One() diff --git a/.example/database/gdb/mysql/gdb_with_insert.go b/.example/database/gdb/mysql/gdb_with_insert.go index 669ab3ce6..b7ef3a15b 100644 --- a/.example/database/gdb/mysql/gdb_with_insert.go +++ b/.example/database/gdb/mysql/gdb_with_insert.go @@ -1,9 +1,11 @@ package main import ( + "context" "fmt" "github.com/gogf/gf/database/gdb" "github.com/gogf/gf/frame/g" + "github.com/gogf/gf/os/gctx" "github.com/gogf/gf/util/gmeta" ) @@ -30,13 +32,13 @@ func main() { } db := g.DB() - db.Transaction(func(tx *gdb.TX) error { + err := db.Transaction(gctx.New(), func(ctx context.Context, tx *gdb.TX) error { for i := 1; i <= 5; i++ { // User. user := User{ Name: fmt.Sprintf(`name_%d`, i), } - lastInsertId, err := db.Model(user).Data(user).OmitEmpty().InsertAndGetId() + lastInsertId, err := db.Ctx(ctx).Model(user).Data(user).OmitEmpty().InsertAndGetId() if err != nil { return err } @@ -45,7 +47,7 @@ func main() { Uid: int(lastInsertId), Address: fmt.Sprintf(`address_%d`, lastInsertId), } - _, err = db.Model(userDetail).Data(userDetail).OmitEmpty().Insert() + _, err = db.Ctx(ctx).Model(userDetail).Data(userDetail).OmitEmpty().Insert() if err != nil { return err } @@ -55,7 +57,7 @@ func main() { Uid: int(lastInsertId), Score: j, } - _, err = db.Model(userScore).Data(userScore).OmitEmpty().Insert() + _, err = db.Ctx(ctx).Model(userScore).Data(userScore).OmitEmpty().Insert() if err != nil { return err } @@ -63,4 +65,5 @@ func main() { } return nil }) + fmt.Println(err) } diff --git a/.example/database/gdb/mysql/issue364.go b/.example/database/gdb/mysql/issue364.go index cae5f6ace..164a8a9bd 100644 --- a/.example/database/gdb/mysql/issue364.go +++ b/.example/database/gdb/mysql/issue364.go @@ -9,7 +9,7 @@ func test1() { db := g.DB() db.SetDebug(true) time.Sleep(1 * time.Minute) - r, e := db.Table("test").Where("id", 10000).Count() + r, e := db.Model("test").Where("id", 10000).Count() if e != nil { panic(e) } @@ -19,7 +19,7 @@ func test1() { func test2() { db := g.DB() db.SetDebug(true) - dao := db.Table("test").Safe() + dao := db.Model("test").Safe() time.Sleep(1 * time.Minute) r, e := dao.Where("id", 10000).Count() if e != nil { diff --git a/container/gmap/gmap_hash_any_any_map.go b/container/gmap/gmap_hash_any_any_map.go index a42cf26ea..3544d0648 100644 --- a/container/gmap/gmap_hash_any_any_map.go +++ b/container/gmap/gmap_hash_any_any_map.go @@ -460,7 +460,7 @@ func (m *AnyAnyMap) Merge(other *AnyAnyMap) { // String returns the map as a string. func (m *AnyAnyMap) String() string { b, _ := m.MarshalJSON() - return gconv.UnsafeBytesToStr(b) + return string(b) } // MarshalJSON implements the interface MarshalJSON for json.Marshal. diff --git a/container/gmap/gmap_hash_int_any_map.go b/container/gmap/gmap_hash_int_any_map.go index f99fd77d4..5ced8024f 100644 --- a/container/gmap/gmap_hash_int_any_map.go +++ b/container/gmap/gmap_hash_int_any_map.go @@ -458,7 +458,7 @@ func (m *IntAnyMap) Merge(other *IntAnyMap) { // String returns the map as a string. func (m *IntAnyMap) String() string { b, _ := m.MarshalJSON() - return gconv.UnsafeBytesToStr(b) + return string(b) } // MarshalJSON implements the interface MarshalJSON for json.Marshal. diff --git a/container/gmap/gmap_hash_int_int_map.go b/container/gmap/gmap_hash_int_int_map.go index 3f8b8d411..5ca359630 100644 --- a/container/gmap/gmap_hash_int_int_map.go +++ b/container/gmap/gmap_hash_int_int_map.go @@ -429,7 +429,7 @@ func (m *IntIntMap) Merge(other *IntIntMap) { // String returns the map as a string. func (m *IntIntMap) String() string { b, _ := m.MarshalJSON() - return gconv.UnsafeBytesToStr(b) + return string(b) } // MarshalJSON implements the interface MarshalJSON for json.Marshal. diff --git a/container/gmap/gmap_hash_int_str_map.go b/container/gmap/gmap_hash_int_str_map.go index c5f5ac323..df5a655d8 100644 --- a/container/gmap/gmap_hash_int_str_map.go +++ b/container/gmap/gmap_hash_int_str_map.go @@ -429,7 +429,7 @@ func (m *IntStrMap) Merge(other *IntStrMap) { // String returns the map as a string. func (m *IntStrMap) String() string { b, _ := m.MarshalJSON() - return gconv.UnsafeBytesToStr(b) + return string(b) } // MarshalJSON implements the interface MarshalJSON for json.Marshal. diff --git a/container/gmap/gmap_hash_str_any_map.go b/container/gmap/gmap_hash_str_any_map.go index 04d70f664..802cd09db 100644 --- a/container/gmap/gmap_hash_str_any_map.go +++ b/container/gmap/gmap_hash_str_any_map.go @@ -454,7 +454,7 @@ func (m *StrAnyMap) Merge(other *StrAnyMap) { // String returns the map as a string. func (m *StrAnyMap) String() string { b, _ := m.MarshalJSON() - return gconv.UnsafeBytesToStr(b) + return string(b) } // MarshalJSON implements the interface MarshalJSON for json.Marshal. diff --git a/container/gmap/gmap_hash_str_int_map.go b/container/gmap/gmap_hash_str_int_map.go index 7bc03cd34..f01fcaa8d 100644 --- a/container/gmap/gmap_hash_str_int_map.go +++ b/container/gmap/gmap_hash_str_int_map.go @@ -432,7 +432,7 @@ func (m *StrIntMap) Merge(other *StrIntMap) { // String returns the map as a string. func (m *StrIntMap) String() string { b, _ := m.MarshalJSON() - return gconv.UnsafeBytesToStr(b) + return string(b) } // MarshalJSON implements the interface MarshalJSON for json.Marshal. diff --git a/container/gmap/gmap_hash_str_str_map.go b/container/gmap/gmap_hash_str_str_map.go index ae68640c8..cfbc945b2 100644 --- a/container/gmap/gmap_hash_str_str_map.go +++ b/container/gmap/gmap_hash_str_str_map.go @@ -432,7 +432,7 @@ func (m *StrStrMap) Merge(other *StrStrMap) { // String returns the map as a string. func (m *StrStrMap) String() string { b, _ := m.MarshalJSON() - return gconv.UnsafeBytesToStr(b) + return string(b) } // MarshalJSON implements the interface MarshalJSON for json.Marshal. diff --git a/container/gmap/gmap_list_map.go b/container/gmap/gmap_list_map.go index 790998da7..805b565f1 100644 --- a/container/gmap/gmap_list_map.go +++ b/container/gmap/gmap_list_map.go @@ -513,7 +513,7 @@ func (m *ListMap) Merge(other *ListMap) { // String returns the map as a string. func (m *ListMap) String() string { b, _ := m.MarshalJSON() - return gconv.UnsafeBytesToStr(b) + return string(b) } // MarshalJSON implements the interface MarshalJSON for json.Marshal. diff --git a/container/gring/gring.go b/container/gring/gring.go index ac308f56c..9114558c4 100644 --- a/container/gring/gring.go +++ b/container/gring/gring.go @@ -23,6 +23,11 @@ type Ring struct { dirty *gtype.Bool // Dirty, which means the len and cap should be recalculated. It's marked dirty when the size of ring changes. } +// internalRingItem stores the ring element value. +type internalRingItem struct { + Value interface{} +} + // New creates and returns a Ring structure of elements. // The optional parameter specifies whether using this structure in concurrent safety, // which is false in default. @@ -38,10 +43,13 @@ func New(cap int, safe ...bool) *Ring { // Val returns the item's value of current position. func (r *Ring) Val() interface{} { + var value interface{} r.mu.RLock() - v := r.ring.Value + if r.ring.Value != nil { + value = r.ring.Value.(internalRingItem).Value + } r.mu.RUnlock() - return v + return value } // Len returns the size of ring. @@ -61,17 +69,21 @@ func (r *Ring) checkAndUpdateLenAndCap() { if !r.dirty.Val() { return } + r.mu.RLock() + defer r.mu.RUnlock() totalLen := 0 emptyLen := 0 if r.ring != nil { - r.mu.RLock() + if r.ring.Value == nil { + emptyLen++ + } + totalLen++ for p := r.ring.Next(); p != r.ring; p = p.Next() { if p.Value == nil { emptyLen++ } totalLen++ } - r.mu.RUnlock() } r.cap.Set(totalLen) r.len.Set(totalLen - emptyLen) @@ -84,18 +96,18 @@ func (r *Ring) Set(value interface{}) *Ring { if r.ring.Value == nil { r.len.Add(1) } - r.ring.Value = value + r.ring.Value = internalRingItem{Value: value} r.mu.Unlock() return r } -// Put sets to current item of ring and moves position to next item. +// Put sets `value` to current item of ring and moves position to next item. func (r *Ring) Put(value interface{}) *Ring { r.mu.Lock() if r.ring.Value == nil { r.len.Add(1) } - r.ring.Value = value + r.ring.Value = internalRingItem{Value: value} r.ring = r.ring.Next() r.mu.Unlock() return r @@ -132,8 +144,8 @@ func (r *Ring) Next() *Ring { // // If r and s point to the same ring, linking // them removes the elements between r and s from the ring. -// The removed elements form a subring and the result is a -// reference to that subring (if no elements were removed, +// The removed elements form a sub-ring and the result is a +// reference to that sub-ring (if no elements were removed, // the result is still the original value for r.Next(), // and not nil). // @@ -155,7 +167,7 @@ func (r *Ring) Link(s *Ring) *Ring { // Unlink removes n % r.Len() elements from the ring r, starting // at r.Next(). If n % r.Len() == 0, r remains unchanged. -// The result is the removed subring. r must not be empty. +// The result is the removed sub-ring. r must not be empty. // func (r *Ring) Unlink(n int) *Ring { r.mu.Lock() @@ -166,56 +178,24 @@ func (r *Ring) Unlink(n int) *Ring { } // RLockIteratorNext iterates and locks reading forward -// with given callback function within RWMutex.RLock. -// If returns true, then it continues iterating; or false to stop. +// with given callback function `f` within RWMutex.RLock. +// If `f` returns true, then it continues iterating; or false to stop. func (r *Ring) RLockIteratorNext(f func(value interface{}) bool) { r.mu.RLock() defer r.mu.RUnlock() - if !f(r.ring.Value) { + if r.ring.Value != nil && !f(r.ring.Value.(internalRingItem).Value) { return } for p := r.ring.Next(); p != r.ring; p = p.Next() { - if !f(p.Value) { - break - } - } -} - -// RLockIteratorPrev iterates and locks reading backward -// with given callback function within RWMutex.RLock. -// If returns true, then it continues iterating; or false to stop. -func (r *Ring) RLockIteratorPrev(f func(value interface{}) bool) { - r.mu.RLock() - defer r.mu.RUnlock() - if !f(r.ring.Value) { - return - } - for p := r.ring.Prev(); p != r.ring; p = p.Prev() { - if !f(p.Value) { - break - } - } -} - -// LockIteratorNext iterates and locks writing forward -// with given callback function within RWMutex.RLock. -// If returns true, then it continues iterating; or false to stop. -func (r *Ring) LockIteratorNext(f func(item *ring.Ring) bool) { - r.mu.RLock() - defer r.mu.RUnlock() - if !f(r.ring) { - return - } - for p := r.ring.Next(); p != r.ring; p = p.Next() { - if !f(p) { + if p.Value == nil || !f(p.Value.(internalRingItem).Value) { break } } } // LockIteratorPrev iterates and locks writing backward -// with given callback function within RWMutex.RLock. -// If returns true, then it continues iterating; or false to stop. +// with given callback function `f` within RWMutex.RLock. +// If `f` returns true, then it continues iterating; or false to stop. func (r *Ring) LockIteratorPrev(f func(item *ring.Ring) bool) { r.mu.RLock() defer r.mu.RUnlock() @@ -234,12 +214,13 @@ func (r *Ring) SliceNext() []interface{} { s := make([]interface{}, 0) r.mu.RLock() if r.ring.Value != nil { - s = append(s, r.ring.Value) + s = append(s, r.ring.Value.(internalRingItem).Value) } for p := r.ring.Next(); p != r.ring; p = p.Next() { - if p.Value != nil { - s = append(s, p.Value) + if p.Value == nil { + break } + s = append(s, p.Value.(internalRingItem).Value) } r.mu.RUnlock() return s @@ -250,12 +231,13 @@ func (r *Ring) SlicePrev() []interface{} { s := make([]interface{}, 0) r.mu.RLock() if r.ring.Value != nil { - s = append(s, r.ring.Value) + s = append(s, r.ring.Value.(internalRingItem).Value) } for p := r.ring.Prev(); p != r.ring; p = p.Prev() { - if p.Value != nil { - s = append(s, p.Value) + if p.Value == nil { + break } + s = append(s, p.Value.(internalRingItem).Value) } r.mu.RUnlock() return s diff --git a/container/gring/gring_unit_test.go b/container/gring/gring_unit_test.go index 706f273a3..a226b10d2 100644 --- a/container/gring/gring_unit_test.go +++ b/container/gring/gring_unit_test.go @@ -7,7 +7,6 @@ package gring_test import ( - "container/ring" "testing" "github.com/gogf/gf/container/gring" @@ -44,6 +43,11 @@ func TestRing_Val(t *testing.T) { }) } func TestRing_CapLen(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + r := gring.New(10) + t.Assert(r.Cap(), 10) + t.Assert(r.Len(), 0) + }) gtest.C(t, func(t *gtest.T) { r := gring.New(10) r.Put("goframe") @@ -81,22 +85,22 @@ func TestRing_Link(t *testing.T) { rs := r.Link(s) t.Assert(rs.Move(2).Val(), "b") - }) } func TestRing_Unlink(t *testing.T) { gtest.C(t, func(t *gtest.T) { r := gring.New(5) - for i := 0; i < 5; i++ { - r.Put(i + 1) + for i := 1; i <= 5; i++ { + r.Put(i) } + t.Assert(r.Val(), 1) // 1 2 3 4 // 删除当前位置往后的2个数据,返回被删除的数据 // 重新计算s len s := r.Unlink(2) // 2 3 t.Assert(s.Val(), 2) - t.Assert(s.Len(), 1) + t.Assert(s.Len(), 2) }) } @@ -120,10 +124,10 @@ func TestRing_Slice(t *testing.T) { r.Set(nil) array2 := r.SliceNext() //[4 5 1 2] //返回当前位置往后不为空的元素数组,长度为4 - t.Assert(array2, g.Slice{4, 5, 1, 2}) + t.Assert(array2, g.Slice{nil, 4, 5, 1, 2}) array3 := r.SlicePrev() //[2 1 5 4] - t.Assert(array3, g.Slice{2, 1, 5, 4}) + t.Assert(array3, g.Slice{nil, 2, 1, 5, 4}) s := gring.New(ringLen) for i := 0; i < ringLen; i++ { @@ -131,106 +135,5 @@ func TestRing_Slice(t *testing.T) { } array4 := s.SlicePrev() // [] t.Assert(array4, g.Slice{1, 5, 4, 3, 2}) - - }) -} - -func TestRing_RLockIterator(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - ringLen := 5 - r := gring.New(ringLen) - - //ring不存在有值元素 - r.RLockIteratorNext(func(v interface{}) bool { - t.Assert(v, nil) - return false - }) - r.RLockIteratorNext(func(v interface{}) bool { - t.Assert(v, nil) - return true - }) - - r.RLockIteratorPrev(func(v interface{}) bool { - t.Assert(v, nil) - return true - }) - - for i := 0; i < ringLen; i++ { - r.Put(i + 1) - } - - //回调函数返回true,RLockIteratorNext遍历5次,期望值分别是1、2、3、4、5 - i := 0 - r.RLockIteratorNext(func(v interface{}) bool { - t.Assert(v, i+1) - i++ - return true - }) - - //RLockIteratorPrev遍历1次返回 false,退出遍历 - r.RLockIteratorPrev(func(v interface{}) bool { - t.Assert(v, 1) - return false - }) - - }) -} - -func TestRing_LockIterator(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - ringLen := 5 - r := gring.New(ringLen) - - //不存在有值元素 - r.LockIteratorNext(func(item *ring.Ring) bool { - t.Assert(item.Value, nil) - return false - }) - r.LockIteratorNext(func(item *ring.Ring) bool { - t.Assert(item.Value, nil) - return false - }) - r.LockIteratorNext(func(item *ring.Ring) bool { - t.Assert(item.Value, nil) - return true - }) - - r.LockIteratorPrev(func(item *ring.Ring) bool { - t.Assert(item.Value, nil) - return false - }) - r.LockIteratorPrev(func(item *ring.Ring) bool { - t.Assert(item.Value, nil) - return true - }) - - //ring初始化元素值 - for i := 0; i < ringLen; i++ { - r.Put(i + 1) - } - - //往后遍历组成数据 [1,2,3,4,5] - array1 := g.Slice{1, 2, 3, 4, 5} - ii := 0 - r.LockIteratorNext(func(item *ring.Ring) bool { - //校验每一次遍历取值是否是期望值 - t.Assert(item.Value, array1[ii]) - ii++ - return true - }) - - //往后取3个元素组成数组 - //获得 [1,5,4] - i := 0 - a := g.Slice{1, 5, 4} - r.LockIteratorPrev(func(item *ring.Ring) bool { - if i > 2 { - return false - } - t.Assert(item.Value, a[i]) - i++ - return true - }) - }) } diff --git a/container/gtype/byte.go b/container/gtype/byte.go index 3b2a8d09b..14fcafe1d 100644 --- a/container/gtype/byte.go +++ b/container/gtype/byte.go @@ -60,12 +60,12 @@ func (v *Byte) String() string { // MarshalJSON implements the interface MarshalJSON for json.Marshal. func (v *Byte) MarshalJSON() ([]byte, error) { - return gconv.UnsafeStrToBytes(strconv.FormatUint(uint64(v.Val()), 10)), nil + return []byte(strconv.FormatUint(uint64(v.Val()), 10)), nil } // UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal. func (v *Byte) UnmarshalJSON(b []byte) error { - v.Set(gconv.Uint8(gconv.UnsafeBytesToStr(b))) + v.Set(gconv.Uint8(string(b))) return nil } diff --git a/container/gtype/bytes.go b/container/gtype/bytes.go index 9574558cb..eae89a722 100644 --- a/container/gtype/bytes.go +++ b/container/gtype/bytes.go @@ -59,7 +59,7 @@ func (v *Bytes) MarshalJSON() ([]byte, error) { val := v.Val() dst := make([]byte, base64.StdEncoding.EncodedLen(len(val))) base64.StdEncoding.Encode(dst, val) - return gconv.UnsafeStrToBytes(`"` + gconv.UnsafeBytesToStr(dst) + `"`), nil + return []byte(`"` + string(dst) + `"`), nil } // UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal. diff --git a/container/gtype/float32.go b/container/gtype/float32.go index 2eaeb8960..5c2ffea03 100644 --- a/container/gtype/float32.go +++ b/container/gtype/float32.go @@ -73,12 +73,12 @@ func (v *Float32) String() string { // MarshalJSON implements the interface MarshalJSON for json.Marshal. func (v *Float32) MarshalJSON() ([]byte, error) { - return gconv.UnsafeStrToBytes(strconv.FormatFloat(float64(v.Val()), 'g', -1, 32)), nil + return []byte(strconv.FormatFloat(float64(v.Val()), 'g', -1, 32)), nil } // UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal. func (v *Float32) UnmarshalJSON(b []byte) error { - v.Set(gconv.Float32(gconv.UnsafeBytesToStr(b))) + v.Set(gconv.Float32(string(b))) return nil } diff --git a/container/gtype/float64.go b/container/gtype/float64.go index ecc80facc..9a7de8c32 100644 --- a/container/gtype/float64.go +++ b/container/gtype/float64.go @@ -73,12 +73,12 @@ func (v *Float64) String() string { // MarshalJSON implements the interface MarshalJSON for json.Marshal. func (v *Float64) MarshalJSON() ([]byte, error) { - return gconv.UnsafeStrToBytes(strconv.FormatFloat(v.Val(), 'g', -1, 64)), nil + return []byte(strconv.FormatFloat(v.Val(), 'g', -1, 64)), nil } // UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal. func (v *Float64) UnmarshalJSON(b []byte) error { - v.Set(gconv.Float64(gconv.UnsafeBytesToStr(b))) + v.Set(gconv.Float64(string(b))) return nil } diff --git a/container/gtype/int.go b/container/gtype/int.go index c1b2543f0..7c9ea774a 100644 --- a/container/gtype/int.go +++ b/container/gtype/int.go @@ -60,12 +60,12 @@ func (v *Int) String() string { // MarshalJSON implements the interface MarshalJSON for json.Marshal. func (v *Int) MarshalJSON() ([]byte, error) { - return gconv.UnsafeStrToBytes(strconv.Itoa(v.Val())), nil + return []byte(strconv.Itoa(v.Val())), nil } // UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal. func (v *Int) UnmarshalJSON(b []byte) error { - v.Set(gconv.Int(gconv.UnsafeBytesToStr(b))) + v.Set(gconv.Int(string(b))) return nil } diff --git a/container/gtype/int32.go b/container/gtype/int32.go index 63d4a5d23..07ac0acf3 100644 --- a/container/gtype/int32.go +++ b/container/gtype/int32.go @@ -60,12 +60,12 @@ func (v *Int32) String() string { // MarshalJSON implements the interface MarshalJSON for json.Marshal. func (v *Int32) MarshalJSON() ([]byte, error) { - return gconv.UnsafeStrToBytes(strconv.Itoa(int(v.Val()))), nil + return []byte(strconv.Itoa(int(v.Val()))), nil } // UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal. func (v *Int32) UnmarshalJSON(b []byte) error { - v.Set(gconv.Int32(gconv.UnsafeBytesToStr(b))) + v.Set(gconv.Int32(string(b))) return nil } diff --git a/container/gtype/int64.go b/container/gtype/int64.go index b9c356ebd..ed2a65d06 100644 --- a/container/gtype/int64.go +++ b/container/gtype/int64.go @@ -60,12 +60,12 @@ func (v *Int64) String() string { // MarshalJSON implements the interface MarshalJSON for json.Marshal. func (v *Int64) MarshalJSON() ([]byte, error) { - return gconv.UnsafeStrToBytes(strconv.FormatInt(v.Val(), 10)), nil + return []byte(strconv.FormatInt(v.Val(), 10)), nil } // UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal. func (v *Int64) UnmarshalJSON(b []byte) error { - v.Set(gconv.Int64(gconv.UnsafeBytesToStr(b))) + v.Set(gconv.Int64(string(b))) return nil } diff --git a/container/gtype/string.go b/container/gtype/string.go index 0e1483b6f..f0b89f4ca 100644 --- a/container/gtype/string.go +++ b/container/gtype/string.go @@ -55,12 +55,12 @@ func (v *String) String() string { // MarshalJSON implements the interface MarshalJSON for json.Marshal. func (v *String) MarshalJSON() ([]byte, error) { - return gconv.UnsafeStrToBytes(`"` + v.Val() + `"`), nil + return []byte(`"` + v.Val() + `"`), nil } // UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal. func (v *String) UnmarshalJSON(b []byte) error { - v.Set(gconv.UnsafeBytesToStr(bytes.Trim(b, `"`))) + v.Set(string(bytes.Trim(b, `"`))) return nil } diff --git a/container/gtype/uint.go b/container/gtype/uint.go index b9203a9af..a6e35996f 100644 --- a/container/gtype/uint.go +++ b/container/gtype/uint.go @@ -60,12 +60,12 @@ func (v *Uint) String() string { // MarshalJSON implements the interface MarshalJSON for json.Marshal. func (v *Uint) MarshalJSON() ([]byte, error) { - return gconv.UnsafeStrToBytes(strconv.FormatUint(uint64(v.Val()), 10)), nil + return []byte(strconv.FormatUint(uint64(v.Val()), 10)), nil } // UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal. func (v *Uint) UnmarshalJSON(b []byte) error { - v.Set(gconv.Uint(gconv.UnsafeBytesToStr(b))) + v.Set(gconv.Uint(string(b))) return nil } diff --git a/container/gtype/uint32.go b/container/gtype/uint32.go index 2fbdcb030..d1f4ea736 100644 --- a/container/gtype/uint32.go +++ b/container/gtype/uint32.go @@ -60,12 +60,12 @@ func (v *Uint32) String() string { // MarshalJSON implements the interface MarshalJSON for json.Marshal. func (v *Uint32) MarshalJSON() ([]byte, error) { - return gconv.UnsafeStrToBytes(strconv.FormatUint(uint64(v.Val()), 10)), nil + return []byte(strconv.FormatUint(uint64(v.Val()), 10)), nil } // UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal. func (v *Uint32) UnmarshalJSON(b []byte) error { - v.Set(gconv.Uint32(gconv.UnsafeBytesToStr(b))) + v.Set(gconv.Uint32(string(b))) return nil } diff --git a/container/gtype/uint64.go b/container/gtype/uint64.go index 580163bb5..7791eeac3 100644 --- a/container/gtype/uint64.go +++ b/container/gtype/uint64.go @@ -60,12 +60,12 @@ func (v *Uint64) String() string { // MarshalJSON implements the interface MarshalJSON for json.Marshal. func (v *Uint64) MarshalJSON() ([]byte, error) { - return gconv.UnsafeStrToBytes(strconv.FormatUint(v.Val(), 10)), nil + return []byte(strconv.FormatUint(v.Val(), 10)), nil } // UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal. func (v *Uint64) UnmarshalJSON(b []byte) error { - v.Set(gconv.Uint64(gconv.UnsafeBytesToStr(b))) + v.Set(gconv.Uint64(string(b))) return nil } diff --git a/database/gdb/gdb_core.go b/database/gdb/gdb_core.go index 58519e927..1f84516c5 100644 --- a/database/gdb/gdb_core.go +++ b/database/gdb/gdb_core.go @@ -205,20 +205,21 @@ func (c *Core) GetScan(pointer interface{}, sql string, args ...interface{}) err t := reflect.TypeOf(pointer) k := t.Kind() if k != reflect.Ptr { - return fmt.Errorf("params should be type of pointer, but got: %v", k) + return gerror.NewCodef(gcode.CodeInvalidParameter, "params should be type of pointer, but got: %v", k) } k = t.Elem().Kind() switch k { case reflect.Array, reflect.Slice: return c.db.GetCore().GetStructs(pointer, sql, args...) + case reflect.Struct: return c.db.GetCore().GetStruct(pointer, sql, args...) } - return fmt.Errorf("element type should be type of struct/slice, unsupported: %v", k) + return gerror.NewCodef(gcode.CodeInvalidParameter, "element type should be type of struct/slice, unsupported: %v", k) } // GetValue queries and returns the field value from database. -// The sql should queries only one field from database, or else it returns only one +// The sql should query only one field from database, or else it returns only one // field of the result. func (c *Core) GetValue(sql string, args ...interface{}) (Value, error) { one, err := c.db.GetOne(sql, args...) @@ -392,7 +393,7 @@ func (c *Core) DoInsert(ctx context.Context, link Link, table string, list List, params []interface{} // Values that will be committed to underlying database driver. onDuplicateStr string // onDuplicateStr is used in "ON DUPLICATE KEY UPDATE" statement. ) - // Handle the field names and place holders. + // Handle the field names and placeholders. for k, _ := range list[0] { keys = append(keys, k) } @@ -423,7 +424,7 @@ func (c *Core) DoInsert(ctx context.Context, link Link, table string, list List, } } valueHolder = append(valueHolder, "("+gstr.Join(values, ",")+")") - // Batch package checks: It meets the batch number or it is the last element. + // Batch package checks: It meets the batch number, or it is the last element. if len(valueHolder) == option.BatchCount || (i == listLength-1 && len(valueHolder) > 0) { r, err := c.db.DoExec(ctx, link, fmt.Sprintf( "%s INTO %s(%s) VALUES%s %s", diff --git a/database/gdb/gdb_core_transaction.go b/database/gdb/gdb_core_transaction.go index 0252f1096..f71c9c4e5 100644 --- a/database/gdb/gdb_core_transaction.go +++ b/database/gdb/gdb_core_transaction.go @@ -9,7 +9,8 @@ package gdb import ( "context" "database/sql" - "fmt" + "github.com/gogf/gf/errors/gcode" + "github.com/gogf/gf/errors/gerror" "reflect" "github.com/gogf/gf/container/gtype" @@ -117,8 +118,12 @@ func (c *Core) Transaction(ctx context.Context, f func(ctx context.Context, tx * tx.ctx = WithTX(tx.ctx, tx) defer func() { if err == nil { - if e := recover(); e != nil { - err = fmt.Errorf("%v", e) + if exception := recover(); exception != nil { + if v, ok := exception.(error); ok { + err = v + } else { + err = gerror.NewCodef(gcode.CodeInternalError, "%+v", exception) + } } } if err != nil { @@ -307,8 +312,12 @@ func (tx *TX) Transaction(ctx context.Context, f func(ctx context.Context, tx *T } defer func() { if err == nil { - if e := recover(); e != nil { - err = fmt.Errorf("%v", e) + if exception := recover(); exception != nil { + if v, ok := exception.(error); ok { + err = v + } else { + err = gerror.NewCodef(gcode.CodeInternalError, "%+v", exception) + } } } if err != nil { @@ -398,21 +407,21 @@ func (tx *TX) GetScan(pointer interface{}, sql string, args ...interface{}) erro t := reflect.TypeOf(pointer) k := t.Kind() if k != reflect.Ptr { - return fmt.Errorf("params should be type of pointer, but got: %v", k) + return gerror.NewCodef(gcode.CodeInvalidParameter, "params should be type of pointer, but got: %v", k) } k = t.Elem().Kind() switch k { case reflect.Array, reflect.Slice: return tx.GetStructs(pointer, sql, args...) + case reflect.Struct: return tx.GetStruct(pointer, sql, args...) - default: - return fmt.Errorf("element type should be type of struct/slice, unsupported: %v", k) } + return gerror.NewCodef(gcode.CodeInvalidParameter, "element type should be type of struct/slice, unsupported: %v", k) } // GetValue queries and returns the field value from database. -// The sql should queries only one field from database, or else it returns only one +// The sql should query only one field from database, or else it returns only one // field of the result. func (tx *TX) GetValue(sql string, args ...interface{}) (Value, error) { one, err := tx.GetOne(sql, args...) diff --git a/database/gdb/gdb_model.go b/database/gdb/gdb_model.go index e7d4f823f..717ab6e01 100644 --- a/database/gdb/gdb_model.go +++ b/database/gdb/gdb_model.go @@ -57,7 +57,7 @@ type Model struct { type ModelHandler func(m *Model) *Model // ChunkHandler is a function that is used in function Chunk, which handles given Result and error. -// It returns true if it wants continue chunking, or else it returns false to stop chunking. +// It returns true if it wants to continue chunking, or else it returns false to stop chunking. type ChunkHandler func(result Result, err error) bool // ModelWhereHolder is the holder for where condition preparing. diff --git a/database/gdb/gdb_model_condition.go b/database/gdb/gdb_model_condition.go index 2ff16eb4c..9a6d4ac50 100644 --- a/database/gdb/gdb_model_condition.go +++ b/database/gdb/gdb_model_condition.go @@ -62,7 +62,7 @@ func (m *Model) WherePri(where interface{}, args ...interface{}) *Model { } // Wheref builds condition string using fmt.Sprintf and arguments. -// Note that if the number of `args` is more than the place holder in `format`, +// Note that if the number of `args` is more than the placeholder in `format`, // the extra `args` will be used as the where condition arguments of the Model. func (m *Model) Wheref(format string, args ...interface{}) *Model { var ( diff --git a/database/gdb/gdb_model_fields.go b/database/gdb/gdb_model_fields.go index a4115039e..0238e8d20 100644 --- a/database/gdb/gdb_model_fields.go +++ b/database/gdb/gdb_model_fields.go @@ -9,6 +9,8 @@ package gdb import ( "fmt" "github.com/gogf/gf/container/gset" + "github.com/gogf/gf/errors/gcode" + "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/text/gstr" "github.com/gogf/gf/util/gconv" "github.com/gogf/gf/util/gutil" @@ -247,7 +249,7 @@ func (m *Model) HasField(field string) (bool, error) { return false, err } if len(tableFields) == 0 { - return false, fmt.Errorf(`empty table fields for table "%s"`, m.tables) + return false, gerror.NewCodef(gcode.CodeNotFound, `empty table fields for table "%s"`, m.tables) } fieldsArray := make([]string, len(tableFields)) for k, v := range tableFields { diff --git a/database/gdb/gdb_type_record.go b/database/gdb/gdb_type_record.go index eff35a1f4..14c26b9e6 100644 --- a/database/gdb/gdb_type_record.go +++ b/database/gdb/gdb_type_record.go @@ -22,13 +22,13 @@ func (r Record) Interface() interface{} { // Json converts `r` to JSON format content. func (r Record) Json() string { content, _ := gparser.VarToJson(r.Map()) - return gconv.UnsafeBytesToStr(content) + return string(content) } // Xml converts `r` to XML format content. func (r Record) Xml(rootTag ...string) string { content, _ := gparser.VarToXml(r.Map(), rootTag...) - return gconv.UnsafeBytesToStr(content) + return string(content) } // Map converts `r` to map[string]interface{}. diff --git a/database/gredis/gredis_conn.go b/database/gredis/gredis_conn.go index a56e9ddd7..347fe79be 100644 --- a/database/gredis/gredis_conn.go +++ b/database/gredis/gredis_conn.go @@ -117,7 +117,7 @@ func (c *Conn) ReceiveVarWithTimeout(timeout time.Duration) (*gvar.Var, error) { func resultToVar(result interface{}, err error) (*gvar.Var, error) { if err == nil { if result, ok := result.([]byte); ok { - return gvar.New(gconv.UnsafeBytesToStr(result)), err + return gvar.New(string(result)), err } // It treats all returned slice as string slice. if result, ok := result.([]interface{}); ok { diff --git a/encoding/gbase64/gbase64.go b/encoding/gbase64/gbase64.go index b88373677..30e104aec 100644 --- a/encoding/gbase64/gbase64.go +++ b/encoding/gbase64/gbase64.go @@ -9,7 +9,6 @@ package gbase64 import ( "encoding/base64" - "github.com/gogf/gf/util/gconv" "io/ioutil" ) @@ -27,7 +26,7 @@ func EncodeString(src string) string { // EncodeToString encodes bytes to string with BASE64 algorithm. func EncodeToString(src []byte) string { - return gconv.UnsafeBytesToStr(Encode(src)) + return string(Encode(src)) } // EncryptFile encodes file content of using BASE64 algorithms. @@ -55,7 +54,7 @@ func EncodeFileToString(path string) (string, error) { if err != nil { return "", err } - return gconv.UnsafeBytesToStr(content), nil + return string(content), nil } // MustEncodeFileToString encodes file content of to string using BASE64 algorithms. @@ -103,7 +102,7 @@ func MustDecodeString(data string) []byte { // DecodeString decodes string with BASE64 algorithm. func DecodeToString(data string) (string, error) { b, err := DecodeString(data) - return gconv.UnsafeBytesToStr(b), err + return string(b), err } // MustDecodeToString decodes string with BASE64 algorithm. diff --git a/encoding/gini/gini.go b/encoding/gini/gini.go index 0ff476b46..a0b31f37f 100644 --- a/encoding/gini/gini.go +++ b/encoding/gini/gini.go @@ -79,24 +79,23 @@ func Decode(data []byte) (res map[string]interface{}, err error) { // Encode converts map to INI format. func Encode(data map[string]interface{}) (res []byte, err error) { w := new(bytes.Buffer) - w.WriteString("; this ini file is produced by package gini\n") for k, v := range data { n, err := w.WriteString(fmt.Sprintf("[%s]\n", k)) if err != nil || n == 0 { - return nil, fmt.Errorf("write data failed. %v", err) + return nil, gerror.WrapCodef(gcode.CodeInternalError, err, "write data failed") } for kk, vv := range v.(map[string]interface{}) { n, err := w.WriteString(fmt.Sprintf("%s=%s\n", kk, vv.(string))) if err != nil || n == 0 { - return nil, fmt.Errorf("write data failed. %v", err) + return nil, gerror.WrapCodef(gcode.CodeInternalError, err, "write data failed") } } } res = make([]byte, w.Len()) n, err := w.Read(res) if err != nil || n == 0 { - return nil, fmt.Errorf("write data failed. %v", err) + return nil, gerror.WrapCodef(gcode.CodeInternalError, err, "write data failed") } return res, nil diff --git a/encoding/gjson/gjson.go b/encoding/gjson/gjson.go index 887b0f232..5efe927c6 100644 --- a/encoding/gjson/gjson.go +++ b/encoding/gjson/gjson.go @@ -322,17 +322,28 @@ func (j *Json) getPointerByPatternWithViolenceCheck(pattern string) *interface{} if !j.vc { return j.getPointerByPatternWithoutViolenceCheck(pattern) } - index := len(pattern) - start := 0 - length := 0 - pointer := j.p + + // It returns nil if pattern is empty. + if pattern == "" { + return nil + } + // It returns all if pattern is ".". + if pattern == "." { + return j.p + } + + var ( + index = len(pattern) + start = 0 + length = 0 + pointer = j.p + ) if index == 0 { return pointer } for { if r := j.checkPatternByPointer(pattern[start:index], pointer); r != nil { - length += index - start - if start > 0 { + if length += index - start; start > 0 { length += 1 } start = index + 1 @@ -361,6 +372,16 @@ func (j *Json) getPointerByPatternWithoutViolenceCheck(pattern string) *interfac if j.vc { return j.getPointerByPatternWithViolenceCheck(pattern) } + + // It returns nil if pattern is empty. + if pattern == "" { + return nil + } + // It returns all if pattern is ".". + if pattern == "." { + return j.p + } + pointer := j.p if len(pattern) == 0 { return pointer diff --git a/encoding/gjson/gjson_api.go b/encoding/gjson/gjson_api.go index 642990201..672c322ac 100644 --- a/encoding/gjson/gjson_api.go +++ b/encoding/gjson/gjson_api.go @@ -8,6 +8,8 @@ package gjson import ( "fmt" + "github.com/gogf/gf/errors/gcode" + "github.com/gogf/gf/errors/gerror" "time" "github.com/gogf/gf/util/gutil" @@ -59,11 +61,6 @@ func (j *Json) Get(pattern string, def ...interface{}) interface{} { return nil } - // It returns all if pattern is ".". - if pattern == "." { - return *j.p - } - var result *interface{} if j.vc { result = j.getPointerByPattern(pattern) @@ -309,14 +306,20 @@ func (j *Json) Len(pattern string) int { // The target value by should be type of slice. func (j *Json) Append(pattern string, value interface{}) error { p := j.getPointerByPattern(pattern) - if p == nil { + if p == nil || *p == nil { + if pattern == "." { + return j.Set("0", value) + } return j.Set(fmt.Sprintf("%s.0", pattern), value) } switch (*p).(type) { case []interface{}: + if pattern == "." { + return j.Set(fmt.Sprintf("%d", len((*p).([]interface{}))), value) + } return j.Set(fmt.Sprintf("%s.%d", pattern, len((*p).([]interface{}))), value) } - return fmt.Errorf("invalid variable type of %s", pattern) + return gerror.NewCodef(gcode.CodeInvalidParameter, "invalid variable type of %s", pattern) } // GetStruct retrieves the value by specified and converts it to specified object diff --git a/encoding/gjson/gjson_api_encoding.go b/encoding/gjson/gjson_api_encoding.go index cea7a8a1b..559a20464 100644 --- a/encoding/gjson/gjson_api_encoding.go +++ b/encoding/gjson/gjson_api_encoding.go @@ -12,7 +12,6 @@ import ( "github.com/gogf/gf/encoding/gxml" "github.com/gogf/gf/encoding/gyaml" "github.com/gogf/gf/internal/json" - "github.com/gogf/gf/util/gconv" ) // ======================================================================== @@ -50,7 +49,7 @@ func (j *Json) MustToJson() []byte { } func (j *Json) MustToJsonString() string { - return gconv.UnsafeBytesToStr(j.MustToJson()) + return string(j.MustToJson()) } func (j *Json) MustToJsonIndent() []byte { @@ -62,7 +61,7 @@ func (j *Json) MustToJsonIndent() []byte { } func (j *Json) MustToJsonIndentString() string { - return gconv.UnsafeBytesToStr(j.MustToJsonIndent()) + return string(j.MustToJsonIndent()) } // ======================================================================== @@ -96,7 +95,7 @@ func (j *Json) MustToXml(rootTag ...string) []byte { } func (j *Json) MustToXmlString(rootTag ...string) string { - return gconv.UnsafeBytesToStr(j.MustToXml(rootTag...)) + return string(j.MustToXml(rootTag...)) } func (j *Json) MustToXmlIndent(rootTag ...string) []byte { @@ -108,7 +107,7 @@ func (j *Json) MustToXmlIndent(rootTag ...string) []byte { } func (j *Json) MustToXmlIndentString(rootTag ...string) string { - return gconv.UnsafeBytesToStr(j.MustToXmlIndent(rootTag...)) + return string(j.MustToXmlIndent(rootTag...)) } // ======================================================================== @@ -135,7 +134,7 @@ func (j *Json) MustToYaml() []byte { } func (j *Json) MustToYamlString() string { - return gconv.UnsafeBytesToStr(j.MustToYaml()) + return string(j.MustToYaml()) } // ======================================================================== @@ -162,7 +161,7 @@ func (j *Json) MustToToml() []byte { } func (j *Json) MustToTomlString() string { - return gconv.UnsafeBytesToStr(j.MustToToml()) + return string(j.MustToToml()) } // ======================================================================== @@ -192,5 +191,5 @@ func (j *Json) MustToIni() []byte { // MustToIniString . func (j *Json) MustToIniString() string { - return gconv.UnsafeBytesToStr(j.MustToIni()) + return string(j.MustToIni()) } diff --git a/encoding/gjson/gjson_api_new_load.go b/encoding/gjson/gjson_api_new_load.go index f9b5c673b..cc7fc10f3 100644 --- a/encoding/gjson/gjson_api_new_load.go +++ b/encoding/gjson/gjson_api_new_load.go @@ -8,7 +8,6 @@ package gjson import ( "bytes" - "fmt" "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "reflect" @@ -260,12 +259,14 @@ func doLoadContentWithOptions(dataType string, data []byte, options Options) (*J if data, err = gtoml.ToJson(data); err != nil { return nil, err } + case "ini", ".ini": if data, err = gini.ToJson(data); err != nil { return nil, err } + default: - err = gerror.NewCode(gcode.CodeInvalidParameter, "unsupported type for loading") + err = gerror.NewCodef(gcode.CodeInvalidParameter, `unsupported type "%s" for loading`, dataType) } if err != nil { return nil, err @@ -279,7 +280,7 @@ func doLoadContentWithOptions(dataType string, data []byte, options Options) (*J } switch result.(type) { case string, []byte: - return nil, fmt.Errorf(`json decoding failed for content: %s`, string(data)) + return nil, gerror.NewCodef(gcode.CodeInternalError, `json decoding failed for content: %s`, data) } return NewWithOptions(result, options), nil } diff --git a/encoding/gjson/gjson_stdlib_json_util.go b/encoding/gjson/gjson_stdlib_json_util.go index be1c57668..28cfccb37 100644 --- a/encoding/gjson/gjson_stdlib_json_util.go +++ b/encoding/gjson/gjson_stdlib_json_util.go @@ -35,7 +35,7 @@ func Decode(data interface{}) (interface{}, error) { } } -// Decode decodes json format to specified golang variable . +// DecodeTo decodes json format to specified golang variable . // The parameter can be either bytes or string type. // The parameter should be a pointer type. func DecodeTo(data interface{}, v interface{}) error { diff --git a/encoding/gjson/gjson_z_unit_basic_test.go b/encoding/gjson/gjson_z_unit_basic_test.go index 7013f2fbf..27b8bee65 100644 --- a/encoding/gjson/gjson_z_unit_basic_test.go +++ b/encoding/gjson/gjson_z_unit_basic_test.go @@ -244,6 +244,22 @@ func Test_Append(t *testing.T) { }) } +func Test_RawArray(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + j := gjson.New(nil) + t.AssertNil(j.Set("0", 1)) + t.AssertNil(j.Set("1", 2)) + t.Assert(j.MustToJsonString(), `[1,2]`) + }) + + gtest.C(t, func(t *gtest.T) { + j := gjson.New(nil) + t.AssertNil(j.Append(".", 1)) + t.AssertNil(j.Append(".", 2)) + t.Assert(j.MustToJsonString(), `[1,2]`) + }) +} + func TestJson_ToJson(t *testing.T) { gtest.C(t, func(t *gtest.T) { p := gjson.New(1) diff --git a/errors/gerror/gerror.go b/errors/gerror/gerror.go index 268af2fab..8249dddcd 100644 --- a/errors/gerror/gerror.go +++ b/errors/gerror/gerror.go @@ -6,8 +6,8 @@ // Package gerror provides simple functions to manipulate errors. // -// Very note that, this package is quite a base package, which should not import extra -// packages except standard packages, to avoid cycle imports. +// Very note that, this package is quite a basic package, which SHOULD NOT import extra +// packages except standard packages and internal packages, to avoid cycle imports. package gerror import ( diff --git a/frame/g/g_object.go b/frame/g/g_object.go index 571d47247..c75247b57 100644 --- a/frame/g/g_object.go +++ b/frame/g/g_object.go @@ -89,7 +89,7 @@ func DB(name ...string) gdb.DB { // Table is alias of Model. // The database component is designed not only for // relational databases but also for NoSQL databases in the future. The name -// "Table" is not proper for that purpose any more. +// "Table" is not proper for that purpose anymore. // Deprecated, use Model instead. func Table(tableNameOrStruct ...interface{}) *gdb.Model { return DB().Model(tableNameOrStruct...) @@ -100,6 +100,11 @@ func Model(tableNameOrStruct ...interface{}) *gdb.Model { return DB().Model(tableNameOrStruct...) } +// ModelRaw creates and returns a model based on a raw sql not a table. +func ModelRaw(rawSql string, args ...interface{}) *gdb.Model { + return DB().Raw(rawSql, args...) +} + // Redis returns an instance of redis client with specified configuration group name. func Redis(name ...string) *gredis.Redis { return gins.Redis(name...) diff --git a/go.mod b/go.mod index bbdb48b3a..fc660eac6 100644 --- a/go.mod +++ b/go.mod @@ -3,18 +3,18 @@ module github.com/gogf/gf go 1.14 require ( - github.com/BurntSushi/toml v0.3.1 + github.com/BurntSushi/toml v0.4.1 github.com/clbanning/mxj v1.8.5-0.20200714211355-ff02cfb8ea28 github.com/fatih/color v1.12.0 - github.com/fsnotify/fsnotify v1.4.9 + github.com/fsnotify/fsnotify v1.5.1 github.com/go-sql-driver/mysql v1.6.0 github.com/gomodule/redigo v1.8.5 github.com/gorilla/websocket v1.4.2 github.com/grokify/html-strip-tags-go v0.0.0-20190921062105-daaa06bf1aaf github.com/olekukonko/tablewriter v0.0.5 - go.opentelemetry.io/otel v1.0.0-RC2 - go.opentelemetry.io/otel/oteltest v1.0.0-RC2 - go.opentelemetry.io/otel/trace v1.0.0-RC2 + go.opentelemetry.io/otel v1.0.0-RC3 + go.opentelemetry.io/otel/oteltest v1.0.0-RC3 + go.opentelemetry.io/otel/trace v1.0.0-RC3 golang.org/x/net v0.0.0-20210520170846-37e1c6afe023 golang.org/x/text v0.3.6 gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b diff --git a/go.sum b/go.sum index 72133957f..269310b56 100644 --- a/go.sum +++ b/go.sum @@ -1,13 +1,13 @@ -github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= -github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/toml v0.4.1 h1:GaI7EiDXDRfa8VshkTj7Fym7ha+y8/XxIgD2okUIjLw= +github.com/BurntSushi/toml v0.4.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/clbanning/mxj v1.8.5-0.20200714211355-ff02cfb8ea28 h1:LdXxtjzvZYhhUaonAaAKArG3pyC67kGL3YY+6hGG8G4= github.com/clbanning/mxj v1.8.5-0.20200714211355-ff02cfb8ea28/go.mod h1:BVjHeAH+rl9rs6f+QIpeRl0tfu10SXn1pUSa5PVGJng= github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/fatih/color v1.12.0 h1:mRhaKNwANqRgUBGKmnI5ZxEk7QXmjQeCcuYFMX2bfcc= github.com/fatih/color v1.12.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM= -github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= -github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/fsnotify/fsnotify v1.5.1 h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI= +github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU= github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE= github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/gomodule/redigo v1.8.5 h1:nRAxCa+SVsyjSBrtZmG/cqb6VbTmuRzpg/PoTFlpumc= @@ -32,20 +32,20 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -go.opentelemetry.io/otel v1.0.0-RC2 h1:SHhxSjB+omnGZPgGlKe+QMp3MyazcOHdQ8qwo89oKbg= -go.opentelemetry.io/otel v1.0.0-RC2/go.mod h1:w1thVQ7qbAy8MHb0IFj8a5Q2QU0l2ksf8u/CN8m3NOM= -go.opentelemetry.io/otel/oteltest v1.0.0-RC2 h1:xNKqMhlZYkASSyvF4JwObZFMq0jhFN3c3SP+2rCzVPk= -go.opentelemetry.io/otel/oteltest v1.0.0-RC2/go.mod h1:kiQ4tw5tAL4JLTbcOYwK1CWI1HkT5aiLzHovgOVnz/A= -go.opentelemetry.io/otel/trace v1.0.0-RC2 h1:dunAP0qDULMIT82atj34m5RgvsIK6LcsXf1c/MsYg1w= -go.opentelemetry.io/otel/trace v1.0.0-RC2/go.mod h1:JPQ+z6nNw9mqEGT8o3eoPTdnNI+Aj5JcxEsVGREIAy4= +go.opentelemetry.io/otel v1.0.0-RC3 h1:kvwiyEkiUT/JaadXzVLI/R1wDO934A7r3Bs2wEe6wqA= +go.opentelemetry.io/otel v1.0.0-RC3/go.mod h1:Ka5j3ua8tZs4Rkq4Ex3hwgBgOchyPVq5S6P2lz//nKQ= +go.opentelemetry.io/otel/oteltest v1.0.0-RC3 h1:MjaeegZTaX0Bv9uB9CrdVjOFM/8slRjReoWoV9xDCpY= +go.opentelemetry.io/otel/oteltest v1.0.0-RC3/go.mod h1:xpzajI9JBRr7gX63nO6kAmImmYIAtuQblZ36Z+LfCjE= +go.opentelemetry.io/otel/trace v1.0.0-RC3 h1:9F0ayEvlxv8BmNmPbU005WK7hC+7KbOazCPZjNa1yME= +go.opentelemetry.io/otel/trace v1.0.0-RC3/go.mod h1:VUt2TUYd8S2/ZRX09ZDFZQwn2RqfMB5MzO17jBojGxo= golang.org/x/net v0.0.0-20210520170846-37e1c6afe023 h1:ADo5wSpq2gqaCGQWzk7S5vd//0iyyLeAratkEoG5dLE= golang.org/x/net v0.0.0-20210520170846-37e1c6afe023/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210423082822-04245dca01da h1:b3NXsE2LusjYGGjL5bxEVZZORm/YEFFrWFjR8eFrw/c= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c h1:F1jZWGFhYfh0Ci55sIpILtKKK8p3i2/krTr0H1rg74I= +golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= diff --git a/net/ghttp/ghttp_func.go b/net/ghttp/ghttp_func.go index a4d96037e..0ecee6687 100644 --- a/net/ghttp/ghttp_func.go +++ b/net/ghttp/ghttp_func.go @@ -36,11 +36,11 @@ func niceCallFunc(f func()) { // Create a new error with stack info. // Note that there's a skip pointing the start stacktrace // of the real error point. - if err, ok := exception.(error); ok { - if gerror.Code(err) != gcode.CodeNil { - panic(err) + if v, ok := exception.(error); ok { + if gerror.Code(v) != gcode.CodeNil { + panic(v) } else { - panic(gerror.WrapCodeSkip(gcode.CodeInternalError, 1, err, "")) + panic(gerror.WrapCodeSkip(gcode.CodeInternalError, 1, v, "")) } } else { panic(gerror.NewCodeSkipf(gcode.CodeInternalError, 1, "%+v", exception)) diff --git a/net/ghttp/ghttp_request_param.go b/net/ghttp/ghttp_request_param.go index 8c9689b2e..c6a044d97 100644 --- a/net/ghttp/ghttp_request_param.go +++ b/net/ghttp/ghttp_request_param.go @@ -70,7 +70,8 @@ func (r *Request) doParse(pointer interface{}, requestType int) error { reflectKind1 = reflectVal1.Kind() ) if reflectKind1 != reflect.Ptr { - return fmt.Errorf( + return gerror.NewCodef( + gcode.CodeInvalidParameter, "parameter should be type of *struct/**struct/*[]struct/*[]*struct, but got: %v", reflectKind1, ) @@ -174,7 +175,7 @@ func (r *Request) GetBody() []byte { // GetBodyString retrieves and returns request body content as string. // It can be called multiple times retrieving the same body content. func (r *Request) GetBodyString() string { - return gconv.UnsafeBytesToStr(r.GetBody()) + return string(r.GetBody()) } // GetJson parses current request content as JSON format, and returns the JSON object. @@ -374,7 +375,7 @@ func (r *Request) parseForm() { // It might be JSON/XML content. if s := gstr.Trim(name + strings.Join(values, " ")); len(s) > 0 { if s[0] == '{' && s[len(s)-1] == '}' || s[0] == '<' && s[len(s)-1] == '>' { - r.bodyContent = gconv.UnsafeStrToBytes(s) + r.bodyContent = []byte(s) params = "" break } diff --git a/net/ghttp/ghttp_server_graceful.go b/net/ghttp/ghttp_server_graceful.go index 8f6d60b53..2641d1424 100644 --- a/net/ghttp/ghttp_server_graceful.go +++ b/net/ghttp/ghttp_server_graceful.go @@ -9,7 +9,6 @@ package ghttp import ( "context" "crypto/tls" - "fmt" "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/os/gproc" @@ -162,19 +161,21 @@ func (s *gracefulServer) doServe() error { // getNetListener retrieves and returns the wrapped net.Listener. func (s *gracefulServer) getNetListener() (net.Listener, error) { - var ln net.Listener - var err error + var ( + ln net.Listener + err error + ) if s.fd > 0 { f := os.NewFile(s.fd, "") ln, err = net.FileListener(f) if err != nil { - err = fmt.Errorf("%d: net.FileListener error: %v", gproc.Pid(), err) + err = gerror.WrapCodef(gcode.CodeInternalError, err, "%d: net.FileListener failed", gproc.Pid()) return nil, err } } else { ln, err = net.Listen("tcp", s.httpServer.Addr) if err != nil { - err = fmt.Errorf("%d: net.Listen error: %v", gproc.Pid(), err) + err = gerror.WrapCodef(gcode.CodeInternalError, err, "%d: net.Listen failed", gproc.Pid()) } } return ln, err diff --git a/net/ghttp/ghttp_server_handler.go b/net/ghttp/ghttp_server_handler.go index 30d747c80..d6d46bf04 100644 --- a/net/ghttp/ghttp_server_handler.go +++ b/net/ghttp/ghttp_server_handler.go @@ -67,11 +67,11 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { } else { if exception := recover(); exception != nil { request.Response.WriteStatus(http.StatusInternalServerError) - if err, ok := exception.(error); ok { - if code := gerror.Code(err); code != gcode.CodeNil { - s.handleErrorLog(err, request) + if v, ok := exception.(error); ok { + if code := gerror.Code(v); code != gcode.CodeNil { + s.handleErrorLog(v, request) } else { - s.handleErrorLog(gerror.WrapCodeSkip(gcode.CodeInternalError, 1, err, ""), request) + s.handleErrorLog(gerror.WrapCodeSkip(gcode.CodeInternalError, 1, v, ""), request) } } else { s.handleErrorLog(gerror.NewCodeSkipf(gcode.CodeInternalError, 1, "%+v", exception), request) diff --git a/net/ghttp/internal/client/client_dump.go b/net/ghttp/internal/client/client_dump.go index 9ac718a65..38774ab36 100644 --- a/net/ghttp/internal/client/client_dump.go +++ b/net/ghttp/internal/client/client_dump.go @@ -12,8 +12,6 @@ import ( "io/ioutil" "net/http" "net/http/httputil" - - "github.com/gogf/gf/util/gconv" ) // dumpTextFormat is the format of the dumped raw string @@ -31,7 +29,7 @@ func getResponseBody(res *http.Response) string { } bodyContent, _ := ioutil.ReadAll(res.Body) res.Body = utils.NewReadCloser(bodyContent, true) - return gconv.UnsafeBytesToStr(bodyContent) + return string(bodyContent) } // RawRequest returns the raw content of the request. @@ -51,7 +49,7 @@ func (r *Response) RawRequest() string { return fmt.Sprintf( dumpTextFormat, "REQUEST ", - gconv.UnsafeBytesToStr(bs), + string(bs), r.requestBody, ) } @@ -70,7 +68,7 @@ func (r *Response) RawResponse() string { return fmt.Sprintf( dumpTextFormat, "RESPONSE", - gconv.UnsafeBytesToStr(bs), + string(bs), getResponseBody(r.Response), ) } diff --git a/net/ghttp/internal/client/client_response.go b/net/ghttp/internal/client/client_response.go index 324115ebf..54699562c 100644 --- a/net/ghttp/internal/client/client_response.go +++ b/net/ghttp/internal/client/client_response.go @@ -9,8 +9,6 @@ package client import ( "io/ioutil" "net/http" - - "github.com/gogf/gf/util/gconv" ) // Response is the struct for client request response. @@ -65,7 +63,7 @@ func (r *Response) ReadAll() []byte { // ReadAllString retrieves and returns the response content as string. func (r *Response) ReadAllString() string { - return gconv.UnsafeBytesToStr(r.ReadAll()) + return string(r.ReadAll()) } // Close closes the response when it will never be used. diff --git a/net/gsmtp/gsmtp.go b/net/gsmtp/gsmtp.go index 37c8dfd5d..f52d1b5c8 100644 --- a/net/gsmtp/gsmtp.go +++ b/net/gsmtp/gsmtp.go @@ -14,7 +14,8 @@ package gsmtp import ( "encoding/base64" "fmt" - "github.com/gogf/gf/util/gconv" + "github.com/gogf/gf/errors/gcode" + "github.com/gogf/gf/errors/gerror" "net/smtp" "strings" ) @@ -53,13 +54,21 @@ func (s *SMTP) SendMail(from, tos, subject, body string, contentType ...string) hp = strings.Split(s.Address, ":") ) if s.Address == "" || len(hp) > 2 { - return fmt.Errorf("server address is either empty or incorrect: %s", s.Address) + return gerror.NewCodef( + gcode.CodeInvalidParameter, + "server address is either empty or incorrect: %s", + s.Address, + ) } else if len(hp) == 1 { server = s.Address address = server + ":25" } else if len(hp) == 2 { if (hp[0] == "") || (hp[1] == "") { - return fmt.Errorf("server address is either empty or incorrect: %s", s.Address) + return gerror.NewCodef( + gcode.CodeInvalidParameter, + "server address is either empty or incorrect: %s", + s.Address, + ) } server = hp[0] address = s.Address @@ -75,17 +84,17 @@ func (s *SMTP) SendMail(from, tos, subject, body string, contentType ...string) } } if len(tosArr) == 0 { - return fmt.Errorf("tos if invalid: %s", tos) + return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid parameter "tos": %s`, tos) } if !strings.Contains(from, "@") { - return fmt.Errorf("from is invalid: %s", from) + return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid parameter "from": %s`, from) } header := map[string]string{ "From": from, "To": strings.Join(tosArr, ";"), - "Subject": fmt.Sprintf("=?UTF-8?B?%s?=", contentEncoding.EncodeToString(gconv.UnsafeStrToBytes(subject))), + "Subject": fmt.Sprintf("=?UTF-8?B?%s?=", contentEncoding.EncodeToString([]byte(subject))), "MIME-Version": "1.0", "Content-Type": "text/plain; charset=UTF-8", "Content-Transfer-Encoding": "base64", @@ -97,12 +106,12 @@ func (s *SMTP) SendMail(from, tos, subject, body string, contentType ...string) for k, v := range header { message += fmt.Sprintf("%s: %s\r\n", k, v) } - message += "\r\n" + contentEncoding.EncodeToString(gconv.UnsafeStrToBytes(body)) + message += "\r\n" + contentEncoding.EncodeToString([]byte(body)) return smtp.SendMail( address, smtp.PlainAuth("", s.Username, s.Password, server), from, tosArr, - gconv.UnsafeStrToBytes(message), + []byte(message), ) } diff --git a/net/gtcp/gtcp_conn_pkg.go b/net/gtcp/gtcp_conn_pkg.go index ef090adcf..923217437 100644 --- a/net/gtcp/gtcp_conn_pkg.go +++ b/net/gtcp/gtcp_conn_pkg.go @@ -8,7 +8,8 @@ package gtcp import ( "encoding/binary" - "fmt" + "github.com/gogf/gf/errors/gcode" + "github.com/gogf/gf/errors/gerror" "time" ) @@ -46,7 +47,8 @@ func (c *Conn) SendPkg(data []byte, option ...PkgOption) error { } length := len(data) if length > pkgOption.MaxDataSize { - return fmt.Errorf( + return gerror.NewCodef( + gcode.CodeInvalidParameter, `data too long, data size %d exceeds allowed max data size %d`, length, pkgOption.MaxDataSize, ) @@ -116,7 +118,7 @@ func (c *Conn) RecvPkg(option ...PkgOption) (result []byte, err error) { // It here validates the size of the package. // It clears the buffer and returns error immediately if it validates failed. if length < 0 || length > pkgOption.MaxDataSize { - return nil, fmt.Errorf(`invalid package size %d`, length) + return nil, gerror.NewCodef(gcode.CodeInvalidParameter, `invalid package size %d`, length) } // Empty package. if length == 0 { @@ -147,7 +149,8 @@ func getPkgOption(option ...PkgOption) (*PkgOption, error) { pkgOption.HeaderSize = pkgHeaderSizeDefault } if pkgOption.HeaderSize > pkgHeaderSizeMax { - return nil, fmt.Errorf( + return nil, gerror.NewCodef( + gcode.CodeInvalidParameter, `package header size %d definition exceeds max header size %d`, pkgOption.HeaderSize, pkgHeaderSizeMax, ) @@ -166,7 +169,8 @@ func getPkgOption(option ...PkgOption) (*PkgOption, error) { } } if pkgOption.MaxDataSize > 0x7FFFFFFF { - return nil, fmt.Errorf( + return nil, gerror.NewCodef( + gcode.CodeInvalidParameter, `package data size %d definition exceeds allowed max data size %d`, pkgOption.MaxDataSize, 0x7FFFFFFF, ) diff --git a/os/gcfg/gcfg_config.go b/os/gcfg/gcfg_config.go index f7db8f603..3d9770abb 100644 --- a/os/gcfg/gcfg_config.go +++ b/os/gcfg/gcfg_config.go @@ -151,7 +151,11 @@ func (c *Config) SetPath(path string) error { } // Should be a directory. if !isDir { - err := fmt.Errorf(`[gcfg] SetPath failed: path "%s" should be directory type`, path) + err := gerror.NewCodef( + gcode.CodeInvalidParameter, + `[gcfg] SetPath failed: path "%s" should be directory type`, + path, + ) if errorPrint() { glog.Error(err) } diff --git a/os/gfile/gfile_contents.go b/os/gfile/gfile_contents.go index 048e15d76..29057ddaa 100644 --- a/os/gfile/gfile_contents.go +++ b/os/gfile/gfile_contents.go @@ -11,8 +11,6 @@ import ( "io" "io/ioutil" "os" - - "github.com/gogf/gf/util/gconv" ) var ( @@ -23,7 +21,7 @@ var ( // GetContents returns the file content of as string. // It returns en empty string if it fails reading. func GetContents(path string) string { - return gconv.UnsafeBytesToStr(GetBytes(path)) + return string(GetBytes(path)) } // GetBytes returns the file content of as []byte. diff --git a/os/gfile/gfile_copy.go b/os/gfile/gfile_copy.go index 26ace7bcf..554c6cd9f 100644 --- a/os/gfile/gfile_copy.go +++ b/os/gfile/gfile_copy.go @@ -7,7 +7,6 @@ package gfile import ( - "fmt" "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "io" @@ -104,7 +103,7 @@ func CopyDir(src string, dst string) (err error) { return err } if !si.IsDir() { - return fmt.Errorf("source is not a directory") + return gerror.NewCode(gcode.CodeInvalidParameter, "source is not a directory") } if !Exists(dst) { err = os.MkdirAll(dst, DefaultPermCopy) diff --git a/os/gproc/gproc.go b/os/gproc/gproc.go index 33fe32f00..4fc36b25f 100644 --- a/os/gproc/gproc.go +++ b/os/gproc/gproc.go @@ -80,9 +80,9 @@ func Uptime() time.Duration { return time.Now().Sub(processStartTime) } -// Shell executes command synchronizingly with given input pipe and output pipe . -// The command reads the input parameters from input pipe , and writes its output automatically -// to output pipe . +// Shell executes command synchronously with given input pipe and output pipe `out`. +// The command reads the input parameters from input pipe `in`, and writes its output automatically +// to output pipe `out`. func Shell(cmd string, out io.Writer, in io.Reader) error { p := NewProcess(getShell(), append([]string{getShellOption()}, parseCommand(cmd)...)) p.Stdin = in @@ -90,13 +90,13 @@ func Shell(cmd string, out io.Writer, in io.Reader) error { return p.Run() } -// ShellRun executes given command synchronizingly and outputs the command result to the stdout. +// ShellRun executes given command `cmd` synchronously and outputs the command result to the stdout. func ShellRun(cmd string) error { p := NewProcess(getShell(), append([]string{getShellOption()}, parseCommand(cmd)...)) return p.Run() } -// ShellExec executes given command synchronizingly and returns the command result. +// ShellExec executes given command `cmd` synchronously and returns the command result. func ShellExec(cmd string, environment ...[]string) (string, error) { buf := bytes.NewBuffer(nil) p := NewProcess(getShell(), append([]string{getShellOption()}, parseCommand(cmd)...), environment...) @@ -106,10 +106,10 @@ func ShellExec(cmd string, environment ...[]string) (string, error) { return buf.String(), err } -// parseCommand parses command into slice arguments. +// parseCommand parses command `cmd` into slice arguments. // -// Note that it just parses the for "cmd.exe" binary in windows, but it is not necessary -// parsing the for other systems using "bash"/"sh" binary. +// Note that it just parses the `cmd` for "cmd.exe" binary in windows, but it is not necessary +// parsing the `cmd` for other systems using "bash"/"sh" binary. func parseCommand(cmd string) (args []string) { if runtime.GOOS != "windows" { return []string{cmd} @@ -170,7 +170,7 @@ func getShell() string { } } -// getShellOption returns the shell option depending on current working operation system. +// getShellOption returns the shell option depending on current working operating system. // It returns "/c" for windows, and "-c" for others. func getShellOption() string { switch runtime.GOOS { @@ -181,7 +181,7 @@ func getShellOption() string { } } -// SearchBinary searches the binary in current working folder and PATH environment. +// SearchBinary searches the binary `file` in current working folder and PATH environment. func SearchBinary(file string) string { // Check if it's absolute path of exists at current working directory. if gfile.Exists(file) { @@ -190,7 +190,7 @@ func SearchBinary(file string) string { return SearchBinaryPath(file) } -// SearchBinaryPath searches the binary in PATH environment. +// SearchBinaryPath searches the binary `file` in PATH environment. func SearchBinaryPath(file string) string { array := ([]string)(nil) switch runtime.GOOS { diff --git a/os/gproc/gproc_process.go b/os/gproc/gproc_process.go index a560c0eb8..51249e5d6 100644 --- a/os/gproc/gproc_process.go +++ b/os/gproc/gproc_process.go @@ -29,9 +29,7 @@ type Process struct { func NewProcess(path string, args []string, environment ...[]string) *Process { env := os.Environ() if len(environment) > 0 { - for k, v := range environment[0] { - env[k] = v - } + env = append(env, environment[0]...) } process := &Process{ Manager: nil, diff --git a/os/gres/gres_func.go b/os/gres/gres_func.go index 4995fbc29..cf45d7a8c 100644 --- a/os/gres/gres_func.go +++ b/os/gres/gres_func.go @@ -13,10 +13,8 @@ import ( "fmt" "github.com/gogf/gf/encoding/gbase64" "github.com/gogf/gf/encoding/gcompress" - "github.com/gogf/gf/text/gstr" - "github.com/gogf/gf/util/gconv" - "github.com/gogf/gf/os/gfile" + "github.com/gogf/gf/text/gstr" ) const ( @@ -116,7 +114,7 @@ func UnpackContent(content string) ([]*File, error) { return nil, err } } else { - data, err = gcompress.UnGzip(gconv.UnsafeStrToBytes(content)) + data, err = gcompress.UnGzip([]byte(content)) if err != nil { return nil, err } @@ -166,7 +164,7 @@ func isHexStr(s string) bool { // hexStrToBytes converts hex string content to []byte. func hexStrToBytes(s string) []byte { - src := gconv.UnsafeStrToBytes(s) + src := []byte(s) dst := make([]byte, hex.DecodedLen(len(src))) hex.Decode(dst, src) return dst diff --git a/os/grpool/grpool.go b/os/grpool/grpool.go index f9c19c356..672aacd48 100644 --- a/os/grpool/grpool.go +++ b/os/grpool/grpool.go @@ -99,10 +99,10 @@ func (p *Pool) AddWithRecover(userFunc func(), recoverFunc ...func(err error)) e defer func() { if exception := recover(); exception != nil { if len(recoverFunc) > 0 && recoverFunc[0] != nil { - if err, ok := exception.(error); ok { - recoverFunc[0](err) + if v, ok := exception.(error); ok { + recoverFunc[0](v) } else { - recoverFunc[0](gerror.NewCodef(gcode.CodeInternalError, `%v`, exception)) + recoverFunc[0](gerror.NewCodef(gcode.CodeInternalError, `%+v`, exception)) } } } diff --git a/os/gspath/gspath_cache.go b/os/gspath/gspath_cache.go index 324be56c1..3e0f47b8b 100644 --- a/os/gspath/gspath_cache.go +++ b/os/gspath/gspath_cache.go @@ -75,8 +75,6 @@ func (sp *SPath) addToCache(filePath, rootPath string) { for _, path := range files { sp.cache.SetIfNotExist(sp.nameFromPath(path, rootPath), sp.makeCacheValue(path, gfile.IsDir(path))) } - } else { - //fmt.Errorf(err.Error()) } } } diff --git a/os/gview/gview_buildin.go b/os/gview/gview_buildin.go index da22f78fa..281e15515 100644 --- a/os/gview/gview_buildin.go +++ b/os/gview/gview_buildin.go @@ -222,7 +222,7 @@ func (view *View) buildInFuncNl2Br(str interface{}) string { // which encodes and returns `value` as JSON string. func (view *View) buildInFuncJson(value interface{}) (string, error) { b, err := json.Marshal(value) - return gconv.UnsafeBytesToStr(b), err + return string(b), err } // buildInFuncPlus implements build-in template function: plus , diff --git a/os/gview/gview_parse.go b/os/gview/gview_parse.go index c8a4811ee..0fd3a095a 100644 --- a/os/gview/gview_parse.go +++ b/os/gview/gview_parse.go @@ -10,26 +10,23 @@ import ( "bytes" "context" "fmt" + "github.com/gogf/gf/container/gmap" "github.com/gogf/gf/encoding/ghash" "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/intlog" + "github.com/gogf/gf/os/gfile" "github.com/gogf/gf/os/gfsnotify" + "github.com/gogf/gf/os/glog" "github.com/gogf/gf/os/gmlock" + "github.com/gogf/gf/os/gres" + "github.com/gogf/gf/os/gspath" "github.com/gogf/gf/text/gstr" - "github.com/gogf/gf/util/gconv" "github.com/gogf/gf/util/gutil" htmltpl "html/template" "strconv" "strings" texttpl "text/template" - - "github.com/gogf/gf/os/gres" - - "github.com/gogf/gf/container/gmap" - "github.com/gogf/gf/os/gfile" - "github.com/gogf/gf/os/glog" - "github.com/gogf/gf/os/gspath" ) const ( @@ -71,7 +68,7 @@ func (view *View) Parse(ctx context.Context, file string, params ...Params) (res return nil } if resource != nil { - content = gconv.UnsafeBytesToStr(resource.Content()) + content = string(resource.Content()) } else { content = gfile.GetContentsWithCache(path) } diff --git a/text/gstr/gstr_parse.go b/text/gstr/gstr_parse.go index a41267403..84f36177d 100644 --- a/text/gstr/gstr_parse.go +++ b/text/gstr/gstr_parse.go @@ -7,7 +7,8 @@ package gstr import ( - "fmt" + "github.com/gogf/gf/errors/gcode" + "github.com/gogf/gf/errors/gerror" "net/url" "strings" ) @@ -116,7 +117,11 @@ func build(result map[string]interface{}, keys []string, value interface{}) erro } children, ok := val.([]interface{}) if !ok { - return fmt.Errorf("expected type '[]interface{}' for key '%s', but got '%T'", key, val) + return gerror.NewCodef( + gcode.CodeInvalidParameter, + "expected type '[]interface{}' for key '%s', but got '%T'", + key, val, + ) } result[key] = append(children, value) return nil @@ -131,7 +136,11 @@ func build(result map[string]interface{}, keys []string, value interface{}) erro } children, ok := val.([]interface{}) if !ok { - return fmt.Errorf("expected type '[]interface{}' for key '%s', but got '%T'", key, val) + return gerror.NewCodef( + gcode.CodeInvalidParameter, + "expected type '[]interface{}' for key '%s', but got '%T'", + key, val, + ) } if l := len(children); l > 0 { if child, ok := children[l-1].(map[string]interface{}); ok { @@ -155,7 +164,11 @@ func build(result map[string]interface{}, keys []string, value interface{}) erro } children, ok := val.(map[string]interface{}) if !ok { - return fmt.Errorf("expected type 'map[string]interface{}' for key '%s', but got '%T'", key, val) + return gerror.NewCodef( + gcode.CodeInvalidParameter, + "expected type 'map[string]interface{}' for key '%s', but got '%T'", + key, val, + ) } if err := build(children, keys[1:], value); err != nil { return err diff --git a/util/guid/guid_string.go b/util/guid/guid_string.go index 666d0ec8d..e8386aeb8 100644 --- a/util/guid/guid_string.go +++ b/util/guid/guid_string.go @@ -10,7 +10,6 @@ import ( "github.com/gogf/gf/container/gtype" "github.com/gogf/gf/encoding/ghash" "github.com/gogf/gf/net/gipv4" - "github.com/gogf/gf/util/gconv" "github.com/gogf/gf/util/grand" "os" "strconv" @@ -94,7 +93,7 @@ func S(data ...[]byte) string { } else { panic("too many data parts, it should be no more than 2 parts") } - return gconv.UnsafeBytesToStr(b) + return string(b) } // getSequence increases and returns the sequence string in 3 bytes. diff --git a/util/gutil/gutil.go b/util/gutil/gutil.go index 38716cdf9..e82c84de8 100644 --- a/util/gutil/gutil.go +++ b/util/gutil/gutil.go @@ -9,6 +9,8 @@ package gutil import ( "fmt" + "github.com/gogf/gf/errors/gcode" + "github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/internal/empty" "github.com/gogf/gf/util/gconv" "reflect" @@ -23,8 +25,12 @@ func Throw(exception interface{}) { // It returns error if any exception occurs, or else it returns nil. func Try(try func()) (err error) { defer func() { - if e := recover(); e != nil { - err = fmt.Errorf(`%v`, e) + if exception := recover(); exception != nil { + if v, ok := exception.(error); ok { + err = v + } else { + err = gerror.NewCodef(gcode.CodeInternalError, `%+v`, exception) + } } }() try() @@ -36,10 +42,10 @@ func Try(try func()) (err error) { func TryCatch(try func(), catch ...func(exception error)) { defer func() { if exception := recover(); exception != nil && len(catch) > 0 { - if err, ok := exception.(error); ok { - catch[0](err) + if v, ok := exception.(error); ok { + catch[0](v) } else { - catch[0](fmt.Errorf(`%v`, exception)) + catch[0](fmt.Errorf(`%+v`, exception)) } } }()