mirror of
https://gitee.com/johng/gf.git
synced 2024-11-30 11:18:02 +08:00
Merge branch 'gogf:master' into master
This commit is contained in:
commit
26584cdbb4
@ -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
|
||||
|
@ -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()
|
||||
|
@ -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())
|
||||
//}
|
||||
}
|
||||
|
@ -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()
|
||||
}
|
||||
|
@ -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)
|
||||
}
|
||||
|
@ -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())
|
||||
}
|
||||
|
@ -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())
|
||||
}
|
||||
}
|
||||
|
@ -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())
|
||||
}
|
||||
|
||||
|
@ -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",
|
||||
|
@ -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 {
|
||||
|
@ -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 {
|
||||
|
@ -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 {
|
||||
|
@ -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)
|
||||
|
@ -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)
|
||||
|
@ -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()
|
||||
|
@ -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()
|
||||
|
||||
}
|
||||
|
@ -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()
|
||||
}
|
||||
|
@ -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 {
|
||||
|
@ -8,7 +8,7 @@ import (
|
||||
|
||||
var (
|
||||
tableName = "orders"
|
||||
dao = g.DB().Table(tableName).Safe()
|
||||
dao = g.DB().Model(tableName).Safe()
|
||||
)
|
||||
|
||||
type OrderServiceEntity struct {
|
||||
|
@ -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))
|
||||
}
|
||||
|
@ -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)
|
||||
}
|
||||
|
@ -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)
|
||||
|
@ -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)
|
||||
}
|
||||
|
@ -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)
|
||||
}
|
||||
|
@ -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)
|
||||
}
|
||||
|
@ -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")
|
||||
|
@ -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)
|
||||
}
|
||||
|
@ -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)
|
||||
}
|
||||
|
@ -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()
|
||||
|
@ -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)
|
||||
}
|
||||
|
@ -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 {
|
||||
|
@ -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.
|
||||
|
@ -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.
|
||||
|
@ -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.
|
||||
|
@ -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.
|
||||
|
@ -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.
|
||||
|
@ -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.
|
||||
|
@ -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.
|
||||
|
@ -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.
|
||||
|
@ -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 <cap> elements.
|
||||
// The optional parameter <safe> 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 <value> 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 <f> within RWMutex.RLock.
|
||||
// If <f> 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 <f> within RWMutex.RLock.
|
||||
// If <f> 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 <f> within RWMutex.RLock.
|
||||
// If <f> 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 <f> within RWMutex.RLock.
|
||||
// If <f> 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
|
||||
|
@ -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
|
||||
})
|
||||
|
||||
})
|
||||
}
|
||||
|
@ -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
|
||||
}
|
||||
|
||||
|
@ -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.
|
||||
|
@ -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
|
||||
}
|
||||
|
||||
|
@ -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
|
||||
}
|
||||
|
||||
|
@ -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
|
||||
}
|
||||
|
||||
|
@ -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
|
||||
}
|
||||
|
||||
|
@ -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
|
||||
}
|
||||
|
||||
|
@ -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
|
||||
}
|
||||
|
||||
|
@ -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
|
||||
}
|
||||
|
||||
|
@ -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
|
||||
}
|
||||
|
||||
|
@ -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
|
||||
}
|
||||
|
||||
|
@ -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",
|
||||
|
@ -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...)
|
||||
|
@ -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.
|
||||
|
@ -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 (
|
||||
|
@ -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 {
|
||||
|
@ -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{}.
|
||||
|
@ -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 {
|
||||
|
@ -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 <path> 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 <path> 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.
|
||||
|
@ -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
|
||||
|
@ -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
|
||||
|
@ -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 <pattern> 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 <pattern> and converts it to specified object
|
||||
|
@ -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())
|
||||
}
|
||||
|
@ -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
|
||||
}
|
||||
|
@ -35,7 +35,7 @@ func Decode(data interface{}) (interface{}, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// Decode decodes json format <data> to specified golang variable <v>.
|
||||
// DecodeTo decodes json format <data> to specified golang variable <v>.
|
||||
// The parameter <data> can be either bytes or string type.
|
||||
// The parameter <v> should be a pointer type.
|
||||
func DecodeTo(data interface{}, v interface{}) error {
|
||||
|
@ -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)
|
||||
|
@ -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 (
|
||||
|
@ -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...)
|
||||
|
10
go.mod
10
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
|
||||
|
24
go.sum
24
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=
|
||||
|
@ -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))
|
||||
|
@ -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
|
||||
}
|
||||
|
@ -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
|
||||
|
@ -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)
|
||||
|
@ -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),
|
||||
)
|
||||
}
|
||||
|
@ -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.
|
||||
|
@ -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),
|
||||
)
|
||||
}
|
||||
|
@ -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,
|
||||
)
|
||||
|
@ -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)
|
||||
}
|
||||
|
@ -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 <path> 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 <path> as []byte.
|
||||
|
@ -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)
|
||||
|
@ -80,9 +80,9 @@ func Uptime() time.Duration {
|
||||
return time.Now().Sub(processStartTime)
|
||||
}
|
||||
|
||||
// Shell executes command <cmd> synchronizingly with given input pipe <in> and output pipe <out>.
|
||||
// The command <cmd> reads the input parameters from input pipe <in>, and writes its output automatically
|
||||
// to output pipe <out>.
|
||||
// Shell executes command <cmd> synchronously with given input pipe <in> and output pipe `out`.
|
||||
// The command <cmd> 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 <cmd> 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 <cmd> 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 <cmd> into slice arguments.
|
||||
// parseCommand parses command `cmd` into slice arguments.
|
||||
//
|
||||
// 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.
|
||||
// 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 <file> 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 <file> in PATH environment.
|
||||
// SearchBinaryPath searches the binary `file` in PATH environment.
|
||||
func SearchBinaryPath(file string) string {
|
||||
array := ([]string)(nil)
|
||||
switch runtime.GOOS {
|
||||
|
@ -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,
|
||||
|
@ -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
|
||||
|
@ -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))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -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())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -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 ,
|
||||
|
@ -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)
|
||||
}
|
||||
|
@ -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
|
||||
|
@ -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.
|
||||
|
@ -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))
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
Loading…
Reference in New Issue
Block a user