diff --git a/.example/container/garray/basic_array.go b/.example/container/garray/basic_array.go deleted file mode 100644 index 3db377d4d..000000000 --- a/.example/container/garray/basic_array.go +++ /dev/null @@ -1,46 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/garray" -) - -func main() { - // Create a int array, which is concurrent-unsafe in default. - a := garray.NewIntArray() - - // Appending items. - for i := 0; i < 10; i++ { - a.Append(i) - } - - // Get the length of the array. - fmt.Println(a.Len()) - - // Get the slice of the array. - fmt.Println(a.Slice()) - - // Get the item of specified index. - fmt.Println(a.Get(6)) - - // Insert after/before specified index. - a.InsertAfter(9, 11) - a.InsertBefore(10, 10) - fmt.Println(a.Slice()) - - a.Set(0, 100) - fmt.Println(a.Slice()) - - // Searching the item and returning the index. - fmt.Println(a.Search(5)) - - // Remove item of specified index. - a.Remove(0) - fmt.Println(a.Slice()) - - // Clearing the array. - fmt.Println(a.Slice()) - a.Clear() - fmt.Println(a.Slice()) -} diff --git a/.example/container/garray/json_marshal.go b/.example/container/garray/json_marshal.go deleted file mode 100644 index 4f5859413..000000000 --- a/.example/container/garray/json_marshal.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "github.com/gogf/gf/v2/container/garray" -) - -func main() { - type Student struct { - Id int - Name string - Scores *garray.IntArray - } - s := Student{ - Id: 1, - Name: "john", - Scores: garray.NewIntArrayFrom([]int{100, 99, 98}), - } - b, _ := json.Marshal(s) - fmt.Println(string(b)) -} diff --git a/.example/container/garray/json_unmarshal.go b/.example/container/garray/json_unmarshal.go deleted file mode 100644 index 144287a99..000000000 --- a/.example/container/garray/json_unmarshal.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "github.com/gogf/gf/v2/container/garray" -) - -func main() { - b := []byte(`{"Id":1,"Name":"john","Scores":[100,99,98]}`) - type Student struct { - Id int - Name string - Scores *garray.IntArray - } - s := Student{} - json.Unmarshal(b, &s) - fmt.Println(s) -} diff --git a/.example/container/garray/sorted_array_basic.go b/.example/container/garray/sorted_array_basic.go deleted file mode 100644 index 81e0531f8..000000000 --- a/.example/container/garray/sorted_array_basic.go +++ /dev/null @@ -1,40 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/garray" -) - -func main() { - // 自定义排序数组,降序排序(SortedIntArray管理的数据是升序) - a := garray.NewSortedArray(func(v1, v2 interface{}) int { - if v1.(int) < v2.(int) { - return 1 - } - if v1.(int) > v2.(int) { - return -1 - } - return 0 - }) - - // 添加数据 - a.Add(2) - a.Add(3) - a.Add(1) - fmt.Println(a.Slice()) - - // 添加重复数据 - a.Add(3) - fmt.Println(a.Slice()) - - // 检索数据,返回最后对比的索引位置,检索结果 - // 检索结果:0: 匹配; <0:参数小于对比值; >0:参数大于对比值 - fmt.Println(a.Search(1)) - - // 设置不可重复 - a.SetUnique(true) - fmt.Println(a.Slice()) - a.Add(1) - fmt.Println(a.Slice()) -} diff --git a/.example/container/garray/sorted_string_array.go b/.example/container/garray/sorted_string_array.go deleted file mode 100644 index a89de1f46..000000000 --- a/.example/container/garray/sorted_string_array.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/garray" -) - -func main() { - array := garray.NewSortedStrArray() - array.Add("9") - array.Add("8") - array.Add("7") - array.Add("6") - array.Add("5") - array.Add("4") - array.Add("3") - array.Add("2") - array.Add("1") - fmt.Println(array.Slice()) - // output: - // [1 2 3 4 5 6 7 8 9] -} diff --git a/.example/container/glist/basic.go b/.example/container/glist/basic.go deleted file mode 100644 index a904ea345..000000000 --- a/.example/container/glist/basic.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/container/glist" -) - -func main() { - l := glist.New() - // Push - l.PushBack(1) - l.PushBack(2) - e := l.PushFront(0) - // Insert - l.InsertBefore(e, -1) - l.InsertAfter(e, "a") - fmt.Println(l) - // Pop - fmt.Println(l.PopFront()) - fmt.Println(l.PopBack()) - fmt.Println(l) -} diff --git a/.example/container/glist/json_marshal.go b/.example/container/glist/json_marshal.go deleted file mode 100644 index 00cc3409b..000000000 --- a/.example/container/glist/json_marshal.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "github.com/gogf/gf/v2/container/glist" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - type Student struct { - Id int - Name string - Scores *glist.List - } - s := Student{ - Id: 1, - Name: "john", - Scores: glist.NewFrom(g.Slice{100, 99, 98}), - } - b, _ := json.Marshal(s) - fmt.Println(string(b)) -} diff --git a/.example/container/glist/json_unmarshal.go b/.example/container/glist/json_unmarshal.go deleted file mode 100644 index 7b03f7cff..000000000 --- a/.example/container/glist/json_unmarshal.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "github.com/gogf/gf/v2/container/glist" -) - -func main() { - b := []byte(`{"Id":1,"Name":"john","Scores":[100,99,98]}`) - type Student struct { - Id int - Name string - Scores *glist.List - } - s := Student{} - json.Unmarshal(b, &s) - fmt.Println(s) -} diff --git a/.example/container/gmap/basic.go b/.example/container/gmap/basic.go deleted file mode 100644 index 4d9b5a453..000000000 --- a/.example/container/gmap/basic.go +++ /dev/null @@ -1,74 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/gmap" -) - -func main() { - // 创建一个默认的gmap对象, - // 默认情况下该gmap对象不支持并发安全特性, - // 初始化时可以给定true参数开启并发安全特性,用以并发安全场景。 - m := gmap.New() - - // 设置键值对 - for i := 0; i < 10; i++ { - m.Set(i, i) - } - // 查询大小 - fmt.Println(m.Size()) - // 批量设置键值对(不同的数据类型对象参数不同) - m.Sets(map[interface{}]interface{}{ - 10: 10, - 11: 11, - }) - fmt.Println(m.Size()) - - // 查询是否存在 - fmt.Println(m.Contains(1)) - - // 查询键值 - fmt.Println(m.Get(1)) - - // 删除数据项 - m.Remove(9) - fmt.Println(m.Size()) - - // 批量删除 - m.Removes([]interface{}{10, 11}) - fmt.Println(m.Size()) - - // 当前键名列表(随机排序) - fmt.Println(m.Keys()) - // 当前键值列表(随机排序) - fmt.Println(m.Values()) - - // 查询键名,当键值不存在时,写入给定的默认值 - fmt.Println(m.GetOrSet(100, 100)) - - // 删除键值对,并返回对应的键值 - fmt.Println(m.Remove(100)) - - // 遍历map - m.Iterator(func(k interface{}, v interface{}) bool { - fmt.Printf("%v:%v ", k, v) - return true - }) - - // 自定义写锁操作 - m.LockFunc(func(m map[interface{}]interface{}) { - m[99] = 99 - }) - - // 自定义读锁操作 - m.RLockFunc(func(m map[interface{}]interface{}) { - fmt.Println(m[99]) - }) - - // 清空map - m.Clear() - - // 判断map是否为空 - fmt.Println(m.IsEmpty()) -} diff --git a/.example/container/gmap/gmap_json_marshal.go b/.example/container/gmap/gmap_json_marshal.go deleted file mode 100644 index 76ac64630..000000000 --- a/.example/container/gmap/gmap_json_marshal.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "github.com/gogf/gf/v2/frame/g" - - "github.com/gogf/gf/v2/container/gmap" -) - -func main() { - m := gmap.New() - m.Sets(g.MapAnyAny{ - "name": "john", - "score": 100, - }) - b, _ := json.Marshal(m) - fmt.Println(string(b)) -} diff --git a/.example/container/gmap/gmap_json_unmarshal.go b/.example/container/gmap/gmap_json_unmarshal.go deleted file mode 100644 index 7f5a9d24a..000000000 --- a/.example/container/gmap/gmap_json_unmarshal.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "github.com/gogf/gf/v2/container/gmap" -) - -func main() { - m := gmap.Map{} - s := []byte(`{"name":"john","score":100}`) - json.Unmarshal(s, &m) - fmt.Println(m.Map()) -} diff --git a/.example/container/gmap/gmap_map_clone_safe.go b/.example/container/gmap/gmap_map_clone_safe.go deleted file mode 100644 index 912ea9eff..000000000 --- a/.example/container/gmap/gmap_map_clone_safe.go +++ /dev/null @@ -1,26 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/container/gmap" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - m1 := gmap.New(true) - m1.Set("1", "1") - - m2 := m1.Map() - m2["2"] = "2" - - g.Dump(m1.Clone()) - g.Dump(m2) - //output: - //{ - // "1": "1" - //} - // - //{ - // "1": "1", - // "2": "2" - //} -} diff --git a/.example/container/gmap/gmap_maps.go b/.example/container/gmap/gmap_maps.go deleted file mode 100644 index 7b7267b1b..000000000 --- a/.example/container/gmap/gmap_maps.go +++ /dev/null @@ -1,31 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/gmap" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gutil" -) - -func main() { - array := g.Slice{2, 3, 1, 5, 4, 6, 8, 7, 9} - hashMap := gmap.New() - linkMap := gmap.NewListMap() - treeMap := gmap.NewTreeMap(gutil.ComparatorInt) - for _, v := range array { - hashMap.Set(v, v) - } - for _, v := range array { - linkMap.Set(v, v) - } - for _, v := range array { - treeMap.Set(v, v) - } - fmt.Println("HashMap Keys:", hashMap.Keys()) - fmt.Println("HashMap Values:", hashMap.Values()) - fmt.Println("LinkMap Keys:", linkMap.Keys()) - fmt.Println("LinkMap Values:", linkMap.Values()) - fmt.Println("TreeMap Keys:", treeMap.Keys()) - fmt.Println("TreeMap Values:", treeMap.Values()) -} diff --git a/.example/container/gmap/gmap_treemap.go b/.example/container/gmap/gmap_treemap.go deleted file mode 100644 index d495ac336..000000000 --- a/.example/container/gmap/gmap_treemap.go +++ /dev/null @@ -1,63 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/gmap" - "github.com/gogf/gf/v2/util/gutil" -) - -func main() { - m := gmap.NewTreeMap(gutil.ComparatorInt) - - // 设置键值对 - for i := 0; i < 10; i++ { - m.Set(i, i) - } - // 查询大小 - fmt.Println(m.Size()) - // 批量设置键值对(不同的数据类型对象参数不同) - m.Sets(map[interface{}]interface{}{ - 10: 10, - 11: 11, - }) - fmt.Println(m.Size()) - - // 查询是否存在 - fmt.Println(m.Contains(1)) - - // 查询键值 - fmt.Println(m.Get(1)) - - // 删除数据项 - m.Remove(9) - fmt.Println(m.Size()) - - // 批量删除 - m.Removes([]interface{}{10, 11}) - fmt.Println(m.Size()) - - // 当前键名列表(随机排序) - fmt.Println(m.Keys()) - // 当前键值列表(随机排序) - fmt.Println(m.Values()) - - // 查询键名,当键值不存在时,写入给定的默认值 - fmt.Println(m.GetOrSet(100, 100)) - - // 删除键值对,并返回对应的键值 - fmt.Println(m.Remove(100)) - - // 遍历map - m.IteratorAsc(func(k interface{}, v interface{}) bool { - fmt.Printf("%v:%v ", k, v) - return true - }) - fmt.Println() - - // 清空map - m.Clear() - - // 判断map是否为空 - fmt.Println(m.IsEmpty()) -} diff --git a/.example/container/gpool/gpool.go b/.example/container/gpool/gpool.go deleted file mode 100644 index a027dcba5..000000000 --- a/.example/container/gpool/gpool.go +++ /dev/null @@ -1,26 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/container/gpool" -) - -func main() { - // 创建一个对象池,过期时间为1000毫秒 - p := gpool.New(1000*time.Millisecond, nil) - - // 从池中取一个对象,返回nil及错误信息 - fmt.Println(p.Get()) - - // 丢一个对象到池中 - p.Put(1) - - // 重新从池中取一个对象,返回1 - fmt.Println(p.Get()) - - // 等待1秒后重试,发现对象已过期,返回nil及错误信息 - time.Sleep(time.Second) - fmt.Println(p.Get()) -} diff --git a/.example/container/gpool/gpool_expirefunc.go b/.example/container/gpool/gpool_expirefunc.go deleted file mode 100644 index 36ded0980..000000000 --- a/.example/container/gpool/gpool_expirefunc.go +++ /dev/null @@ -1,33 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/container/gpool" - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - // 创建对象复用池,对象过期时间为3000毫秒,并给定创建及销毁方法 - p := gpool.New(3000*time.Millisecond, func() (interface{}, error) { - return gtcp.NewConn("www.baidu.com:80") - }, func(i interface{}) { - glog.Print("expired") - i.(*gtcp.Conn).Close() - }) - conn, err := p.Get() - if err != nil { - panic(err) - } - result, err := conn.(*gtcp.Conn).SendRecv([]byte("HEAD / HTTP/1.1\n\n"), -1) - if err != nil { - panic(err) - } - fmt.Println(string(result)) - // 丢回池中以便重复使用 - p.Put(conn) - // 等待一定时间观察过期方法调用 - time.Sleep(4 * time.Second) -} diff --git a/.example/container/gqueue/gqueue.go b/.example/container/gqueue/gqueue.go deleted file mode 100644 index 5a1474330..000000000 --- a/.example/container/gqueue/gqueue.go +++ /dev/null @@ -1,34 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/container/gqueue" - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - q := gqueue.New() - // 数据生产者,每隔1秒往队列写数据 - gtimer.SetInterval(time.Second, func() { - v := gtime.Now().String() - q.Push(v) - fmt.Println("Push:", v) - }) - - // 3秒后关闭队列 - gtimer.SetTimeout(3*time.Second, func() { - q.Close() - }) - - // 消费者,不停读取队列数据并输出到终端 - for { - if v := q.Pop(); v != nil { - fmt.Println(" Pop:", v) - } else { - break - } - } -} diff --git a/.example/container/gqueue/gqueue2.go b/.example/container/gqueue/gqueue2.go deleted file mode 100644 index 6b5459c47..000000000 --- a/.example/container/gqueue/gqueue2.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/container/gqueue" - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - q := gqueue.New() - // 数据生产者,每隔1秒往队列写数据 - gtimer.SetInterval(time.Second, func() { - for i := 0; i < 10; i++ { - q.Push(i) - } - }) - - // 消费者,不停读取队列数据并输出到终端 - for { - if v := q.Pop(); v != nil { - fmt.Println(" Pop:", v) - } else { - break - } - } -} diff --git a/.example/container/gqueue/gqueue3.go b/.example/container/gqueue/gqueue3.go deleted file mode 100644 index 55c279a4c..000000000 --- a/.example/container/gqueue/gqueue3.go +++ /dev/null @@ -1,30 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/container/gqueue" - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - queue := gqueue.New() - // 数据生产者,每隔1秒往队列写数据 - gtimer.SetInterval(time.Second, func() { - queue.Push(gtime.Now().String()) - }) - - // 消费者,不停读取队列数据并输出到终端 - for { - select { - case v := <-queue.C: - if v != nil { - fmt.Println(v) - } else { - return - } - } - } -} diff --git a/.example/container/gring/gring.go b/.example/container/gring/gring.go deleted file mode 100644 index 871c4b9c2..000000000 --- a/.example/container/gring/gring.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/gring" -) - -func main() { - r1 := gring.New(10) - for i := 0; i < 5; i++ { - r1.Set(i).Next() - } - fmt.Println("Len:", r1.Len()) - fmt.Println("Cap:", r1.Cap()) - fmt.Println(r1.SlicePrev()) - fmt.Println(r1.SliceNext()) - - r2 := gring.New(10) - for i := 0; i < 10; i++ { - r2.Set(i).Next() - } - fmt.Println("Len:", r2.Len()) - fmt.Println("Cap:", r2.Cap()) - fmt.Println(r2.SlicePrev()) - fmt.Println(r2.SliceNext()) - -} diff --git a/.example/container/gring/gring_josephus.go b/.example/container/gring/gring_josephus.go deleted file mode 100644 index 078c31b5e..000000000 --- a/.example/container/gring/gring_josephus.go +++ /dev/null @@ -1,58 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/gring" -) - -type Player struct { - position int // 位置 - alive bool // 是否存活 -} - -const ( - playerCount = 41 // 玩家人数 - startPos = 1 // 开始报数位置 -) - -var ( - deadline = 3 -) - -func main() { - // 关闭并发安全,当前场景没有必要 - r := gring.New(playerCount, false) - - // 设置所有玩家初始值 - for i := 1; i <= playerCount; i++ { - r.Put(&Player{i, true}) - } - - // 如果开始报数的位置不为1,则设置开始位置 - if startPos > 1 { - r.Move(startPos - 1) - } - - counter := 1 // 报数从1开始,因为下面的循环从第二个开始计算 - deadCount := 0 // 死亡人数,初始值为0 - - // 直到所有人都死亡,否则循环一直执行 - for deadCount < playerCount { - // 跳到下一个人 - r.Next() - - // 如果是活着的人,则报数 - if r.Val().(*Player).alive { - counter++ - } - - // 如果报数为deadline,则此人淘汰出局 - if counter == deadline { - r.Val().(*Player).alive = false - fmt.Printf("Player %d died!\n", r.Val().(*Player).position) - deadCount++ - counter = 0 - } - } -} diff --git a/.example/container/gset/gset1.go b/.example/container/gset/gset1.go deleted file mode 100644 index 2033edf3c..000000000 --- a/.example/container/gset/gset1.go +++ /dev/null @@ -1,53 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/gset" -) - -func main() { - // 创建一个非并发安全的集合对象 - s := gset.New(true) - - // 添加数据项 - s.Add(1) - - // 批量添加数据项 - s.Add([]interface{}{1, 2, 3}...) - - // 集合数据项大小 - fmt.Println(s.Size()) - - // 集合中是否存在指定数据项 - fmt.Println(s.Contains(2)) - - // 返回数据项slice - fmt.Println(s.Slice()) - - // 删除数据项 - s.Remove(3) - - // 遍历数据项 - s.Iterator(func(v interface{}) bool { - fmt.Println("Iterator:", v) - return true - }) - - // 将集合转换为字符串 - fmt.Println(s.String()) - - // 并发安全写锁操作 - s.LockFunc(func(m map[interface{}]struct{}) { - m[4] = struct{}{} - }) - - // 并发安全读锁操作 - s.RLockFunc(func(m map[interface{}]struct{}) { - fmt.Println(m) - }) - - // 清空集合 - s.Clear() - fmt.Println(s.Size()) -} diff --git a/.example/container/gset/gset2.go b/.example/container/gset/gset2.go deleted file mode 100644 index 25fc11762..000000000 --- a/.example/container/gset/gset2.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/gset" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - s1 := gset.NewFrom(g.Slice{1, 2, 3}) - s2 := gset.NewFrom(g.Slice{4, 5, 6}) - s3 := gset.NewFrom(g.Slice{1, 2, 3, 4, 5, 6, 7}) - - // 交集 - fmt.Println(s3.Intersect(s1).Slice()) - // 差集 - fmt.Println(s3.Diff(s1).Slice()) - // 并集 - fmt.Println(s1.Union(s2).Slice()) - // 补集 - fmt.Println(s1.Complement(s3).Slice()) -} diff --git a/.example/container/gset/json_marshal.go b/.example/container/gset/json_marshal.go deleted file mode 100644 index a554f1e3b..000000000 --- a/.example/container/gset/json_marshal.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "github.com/gogf/gf/v2/container/gset" -) - -func main() { - type Student struct { - Id int - Name string - Scores *gset.IntSet - } - s := Student{ - Id: 1, - Name: "john", - Scores: gset.NewIntSetFrom([]int{100, 99, 98}), - } - b, _ := json.Marshal(s) - fmt.Println(string(b)) -} diff --git a/.example/container/gset/json_unmarshal.go b/.example/container/gset/json_unmarshal.go deleted file mode 100644 index a71208a31..000000000 --- a/.example/container/gset/json_unmarshal.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "github.com/gogf/gf/v2/container/gset" -) - -func main() { - b := []byte(`{"Id":1,"Name":"john","Scores":[100,99,98]}`) - type Student struct { - Id int - Name string - Scores *gset.IntSet - } - s := Student{} - json.Unmarshal(b, &s) - fmt.Println(s) -} diff --git a/.example/container/gtree/gtree_avltree.go b/.example/container/gtree/gtree_avltree.go deleted file mode 100644 index 5814212ec..000000000 --- a/.example/container/gtree/gtree_avltree.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/gtree" - "github.com/gogf/gf/v2/util/gutil" -) - -func main() { - tree := gtree.NewAVLTree(gutil.ComparatorInt) - for i := 0; i < 10; i++ { - tree.Set(i, i*10) - } - // 打印树形 - tree.Print() - // 前序遍历 - fmt.Println("ASC:") - tree.IteratorAsc(func(key, value interface{}) bool { - fmt.Println(key, value) - return true - }) - // 后续遍历 - fmt.Println("DESC:") - tree.IteratorDesc(func(key, value interface{}) bool { - fmt.Println(key, value) - return true - }) -} diff --git a/.example/container/gtree/gtree_btree.go b/.example/container/gtree/gtree_btree.go deleted file mode 100644 index f1b04d66b..000000000 --- a/.example/container/gtree/gtree_btree.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/gtree" -) - -func main() { - tree := gtree.NewBTree(10, func(v1, v2 interface{}) int { - return v1.(int) - v2.(int) - }) - for i := 0; i < 20; i++ { - tree.Set(i, i*10) - } - fmt.Println(tree.String()) - - tree.IteratorDesc(func(key, value interface{}) bool { - fmt.Println(key, value) - return true - }) -} diff --git a/.example/container/gtree/gtree_redblackmap.go b/.example/container/gtree/gtree_redblackmap.go deleted file mode 100644 index 5689110a2..000000000 --- a/.example/container/gtree/gtree_redblackmap.go +++ /dev/null @@ -1,63 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/gtree" - "github.com/gogf/gf/v2/util/gutil" -) - -func main() { - m := gtree.NewRedBlackTree(gutil.ComparatorInt) - - // 设置键值对 - for i := 0; i < 10; i++ { - m.Set(i, i*10) - } - // 查询大小 - fmt.Println(m.Size()) - // 批量设置键值对(不同的数据类型对象参数不同) - m.Sets(map[interface{}]interface{}{ - 10: 10, - 11: 11, - }) - fmt.Println(m.Size()) - - // 查询是否存在 - fmt.Println(m.Contains(1)) - - // 查询键值 - fmt.Println(m.Get(1)) - - // 删除数据项 - m.Remove(9) - fmt.Println(m.Size()) - - // 批量删除 - m.Removes([]interface{}{10, 11}) - fmt.Println(m.Size()) - - // 当前键名列表(随机排序) - fmt.Println(m.Keys()) - // 当前键值列表(随机排序) - fmt.Println(m.Values()) - - // 查询键名,当键值不存在时,写入给定的默认值 - fmt.Println(m.GetOrSet(100, 100)) - - // 删除键值对,并返回对应的键值 - fmt.Println(m.Remove(100)) - - // 遍历map - m.IteratorAsc(func(k interface{}, v interface{}) bool { - fmt.Printf("%v:%v ", k, v) - return true - }) - fmt.Println() - - // 清空map - m.Clear() - - // 判断map是否为空 - fmt.Println(m.IsEmpty()) -} diff --git a/.example/container/gtree/gtree_redblacktree.go b/.example/container/gtree/gtree_redblacktree.go deleted file mode 100644 index 01bbafb69..000000000 --- a/.example/container/gtree/gtree_redblacktree.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/container/gtree" -) - -func main() { - tree := gtree.NewRedBlackTree(func(v1, v2 interface{}) int { - return v1.(int) - v2.(int) - }) - for i := 0; i < 10; i++ { - tree.Set(i, i) - } - tree.Print() - tree.Flip() - tree.Print() -} diff --git a/.example/container/gtype/gtype_int.go b/.example/container/gtype/gtype_int.go deleted file mode 100644 index ba8307290..000000000 --- a/.example/container/gtype/gtype_int.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/gtype" -) - -func main() { - // 创建一个Int型的并发安全基本类型对象 - i := gtype.NewInt() - - // 设置值 - i.Set(10) - - // 获取值 - fmt.Println(i.Val()) - - // (整型/浮点型有效)数值 增加/删除 delta - fmt.Println(i.Add(-1)) -} diff --git a/.example/container/gtype/json_marshal.go b/.example/container/gtype/json_marshal.go deleted file mode 100644 index e91e4d7d9..000000000 --- a/.example/container/gtype/json_marshal.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "github.com/gogf/gf/v2/container/gtype" -) - -func main() { - type Student struct { - Id *gtype.Int - Name *gtype.String - Scores *gtype.Interface - } - s := Student{ - Id: gtype.NewInt(1), - Name: gtype.NewString("john"), - Scores: gtype.NewInterface([]int{100, 99, 98}), - } - b, _ := json.Marshal(s) - fmt.Println(string(b)) -} diff --git a/.example/container/gtype/json_unmarshal.go b/.example/container/gtype/json_unmarshal.go deleted file mode 100644 index d460cfc67..000000000 --- a/.example/container/gtype/json_unmarshal.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "github.com/gogf/gf/v2/container/gtype" -) - -func main() { - b := []byte(`{"Id":1,"Name":"john","Scores":[100,99,98]}`) - type Student struct { - Id *gtype.Int - Name *gtype.String - Scores *gtype.Interface - } - s := Student{} - json.Unmarshal(b, &s) - fmt.Println(s) -} diff --git a/.example/container/gvar/json_marshal.go b/.example/container/gvar/json_marshal.go deleted file mode 100644 index fbbb01679..000000000 --- a/.example/container/gvar/json_marshal.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - type Student struct { - Id *g.Var - Name *g.Var - Scores *g.Var - } - s := Student{ - Id: g.NewVar(1), - Name: g.NewVar("john"), - Scores: g.NewVar([]int{100, 99, 98}), - } - b, _ := json.Marshal(s) - fmt.Println(string(b)) -} diff --git a/.example/container/gvar/json_unmarshal.go b/.example/container/gvar/json_unmarshal.go deleted file mode 100644 index 2e79601e7..000000000 --- a/.example/container/gvar/json_unmarshal.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - b := []byte(`{"Id":1,"Name":"john","Scores":[100,99,98]}`) - type Student struct { - Id *g.Var - Name *g.Var - Scores *g.Var - } - s := Student{} - json.Unmarshal(b, &s) - fmt.Println(s) -} diff --git a/.example/container/gvar/var.go b/.example/container/gvar/var.go deleted file mode 100644 index 7752eed11..000000000 --- a/.example/container/gvar/var.go +++ /dev/null @@ -1,33 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - var v g.Var - - v.Set("123") - - fmt.Println(v.Val()) - - // 基本类型转换 - fmt.Println(v.Int()) - fmt.Println(v.Uint()) - fmt.Println(v.Float64()) - - // slice转换 - fmt.Println(v.Ints()) - fmt.Println(v.Floats()) - fmt.Println(v.Strings()) - - // struct转换 - type Score struct { - Value int - } - s := new(Score) - v.Struct(s) - fmt.Println(s) -} diff --git a/.example/database/gdb/driver/driver/driver.go b/.example/database/gdb/driver/driver/driver.go deleted file mode 100644 index 9350832c1..000000000 --- a/.example/database/gdb/driver/driver/driver.go +++ /dev/null @@ -1,71 +0,0 @@ -package driver - -import ( - "context" - "database/sql" - "github.com/gogf/gf/v2/database/gdb" - "github.com/gogf/gf/v2/os/gtime" -) - -// MyDriver is a custom database driver, which is used for testing only. -// For simplifying the unit testing case purpose, MyDriver struct inherits the mysql driver -// gdb.DriverMysql and overwrites its functions DoQuery and DoExec. -// So if there's any sql execution, it goes through MyDriver.DoQuery/MyDriver.DoExec firstly -// and then gdb.DriverMysql.DoQuery/gdb.DriverMysql.DoExec. -// You can call it sql "HOOK" or "HiJack" as your will. -type MyDriver struct { - *gdb.DriverMysql -} - -var ( - // customDriverName is my driver name, which is used for registering. - customDriverName = "MyDriver" -) - -func init() { - // It here registers my custom driver in package initialization function "init". - // You can later use this type in the database configuration. - if err := gdb.Register(customDriverName, &MyDriver{}); err != nil { - panic(err) - } -} - -// New creates and returns a database object for mysql. -// It implements the interface of gdb.Driver for extra database driver installation. -func (d *MyDriver) New(core *gdb.Core, node *gdb.ConfigNode) (gdb.DB, error) { - return &MyDriver{ - &gdb.DriverMysql{ - Core: core, - }, - }, nil -} - -// DoQuery commits the sql string and its arguments to underlying driver -// through given link object and returns the execution result. -func (d *MyDriver) DoQuery(ctx context.Context, link gdb.Link, sql string, args ...interface{}) (rows *sql.Rows, err error) { - tsMilli := gtime.TimestampMilli() - rows, err = d.DriverMysql.DoQuery(ctx, link, sql, args...) - link.Exec( - "INSERT INTO `monitor`(`sql`,`cost`,`time`,`error`) VALUES(?,?,?,?)", - gdb.FormatSqlWithArgs(sql, args), - gtime.TimestampMilli()-tsMilli, - gtime.Now(), - err, - ) - return -} - -// DoExec commits the query string and its arguments to underlying driver -// through given link object and returns the execution result. -func (d *MyDriver) DoExec(ctx context.Context, link gdb.Link, sql string, args ...interface{}) (result sql.Result, err error) { - tsMilli := gtime.TimestampMilli() - result, err = d.DriverMysql.DoExec(ctx, link, sql, args...) - link.Exec( - "INSERT INTO `monitor`(`sql`,`cost`,`time`,`error`) VALUES(?,?,?,?)", - gdb.FormatSqlWithArgs(sql, args), - gtime.TimestampMilli()-tsMilli, - gtime.Now(), - err, - ) - return -} diff --git a/.example/database/gdb/driver/main.go b/.example/database/gdb/driver/main.go deleted file mode 100644 index 06ab7d0f9..000000000 --- a/.example/database/gdb/driver/main.go +++ /dev/null @@ -1 +0,0 @@ -package main diff --git a/.example/database/gdb/mssql/config.toml b/.example/database/gdb/mssql/config.toml deleted file mode 100644 index a57e9aa78..000000000 --- a/.example/database/gdb/mssql/config.toml +++ /dev/null @@ -1,3 +0,0 @@ - -[database] - linkinfo = "mssql:user id=test;password=test1;server=122.152.202.91;port=1433;database=test;encrypt=disable" \ No newline at end of file diff --git a/.example/database/gdb/mssql/gdb_all.go b/.example/database/gdb/mssql/gdb_all.go deleted file mode 100644 index 396099c6a..000000000 --- a/.example/database/gdb/mssql/gdb_all.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/os/gtime" - - //_ "github.com/denisenkom/go-mssqldb" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - type Table2 struct { - Id string `orm:"id;pr" json:"id"` //ID - CreateTime gtime.Time `orm:"createtime" json:"createtime"` //创建时间 - UpdateTime gtime.Time `orm:"updatetime" json:"updatetime"` //更新时间 - } - var table2 Table2 - err := g.DB().Model("table2").Where("id", 1).Scan(&table2) - if err != nil { - panic(err) - } - fmt.Println(table2.CreateTime) -} diff --git a/.example/database/gdb/mssql/gdb_sqlserver.go b/.example/database/gdb/mssql/gdb_sqlserver.go deleted file mode 100644 index 1281f0e08..000000000 --- a/.example/database/gdb/mssql/gdb_sqlserver.go +++ /dev/null @@ -1,565 +0,0 @@ -package main - -import ( - "fmt" - "time" - - //_ "github.com/denisenkom/go-mssqldb" - "github.com/gogf/gf/v2/database/gdb" - "github.com/gogf/gf/v2/frame/g" -) - -// 本文件用于gf框架的mssql数据库操作示例,不作为单元测试使用 - -var db gdb.DB - -// 初始化配置及创建数据库 -func init() { - gdb.AddDefaultConfigNode(gdb.ConfigNode{ - Host: "127.0.0.1", - Port: "1433", - User: "sa", - Pass: "123456", - Name: "test", - Type: "mssql", - Role: "master", - Charset: "utf8", - }) - db, _ = gdb.New() - - //gins.Config().SetPath("/home/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/.example/frame") - //db = g.Database() - - //gdb.SetConfig(gdb.ConfigNode { - // Host : "127.0.0.1", - // Port : 3306, - // User : "root", - // Pass : "123456", - // Name : "test", - // Type : "mysql", - //}) - //db, _ = gdb.Instance() - - //gdb.SetConfig(gdb.Config { - // "default" : gdb.ConfigGroup { - // gdb.ConfigNode { - // Host : "127.0.0.1", - // Port : "3306", - // User : "root", - // Pass : "123456", - // Name : "test", - // Type : "mysql", - // Role : "master", - // Weight : 100, - // }, - // gdb.ConfigNode { - // Host : "127.0.0.2", - // Port : "3306", - // User : "root", - // Pass : "123456", - // Name : "test", - // Type : "mysql", - // Role : "master", - // Weight : 100, - // }, - // gdb.ConfigNode { - // Host : "127.0.0.3", - // Port : "3306", - // User : "root", - // Pass : "123456", - // Name : "test", - // Type : "mysql", - // Role : "master", - // Weight : 100, - // }, - // gdb.ConfigNode { - // Host : "127.0.0.4", - // Port : "3306", - // User : "root", - // Pass : "123456", - // Name : "test", - // Type : "mysql", - // Role : "master", - // Weight : 100, - // }, - // }, - //}) - //db, _ = gdb.Instance() -} - -// 创建测试数据库 -func create() error { - fmt.Println("drop table aa_user:") - _, err := db.Exec("drop table aa_user") - if err != nil { - fmt.Println("drop table aa_user error.", err) - } - - s := ` - CREATE TABLE aa_user ( - id int not null, - name VARCHAR(60), - age int, - addr varchar(60), - PRIMARY KEY (id) - ) - ` - fmt.Println("create table aa_user:") - _, err = db.Exec(s) - if err != nil { - fmt.Println("create table error.", err) - return err - } - - /*_, err = db.Exec("drop sequence id_seq") - if err != nil { - fmt.Println("drop sequence id_seq", err) - } - - fmt.Println("create sequence id_seq") - _, err = db.Exec("create sequence id_seq increment by 1 start with 1 maxvalue 9999999999 cycle cache 10") - if err != nil { - fmt.Println("create sequence id_seq error.", err) - return err - } - - s = ` - CREATE TRIGGER id_trigger before insert on aa_user for each row - begin - select id_seq.nextval into :new.id from dual; - end; - ` - _, err = db.Exec(s) - if err != nil { - fmt.Println("create trigger error.", err) - return err - }*/ - - _, err = db.Exec("drop table user_detail") - if err != nil { - fmt.Println("drop table user_detail", err) - } - - s = ` - CREATE TABLE user_detail ( - id int not null, - site VARCHAR(255), - PRIMARY KEY (id) - ) - ` - fmt.Println("create table user_detail:") - _, err = db.Exec(s) - if err != nil { - fmt.Println("create table user_detail error.", err) - return err - } - fmt.Println("create table success.") - return nil -} - -// 数据写入 -func insert(id int) { - fmt.Println("insert:") - r, err := db.Insert("aa_user", gdb.Map{ - "id": id, - "name": "john", - "age": id, - }) - fmt.Println(r.LastInsertId()) - fmt.Println(r.RowsAffected()) - if err == nil { - r, err = db.Insert("user_detail", gdb.Map{ - "id": id, - "site": "http://johng.cn", - }) - if err == nil { - fmt.Printf("id: %d\n", id) - } else { - fmt.Println(err) - } - - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 基本sql查询 -func query() { - fmt.Println("query:") - list, err := db.GetAll("select * from aa_user where 1=1") - if err == nil { - fmt.Println(list) - } else { - fmt.Println(err) - } - - list, err = db.Table("aa_user").OrderBy("id").Limit(0, 5).Select() - if err == nil { - fmt.Println(list) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// replace into -func replace() { - fmt.Println("replace:") - r, err := db.Save("aa_user", gdb.Map{ - "id": 1, - "name": "john", - }) - if err == nil { - fmt.Println(r.LastInsertId()) - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 数据保存 -func save() { - fmt.Println("save:") - r, err := db.Save("aa_user", gdb.Map{ - "id": 1, - "name": "john", - }) - if err == nil { - fmt.Println(r.LastInsertId()) - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 批量写入 -func batchInsert() { - fmt.Println("batchInsert:") - _, err := db.BatchInsert("aa_user", gdb.List{ - {"id": 11, "name": "batchInsert_john_1", "age": 11}, - {"id": 12, "name": "batchInsert_john_2", "age": 12}, - {"id": 13, "name": "batchInsert_john_3", "age": 13}, - {"id": 14, "name": "batchInsert_john_4", "age": 14}, - }, 10) - if err != nil { - fmt.Println(err) - } - fmt.Println() -} - -// 数据更新 -func update1() { - fmt.Println("update1:") - r, err := db.Update("aa_user", gdb.Map{"name": "john1", "age": 1}, "id=?", 1) - if err == nil { - fmt.Println(r.LastInsertId()) - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 数据更新 -func update2() { - fmt.Println("update2:") - r, err := db.Update("aa_user", gdb.Map{"name": "john6", "age": 6}, "id=?", 2) - if err == nil { - fmt.Println(r.LastInsertId()) - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 数据更新 -func update3() { - fmt.Println("update3:") - r, err := db.Update("aa_user", "name=?", "id=?", "john2", 3) - if err == nil { - fmt.Println(r.LastInsertId()) - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式查询操作1 -func linkopSelect1() { - fmt.Println("linkopSelect1:") - r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Fields("u.*, ud.site").Where("u.id > ?", 1).Limit(3, 5).Select() - if err == nil { - fmt.Println(r) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式查询操作2 -func linkopSelect2() { - fmt.Println("linkopSelect2:") - r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Fields("u.*,ud.site").Where("u.id=?", 1).One() - if err == nil { - fmt.Println(r) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式查询操作3 -func linkopSelect3() { - fmt.Println("linkopSelect3:") - r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Fields("ud.site").Where("u.id=?", 1).Value() - if err == nil { - fmt.Println(r.String()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式查询数量1 -func linkopCount1() { - fmt.Println("linkopCount1:") - r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Where("name like ?", "john").Count() - if err == nil { - fmt.Println(r) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 错误操作 -func linkopUpdate1() { - fmt.Println("linkopUpdate1:") - r, err := db.Table("henghe_setting").Update() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println("error", err) - } - fmt.Println() -} - -// 通过Map指针方式传参方式 -func linkopUpdate2() { - fmt.Println("linkopUpdate2:") - r, err := db.Table("aa_user").Data(gdb.Map{"name": "john2"}).Where("name=?", "john").Update() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 通过字符串方式传参 -func linkopUpdate3() { - fmt.Println("linkopUpdate3:") - r, err := db.Table("aa_user").Data("name='john3'").Where("name=?", "john2").Update() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// Where条件使用Map -func linkopUpdate4() { - fmt.Println("linkopUpdate4:") - r, err := db.Table("aa_user").Data(gdb.Map{"name": "john11111"}).Where(g.Map{"id": 1}).Update() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式批量写入 -func linkopBatchInsert1() { - fmt.Println("linkopBatchInsert1:") - r, err := db.Table("aa_user").Filter().Data(gdb.List{ - {"id": 21, "name": "linkopBatchInsert1_john_1", "amt": 21.21, "tt": "haha"}, - {"id": 22, "name": "linkopBatchInsert1_john_2", "amt": 22.22, "cc": "hahacc"}, - {"id": 23, "name": "linkopBatchInsert1_john_3", "amt": 23.23, "bb": "hahabb"}, - {"id": 24, "name": "linkopBatchInsert1_john_4", "amt": 24.24, "aa": "hahaaa"}, - }).Insert() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式批量写入,指定每批次写入的条数 -func linkopBatchInsert2() { - fmt.Println("linkopBatchInsert2:") - r, err := db.Table("aa_user").Data(gdb.List{ - {"id": 25, "name": "linkopBatchInsert2john_1"}, - {"id": 26, "name": "linkopBatchInsert2john_2"}, - {"id": 27, "name": "linkopBatchInsert2john_3"}, - {"id": 28, "name": "linkopBatchInsert2john_4"}, - }).Batch(2).Insert() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式批量保存 -func linkopBatchSave() { - fmt.Println("linkopBatchSave:") - r, err := db.Table("aa_user").Data(gdb.List{ - {"id": 1, "name": "john_1"}, - {"id": 2, "name": "john_2"}, - {"id": 3, "name": "john_3"}, - {"id": 4, "name": "john_4"}, - }).Save() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 事务操作示例1 -func transaction1() { - fmt.Println("transaction1:") - if tx, err := db.Begin(); err == nil { - r, err := tx.Insert("aa_user", gdb.Map{ - "id": 30, - "name": "transaction1", - }) - tx.Rollback() - fmt.Println(r, err) - } - fmt.Println() -} - -// 事务操作示例2 -func transaction2() { - fmt.Println("transaction2:") - if tx, err := db.Begin(); err == nil { - r, err := tx.Table("user_detail").Data(gdb.Map{"id": 6, "site": "www.baidu.com哈哈哈*?''\"~!@#$%^&*()"}).Insert() - tx.Commit() - fmt.Println(r, err) - } - fmt.Println() -} - -// 主从io复用测试,在mysql中使用 show full processlist 查看链接信息 -func keepPing() { - fmt.Println("keepPing:") - for i := 0; i < 30; i++ { - fmt.Println("ping...", i) - err := db.PingMaster() - if err != nil { - fmt.Println(err) - return - } - err = db.PingSlave() - if err != nil { - fmt.Println(err) - return - } - time.Sleep(1 * time.Second) - } -} - -// like语句查询 -func likeQuery() { - fmt.Println("likeQuery:") - if r, err := db.Table("aa_user").Where("name like ?", "%john%").Select(); err == nil { - fmt.Println(r) - } else { - fmt.Println(err) - } -} - -// mapToStruct -func mapToStruct() { - type User struct { - Id int - Name string - Age int - Addr string - } - fmt.Println("mapToStruct:") - if r, err := db.Table("aa_user").Where("id=?", 1).One(); err == nil { - u := User{} - if err := r.ToStruct(&u); err == nil { - fmt.Println(r) - fmt.Println(u) - } else { - fmt.Println(err) - } - } else { - fmt.Println(err) - } -} - -func main() { - - db.PingMaster() - db.SetDebug(true) - /*err := create() - if err != nil { - return - }*/ - - //test1 - /*for i := 1; i < 5; i++ { - insert(i) - }*/ - //insert(2) - //query() - - //batchInsert() - //query() - - //replace() - //save() - - /*update1() - update2() - update3() - */ - - /*linkopSelect1() - linkopSelect2() - linkopSelect3() - linkopCount1() - */ - - /*linkopUpdate1() - linkopUpdate2() - linkopUpdate3() - linkopUpdate4() - */ - - linkopBatchInsert1() - query() - //linkopBatchInsert2() - - //transaction1() - //transaction2() - // - //keepPing() - //likeQuery() - //mapToStruct() - //getQueriedSqls() -} diff --git a/.example/database/gdb/mysql/config.toml b/.example/database/gdb/mysql/config.toml deleted file mode 100644 index 0ea384859..000000000 --- a/.example/database/gdb/mysql/config.toml +++ /dev/null @@ -1,26 +0,0 @@ - -# MySQL. -[database] - [database.logger] - Level = "all" - Stdout = true - CtxKeys = ["RequestId"] - [database.default] - link = "mysql:root:12345678@tcp(127.0.0.1:3306)/test" - debug = true - -# Redis. -[redis] - default = "127.0.0.1:6379,0" - cache = "127.0.0.1:6379,1" - -#[database] -# [[database.default]] -# type = "mysql" -# link = "root:12345678@tcp(127.0.0.1:3306)/test?parseTime=true&loc=Local" -# - - - - - diff --git a/.example/database/gdb/mysql/config/gdb.go b/.example/database/gdb/mysql/config/gdb.go deleted file mode 100644 index 3dcb15ddd..000000000 --- a/.example/database/gdb/mysql/config/gdb.go +++ /dev/null @@ -1,41 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/database/gdb" - "github.com/gogf/gf/v2/os/gctx" - "sync" - "time" -) - -var db gdb.DB - -func init() { - gdb.AddDefaultConfigNode(gdb.ConfigNode{ - Host: "127.0.0.1", - Port: "3306", - User: "root", - Pass: "12345678", - Name: "test", - Type: "mysql", - Role: "master", - Charset: "utf8", - MaxOpenConnCount: 100, - }) - db, _ = gdb.New() -} - -func main() { - 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.Ctx(ctx).Model("user").Where("id=1").All() - }() - } - wg.Wait() -} diff --git a/.example/database/gdb/mysql/config2.toml b/.example/database/gdb/mysql/config2.toml deleted file mode 100644 index 8722ede8c..000000000 --- a/.example/database/gdb/mysql/config2.toml +++ /dev/null @@ -1,4 +0,0 @@ - -# MySQL数据库配置 -[database] - link = "mysql:root:8692651@tcp(192.168.1.11:3306)/test" diff --git a/.example/database/gdb/mysql/config3.toml b/.example/database/gdb/mysql/config3.toml deleted file mode 100644 index ce3512864..000000000 --- a/.example/database/gdb/mysql/config3.toml +++ /dev/null @@ -1,7 +0,0 @@ - -# MySQL数据库配置 -[database] - [database.default] - link = "mysql:root:8692651@tcp(192.168.1.11:3306)/test" - [database.user] - link = "mysql:root:8692651@tcp(192.168.1.11:3306)/test" \ No newline at end of file diff --git a/.example/database/gdb/mysql/gdb_all.go b/.example/database/gdb/mysql/gdb_all.go deleted file mode 100644 index 38c5e3409..000000000 --- a/.example/database/gdb/mysql/gdb_all.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gctx" -) - -func main() { - var ( - db = g.DB() - ctx = gctx.New() - ) - // 开启调试模式,以便于记录所有执行的SQL - db.SetDebug(true) - - 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) - } -} diff --git a/.example/database/gdb/mysql/gdb_args_slice.go b/.example/database/gdb/mysql/gdb_args_slice.go deleted file mode 100644 index 88496f345..000000000 --- a/.example/database/gdb/mysql/gdb_args_slice.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gctx" -) - -func main() { - var ( - db = g.DB() - ctx = gctx.New() - ) - - db.Ctx(ctx).Model("user"). - Where("nickname like ? and passport like ?", g.Slice{"T3", "t3"}). - OrderAsc("id").All() - - conditions := g.Map{ - "nickname like ?": "%T%", - "id between ? and ?": g.Slice{1, 3}, - "id >= ?": 1, - "create_time > ?": 0, - "id in(?)": g.Slice{1, 2, 3}, - } - db.Ctx(ctx).Model("user").Where(conditions).OrderAsc("id").All() - - var params []interface{} - 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 deleted file mode 100644 index cdc2e7b36..000000000 --- a/.example/database/gdb/mysql/gdb_batch_insert.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gctx" -) - -func main() { - var ( - db = g.DB() - ctx = gctx.New() - ) - db.SetDebug(true) - list := make(g.List, 0) - for i := 0; i < 100; i++ { - list = append(list, g.Map{ - "name": fmt.Sprintf(`name_%d`, i), - }) - } - r, e := db.Ctx(ctx).Model("user").Data(list).Batch(2).Insert() - if e != nil { - panic(e) - } - if r != nil { - fmt.Println(r.LastInsertId()) - } -} diff --git a/.example/database/gdb/mysql/gdb_binary.go b/.example/database/gdb/mysql/gdb_binary.go deleted file mode 100644 index e0f0b4f6b..000000000 --- a/.example/database/gdb/mysql/gdb_binary.go +++ /dev/null @@ -1,55 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/os/gctx" - - "github.com/gogf/gf/v2/crypto/gaes" - "github.com/gogf/gf/v2/database/gdb" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - gdb.AddDefaultConfigNode(gdb.ConfigNode{ - Host: "127.0.0.1", - Port: "3306", - User: "root", - Pass: "123456", - Name: "test", - Type: "mysql", - Role: "master", - Charset: "utf8", - }) - var ( - ctx = gctx.New() - ) - db, err := gdb.New() - if err != nil { - panic(err) - } - - key := "0123456789123456" - - name := "john" - encryptedName, err := gaes.Encrypt([]byte(name), []byte(key)) - if err != nil { - fmt.Println(err) - } - - // 写入 - r, err := db.Ctx(ctx).Model("user").Data(g.Map{ - "uid": 1, - "name": encryptedName, - }).Save() - if err != nil { - fmt.Println(err) - } - fmt.Println(r.RowsAffected()) - - // 查询 - one, err := db.Ctx(ctx).Model("user").Where("name=?", encryptedName).One() - if err != nil { - fmt.Println(err) - } - fmt.Println(one.Map()) -} diff --git a/.example/database/gdb/mysql/gdb_bit.go b/.example/database/gdb/mysql/gdb_bit.go deleted file mode 100644 index f08133af1..000000000 --- a/.example/database/gdb/mysql/gdb_bit.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/os/gctx" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - var ( - db = g.DB() - ctx = gctx.New() - ) - db.SetDebug(true) - - r, e := db.Ctx(ctx).Model("test").All() - if e != nil { - panic(e) - } - if r != nil { - fmt.Println(r.List()) - } -} diff --git a/.example/database/gdb/mysql/gdb_cache.go b/.example/database/gdb/mysql/gdb_cache.go deleted file mode 100644 index 35583865b..000000000 --- a/.example/database/gdb/mysql/gdb_cache.go +++ /dev/null @@ -1,44 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/database/gdb" - "github.com/gogf/gf/v2/os/gctx" - "github.com/gogf/gf/v2/util/gutil" - "time" -) - -func main() { - gdb.AddDefaultConfigNode(gdb.ConfigNode{ - Host: "127.0.0.1", - Port: "3306", - User: "root", - Pass: "12345678", - Name: "test", - Type: "mysql", - Role: "master", - Charset: "utf8", - }) - var ( - ctx = gctx.New() - ) - db, err := gdb.New() - if err != nil { - panic(err) - } - //db.GetCache().SetAdapter(adapter.NewRedis(g.Redis())) - // 开启调试模式,以便于记录所有执行的SQL - db.SetDebug(true) - - // 执行2次查询并将查询结果缓存3秒,并可执行缓存名称(可选) - for i := 0; i < 3; i++ { - r, _ := db.Ctx(ctx).Model("user").Cache(3000*time.Second).Where("id=?", 1).One() - gutil.Dump(r.Map()) - } - - // 执行更新操作,并清理指定名称的查询缓存 - //db.Table("user").Cache(-1, "vip-user").Data(gdb.Map{"name": "smith"}).Where("id=?", 1).Update() - - // 再次执行查询,启用查询缓存特性 - //r, _ := db.Table("user").Cache(300000*time.Second, "vip-user").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 deleted file mode 100644 index b8af08994..000000000 --- a/.example/database/gdb/mysql/gdb_complecated.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - // error! - r, err := g.DB().Model("user").Where(g.Map{ - "or": g.Map{ - "nickname": "jim", - "create_time > ": "2019-10-01", - }, - "and": g.Map{ - "nickname": "tom", - "create_time > ": "2019-10-01", - }, - }).All() - if err != nil { - panic(err) - } - g.Dump(r) - -} diff --git a/.example/database/gdb/mysql/gdb_config.go b/.example/database/gdb/mysql/gdb_config.go deleted file mode 100644 index 9e0efa73d..000000000 --- a/.example/database/gdb/mysql/gdb_config.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - 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) - } -} diff --git a/.example/database/gdb/mysql/gdb_config2.go b/.example/database/gdb/mysql/gdb_config2.go deleted file mode 100644 index 15120d2d0..000000000 --- a/.example/database/gdb/mysql/gdb_config2.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - g.Config().SetFileName("config2.toml") - 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) - } -} diff --git a/.example/database/gdb/mysql/gdb_config3.go b/.example/database/gdb/mysql/gdb_config3.go deleted file mode 100644 index 960c34a24..000000000 --- a/.example/database/gdb/mysql/gdb_config3.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - g.Config().SetFileName("config3.toml") - 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").Model("user").Where("uid=?", 1).One(); err == nil { - fmt.Println(r["uid"].Int()) - fmt.Println(r["name"].String()) - } else { - fmt.Println(err) - } -} diff --git a/.example/database/gdb/mysql/gdb_ctx.go b/.example/database/gdb/mysql/gdb_ctx.go deleted file mode 100644 index a27edc2f9..000000000 --- a/.example/database/gdb/mysql/gdb_ctx.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - 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 deleted file mode 100644 index 3d8796f9a..000000000 --- a/.example/database/gdb/mysql/gdb_ctx_model.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - 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 deleted file mode 100644 index 317316ec3..000000000 --- a/.example/database/gdb/mysql/gdb_datetime.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/os/gctx" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - var ( - db = g.DB() - ctx = gctx.New() - ) - db.SetDebug(true) - - r, err := db.Ctx(ctx).Model("user").Data(g.Map{ - "name": "john", - "create_time": gtime.Now().String(), - }).Insert() - if err == nil { - fmt.Println(r.LastInsertId()) - } else { - panic(err) - } -} diff --git a/.example/database/gdb/mysql/gdb_debug1.go b/.example/database/gdb/mysql/gdb_debug1.go deleted file mode 100644 index 8eaa2e49d..000000000 --- a/.example/database/gdb/mysql/gdb_debug1.go +++ /dev/null @@ -1,41 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/database/gdb" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gctx" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - gdb.AddDefaultConfigNode(gdb.ConfigNode{ - Host: "127.0.0.1", - Port: "3306", - User: "root", - Pass: "12345678", - Name: "test", - Type: "mysql", - Role: "master", - Charset: "utf8", - }) - var ( - ctx = gctx.New() - ) - db, err := gdb.New() - if err != nil { - panic(err) - } - //db.SetDebug(false) - - glog.SetPath("/tmp") - - // 执行3条SQL查询 - for i := 1; i <= 3; i++ { - db.Ctx(ctx).Model("user").Where("uid=?", i).One() - } - // 构造一条错误查询 - db.Model("user").Where("no_such_field=?", "just_test").One() - - 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 deleted file mode 100644 index 0ab81ac21..000000000 --- a/.example/database/gdb/mysql/gdb_debug2.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gctx" -) - -func main() { - var ( - db = g.DB() - ctx = gctx.New() - ) - - // 执行3条SQL查询 - for i := 1; i <= 3; i++ { - db.Ctx(ctx).Model("user").Where("id=?", i).One() - } - // 构造一条错误查询 - db.Ctx(ctx).Model("user").Where("no_such_field=?", "just_test").One() - - db.Ctx(ctx).Model("user").Data(g.Map{"name": "smith"}).Where("uid=?", 1).Save() -} diff --git a/.example/database/gdb/mysql/gdb_distinct.go b/.example/database/gdb/mysql/gdb_distinct.go deleted file mode 100644 index c043102e9..000000000 --- a/.example/database/gdb/mysql/gdb_distinct.go +++ /dev/null @@ -1,9 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - g.DB().Model("user").Distinct().CountColumn("uid,name") -} diff --git a/.example/database/gdb/mysql/gdb_insert.go b/.example/database/gdb/mysql/gdb_insert.go deleted file mode 100644 index a8a3f1bbd..000000000 --- a/.example/database/gdb/mysql/gdb_insert.go +++ /dev/null @@ -1,30 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/database/gdb" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - //db := g.DB() - - gdb.AddDefaultConfigNode(gdb.ConfigNode{ - Link: "root:12345678@tcp(127.0.0.1:3306)/test?parseTime=true&loc=Local", - Type: "mysql", - Charset: "utf8", - }) - db, _ := gdb.New() - - db.SetDebug(true) - - r, e := db.Model("user").Data(g.Map{ - "create_at": "now()", - }).Unscoped().Insert() - if e != nil { - panic(e) - } - if r != nil { - fmt.Println(r.LastInsertId()) - } -} diff --git a/.example/database/gdb/mysql/gdb_issue_278.go b/.example/database/gdb/mysql/gdb_issue_278.go deleted file mode 100644 index 4bcb82ffa..000000000 --- a/.example/database/gdb/mysql/gdb_issue_278.go +++ /dev/null @@ -1,50 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -var ( - tableName = "orders" - dao = g.DB().Model(tableName).Safe() -) - -type OrderServiceEntity struct { - GoodsPrice float64 `json:"goods_price" gvalid:"required"` - PayTo int8 `json:"payTo" gvalid:"required"` - PayStatus int8 `json:"payStatus" ` - CreateTime string `json:"createTime" ` - AppId string `json:"appId" gvalid:"required"` - PayUser string `json:"pay_user" gvalid:"required"` - QrUrl string `json:"qr_url" ` -} - -type Create struct { - Id int64 `json:"id" gconv:"id"` - GoodsPrice float64 `json:"goodsPrice" gconv:"goods_price"` - PayTo int8 `json:"payTo" gconv:"pay_to"` - PayStatus int8 `json:"payStatus" gconv:"pay_status"` - CreateTime string `json:"createTime" gconv:"create_time"` - UserId int `json:"user_id" ` - PayUser string `json:"pay_user" ` - QrUrl string `json:"qr_url" ` -} - -func main() { - g.DB().SetDebug(true) - userInfo := Create{ - Id: 3, - } - orderService := OrderServiceEntity{ - GoodsPrice: 0.1, - PayTo: 1, - } - size, err := dao.Where("user_id", userInfo.Id). - And("goods_price", float64(100.10)). - And("pay_status", 0). - And("pay_to", orderService.PayTo).Count() - fmt.Println(err) - fmt.Println(size) -} diff --git a/.example/database/gdb/mysql/gdb_json_xml.go b/.example/database/gdb/mysql/gdb_json_xml.go deleted file mode 100644 index ec986e321..000000000 --- a/.example/database/gdb/mysql/gdb_json_xml.go +++ /dev/null @@ -1,41 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/encoding/gjson" - "github.com/gogf/gf/v2/os/gctx" - - "github.com/gogf/gf/v2/database/gdb" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - gdb.AddDefaultConfigNode(gdb.ConfigNode{ - Host: "127.0.0.1", - Port: "3306", - User: "root", - Pass: "12345678", - Name: "test", - Type: "mysql", - Role: "master", - Charset: "utf8", - }) - 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.Json()) - fmt.Println(one.Xml()) - - // 自定义方法方法转换为json/xml - jsonContent, _ := gjson.New(one.Map()).ToJson() - fmt.Println(string(jsonContent)) - xmlContent, _ := gjson.New(one.Map()).ToJson() - fmt.Println(string(xmlContent)) -} diff --git a/.example/database/gdb/mysql/gdb_pool.go b/.example/database/gdb/mysql/gdb_pool.go deleted file mode 100644 index 1ef261186..000000000 --- a/.example/database/gdb/mysql/gdb_pool.go +++ /dev/null @@ -1,26 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/os/gctx" - "time" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - var ( - db = g.DB() - ctx = gctx.New() - ) - - // 开启调试模式,以便于记录所有执行的SQL - db.SetDebug(true) - - for { - for i := 0; i < 10; i++ { - 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 deleted file mode 100644 index 4ae644c99..000000000 --- a/.example/database/gdb/mysql/gdb_reconnect.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gctx" - "time" -) - -func main() { - var ( - db = g.DB() - ctx = gctx.New() - ) - db.SetDebug(true) - for { - 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 deleted file mode 100644 index 5c1f421c8..000000000 --- a/.example/database/gdb/mysql/gdb_struct.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - db := g.DB() - // 开启调试模式,以便于记录所有执行的SQL - db.SetDebug(true) - - type User struct { - Uid int - Name string - } - user := (*User)(nil) - fmt.Println(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 deleted file mode 100644 index f179183c5..000000000 --- a/.example/database/gdb/mysql/gdb_tables.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gctx" -) - -func main() { - var ( - db = g.DB() - ctx = gctx.New() - ) - db.SetDebug(true) - - tables, err := db.Tables(ctx) - if err != nil { - panic(err) - } - if tables != nil { - g.Dump(tables) - } -} diff --git a/.example/database/gdb/mysql/gdb_tables_fields.go b/.example/database/gdb/mysql/gdb_tables_fields.go deleted file mode 100644 index 96dff35ba..000000000 --- a/.example/database/gdb/mysql/gdb_tables_fields.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gctx" -) - -func main() { - var ( - db = g.DB() - ctx = gctx.New() - ) - db.SetDebug(true) - - tables, e := db.Tables(ctx) - if e != nil { - panic(e) - } - if tables != nil { - g.Dump(tables) - for _, table := range tables { - fields, err := db.TableFields(ctx, table) - if err != nil { - panic(err) - } - g.Dump(fields) - } - } -} diff --git a/.example/database/gdb/mysql/gdb_transaction.go b/.example/database/gdb/mysql/gdb_transaction.go deleted file mode 100644 index a181829f4..000000000 --- a/.example/database/gdb/mysql/gdb_transaction.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - var ( - db = g.DB() - table = "user" - ) - tx, err := db.Begin() - if err != nil { - panic(err) - } - if err = tx.Begin(); err != nil { - panic(err) - } - _, err = tx.Model(table).Data(g.Map{"id": 1, "name": "john"}).Insert() - if err = tx.Rollback(); err != nil { - panic(err) - } - _, err = tx.Model(table).Data(g.Map{"id": 2, "name": "smith"}).Insert() - if err = tx.Commit(); err != nil { - panic(err) - } -} diff --git a/.example/database/gdb/mysql/gdb_transaction_closure.go b/.example/database/gdb/mysql/gdb_transaction_closure.go deleted file mode 100644 index 9c39a7db0..000000000 --- a/.example/database/gdb/mysql/gdb_transaction_closure.go +++ /dev/null @@ -1,37 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/database/gdb" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gctx" -) - -func main() { - var ( - err error - db = g.DB() - ctx = gctx.New() - table = "user" - ) - if err = db.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error { - // Nested transaction 1. - 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(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") - }); err != nil { - return err - } - return nil - }); err != nil { - panic(err) - } -} diff --git a/.example/database/gdb/mysql/gdb_transaction_savepoint.go b/.example/database/gdb/mysql/gdb_transaction_savepoint.go deleted file mode 100644 index 13eba5d0b..000000000 --- a/.example/database/gdb/mysql/gdb_transaction_savepoint.go +++ /dev/null @@ -1,40 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - var ( - err error - db = g.DB() - table = "user" - ) - tx, err := db.Begin() - if err != nil { - panic(err) - } - defer func() { - if err := recover(); err != nil { - _ = tx.Rollback() - } - }() - if _, err = tx.Model(table).Data(g.Map{"id": 1, "name": "john"}).Insert(); err != nil { - panic(err) - } - if err = tx.SavePoint("MyPoint"); err != nil { - panic(err) - } - if _, err = tx.Model(table).Data(g.Map{"id": 2, "name": "smith"}).Insert(); err != nil { - panic(err) - } - if _, err = tx.Model(table).Data(g.Map{"id": 3, "name": "green"}).Insert(); err != nil { - panic(err) - } - if err = tx.RollbackTo("MyPoint"); err != nil { - panic(err) - } - if err = tx.Commit(); err != nil { - panic(err) - } -} diff --git a/.example/database/gdb/mysql/gdb_update_field.go b/.example/database/gdb/mysql/gdb_update_field.go deleted file mode 100644 index e653469f0..000000000 --- a/.example/database/gdb/mysql/gdb_update_field.go +++ /dev/null @@ -1,34 +0,0 @@ -package main - -import ( - "database/sql" - - "github.com/gogf/gf/v2/os/gfile" - - "github.com/gogf/gf/v2/encoding/gjson" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - db := g.DB() - table := "medicine_clinics_upload_yinchuan" - list, err := db.Model(table).All() - if err != nil && err != sql.ErrNoRows { - panic(err) - } - content := "" - for _, item := range list { - if j, err := gjson.DecodeToJson(item["upload_data"].String()); err != nil { - panic(err) - } else { - s, _ := j.ToJsonIndentString() - content += item["id"].String() + "\t" + item["medicine_clinic_id"].String() + "\t" - content += s - content += "\n\n" - //if _, err := db.Table(table).Data("data_decode", s).Where("id", item["id"].Int()).Update(); err != nil { - // panic(err) - //} - } - } - gfile.PutContents("/Users/john/Temp/medicine_clinics_upload_yinchuan.txt", content) -} diff --git a/.example/database/gdb/mysql/gdb_update_union.go b/.example/database/gdb/mysql/gdb_update_union.go deleted file mode 100644 index edacbdbe7..000000000 --- a/.example/database/gdb/mysql/gdb_update_union.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - db := g.DB() - db.SetDebug(true) - 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) - } - fmt.Println(result.RowsAffected()) -} diff --git a/.example/database/gdb/mysql/gdb_value.go b/.example/database/gdb/mysql/gdb_value.go deleted file mode 100644 index aace6c5b2..000000000 --- a/.example/database/gdb/mysql/gdb_value.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - one, err := g.Model("carlist c"). - LeftJoin("cardetail d", "c.postid=d.carid"). - Where("c.postid", "142039140032006"). - Fields("c.*,d.*").One() - fmt.Println(err) - g.Dump(one) -} diff --git a/.example/database/gdb/mysql/gdb_with_insert.go b/.example/database/gdb/mysql/gdb_with_insert.go deleted file mode 100644 index 79e8e3d86..000000000 --- a/.example/database/gdb/mysql/gdb_with_insert.go +++ /dev/null @@ -1,69 +0,0 @@ -package main - -import ( - "context" - "fmt" - "github.com/gogf/gf/v2/database/gdb" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gctx" - "github.com/gogf/gf/v2/util/gmeta" -) - -func main() { - type UserDetail struct { - gmeta.Meta `orm:"table:user_detail"` - Uid int `json:"uid"` - Address string `json:"address"` - } - - type UserScore struct { - gmeta.Meta `orm:"table:user_score"` - Id int `json:"id"` - Uid int `json:"uid"` - Score int `json:"score"` - } - - type User struct { - gmeta.Meta `orm:"table:user"` - Id int `json:"id"` - Name string `json:"name"` - UserDetail *UserDetail `orm:"with:uid=id"` - UserScores []*UserScore `orm:"with:uid=id"` - } - - db := g.DB() - 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.Ctx(ctx).Model(user).Data(user).OmitEmpty().InsertAndGetId() - if err != nil { - return err - } - // Detail. - userDetail := UserDetail{ - Uid: int(lastInsertId), - Address: fmt.Sprintf(`address_%d`, lastInsertId), - } - _, err = db.Ctx(ctx).Model(userDetail).Data(userDetail).OmitEmpty().Insert() - if err != nil { - return err - } - // Scores. - for j := 1; j <= 5; j++ { - userScore := UserScore{ - Uid: int(lastInsertId), - Score: j, - } - _, err = db.Ctx(ctx).Model(userScore).Data(userScore).OmitEmpty().Insert() - if err != nil { - return err - } - } - } - return nil - }) - fmt.Println(err) -} diff --git a/.example/database/gdb/mysql/gdb_with_slect.go b/.example/database/gdb/mysql/gdb_with_slect.go deleted file mode 100644 index 327062e88..000000000 --- a/.example/database/gdb/mysql/gdb_with_slect.go +++ /dev/null @@ -1,37 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gmeta" -) - -func main() { - type UserDetail struct { - gmeta.Meta `orm:"table:user_detail"` - Uid int `json:"uid"` - Address string `json:"address"` - } - - type UserScore struct { - gmeta.Meta `orm:"table:user_score"` - Id int `json:"id"` - Uid int `json:"uid"` - Score int `json:"score"` - } - - type User struct { - gmeta.Meta `orm:"table:user"` - Id int `json:"id"` - Name string `json:"name"` - UserDetail *UserDetail `orm:"with:uid=id"` - UserScores []*UserScore `orm:"with:uid=id"` - } - - db := g.DB() - var user *User - err := db.Model(user).WithAll().Where("id", 3).Scan(&user) - if err != nil { - panic(err) - } - g.Dump(user) -} diff --git a/.example/database/gdb/mysql/issue364.go b/.example/database/gdb/mysql/issue364.go deleted file mode 100644 index 2f84b1aaf..000000000 --- a/.example/database/gdb/mysql/issue364.go +++ /dev/null @@ -1,34 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "time" -) - -func test1() { - db := g.DB() - db.SetDebug(true) - time.Sleep(1 * time.Minute) - r, e := db.Model("test").Where("id", 10000).Count() - if e != nil { - panic(e) - } - g.Dump(r) -} - -func test2() { - db := g.DB() - db.SetDebug(true) - dao := db.Model("test").Safe() - time.Sleep(1 * time.Minute) - r, e := dao.Where("id", 10000).Count() - if e != nil { - panic(e) - } - g.Dump(r) -} - -func main() { - test1() - test2() -} diff --git a/.example/database/gdb/oracle/gdb.go b/.example/database/gdb/oracle/gdb.go deleted file mode 100644 index c2f35661d..000000000 --- a/.example/database/gdb/oracle/gdb.go +++ /dev/null @@ -1,565 +0,0 @@ -package main - -import ( - "fmt" - "time" - - //_ "github.com/mattn/go-oci8" - "github.com/gogf/gf/v2/database/gdb" - "github.com/gogf/gf/v2/frame/g" -) - -// 本文件用于gf框架的mysql数据库操作示例,不作为单元测试使用 - -var db gdb.DB - -// 初始化配置及创建数据库 -func init() { - gdb.AddDefaultConfigNode(gdb.ConfigNode{ - Host: "192.168.146.0", - Port: "1521", - User: "test", - Pass: "test", - Name: "orcl", - Type: "oracle", - Role: "master", - }) - db, _ = gdb.New() - - //gins.Config().SetPath("/home/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/.example/frame") - //db = g.Database() - - //gdb.SetConfig(gdb.ConfigNode { - // Host : "127.0.0.1", - // Port : 3306, - // User : "root", - // Pass : "123456", - // Name : "test", - // Type : "mysql", - //}) - //db, _ = gdb.Instance() - - //gdb.SetConfig(gdb.Config { - // "default" : gdb.ConfigGroup { - // gdb.ConfigNode { - // Host : "127.0.0.1", - // Port : "3306", - // User : "root", - // Pass : "123456", - // Name : "test", - // Type : "mysql", - // Role : "master", - // Weight : 100, - // }, - // gdb.ConfigNode { - // Host : "127.0.0.2", - // Port : "3306", - // User : "root", - // Pass : "123456", - // Name : "test", - // Type : "mysql", - // Role : "master", - // Weight : 100, - // }, - // gdb.ConfigNode { - // Host : "127.0.0.3", - // Port : "3306", - // User : "root", - // Pass : "123456", - // Name : "test", - // Type : "mysql", - // Role : "master", - // Weight : 100, - // }, - // gdb.ConfigNode { - // Host : "127.0.0.4", - // Port : "3306", - // User : "root", - // Pass : "123456", - // Name : "test", - // Type : "mysql", - // Role : "master", - // Weight : 100, - // }, - // }, - //}) - //db, _ = gdb.Instance() -} - -// 创建测试数据库 -func create() error { - fmt.Println("drop table aa_user:") - _, err := db.Exec("drop table aa_user") - if err != nil { - fmt.Println("drop table aa_user error.", err) - } - - s := ` - CREATE TABLE aa_user ( - id number(10) not null, - name VARCHAR2(45), - age number(8), - addr varchar2(60), - amt number(12,2), - PRIMARY KEY (id) - ) - ` - fmt.Println("create table aa_user:") - _, err = db.Exec(s) - if err != nil { - fmt.Println("create table error.", err) - return err - } - - _, err = db.Exec("drop sequence id_seq") - if err != nil { - fmt.Println("drop sequence id_seq", err) - } - - /*fmt.Println("create sequence id_seq") - _, err = db.Exec("create sequence id_seq increment by 1 start with 1 maxvalue 9999999999 cycle cache 10") - if err != nil { - fmt.Println("create sequence id_seq error.", err) - return err - } - - s = ` - CREATE TRIGGER id_trigger before insert on aa_user for each row - begin - select id_seq.nextval into :new.id from dual; - end; - ` - _, err = db.Exec(s) - if err != nil { - fmt.Println("create trigger error.", err) - return err - }*/ - - _, err = db.Exec("drop table user_detail") - if err != nil { - fmt.Println("drop table user_detail", err) - } - - s = ` - CREATE TABLE user_detail ( - id number(10) not null, - site VARCHAR2(255), - PRIMARY KEY (id) - ) - ` - fmt.Println("create table user_detail:") - _, err = db.Exec(s) - if err != nil { - fmt.Println("create table user_detail error.", err) - return err - } - fmt.Println("create table success.") - return nil -} - -// 数据写入 -func insert(id int) { - fmt.Println("insert:") - - r, err := db.Insert("aa_user", gdb.Map{ - "id": id, - "name": "john", - "age": id, - }) - fmt.Println(r.LastInsertId()) - fmt.Println(r.RowsAffected()) - if err == nil { - r, err = db.Insert("user_detail", gdb.Map{ - "id": id, - "site": "http://johng.cn", - }) - if err == nil { - fmt.Printf("id: %d\n", id) - } else { - fmt.Println(err) - } - - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 基本sql查询 -func query() { - fmt.Println("query:") - list, err := db.GetAll("select * from aa_user") - if err == nil { - fmt.Println(list) - } else { - fmt.Println(err) - } - - list, err = db.Table("aa_user").OrderBy("id").Limit(0, 2).Select() - if err == nil { - fmt.Println(list) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// replace into -func replace() { - fmt.Println("replace:") - r, err := db.Save("aa_user", gdb.Map{ - "id": 1, - "name": "john", - }) - if err == nil { - fmt.Println(r.LastInsertId()) - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 数据保存 -func save() { - fmt.Println("save:") - r, err := db.Save("aa_user", gdb.Map{ - "id": 1, - "name": "john", - }) - if err == nil { - fmt.Println(r.LastInsertId()) - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 批量写入 -func batchInsert() { - fmt.Println("batchInsert:") - _, err := db.BatchInsert("aa_user", gdb.List{ - {"id": 11, "name": "batchInsert_john_1", "age": 11, "amt": 11.11}, - {"id": 12, "name": "batchInsert_john_2", "age": 12, "amt": 12.12}, - {"id": 13, "name": "batchInsert_john_3", "age": 13, "amt": 13.13}, - {"id": 14, "name": "batchInsert_john_4", "age": 14, "amt": 14.14}, - }, 10) - if err != nil { - fmt.Println(err) - } - fmt.Println() -} - -// 数据更新 -func update1() { - fmt.Println("update1:") - r, err := db.Update("aa_user", gdb.Map{"name": "john1", "age": 1}, "id=?", 1) - if err == nil { - fmt.Println(r.LastInsertId()) - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 数据更新 -func update2() { - fmt.Println("update2:") - r, err := db.Update("aa_user", gdb.Map{"name": "john6", "age": 6}, "id=?", 2) - if err == nil { - fmt.Println(r.LastInsertId()) - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 数据更新 -func update3() { - fmt.Println("update3:") - r, err := db.Update("aa_user", "name=?", "id=?", "john2", 3) - if err == nil { - fmt.Println(r.LastInsertId()) - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式查询操作1 -func linkopSelect1() { - fmt.Println("linkopSelect1:") - r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Fields("u.*, ud.site").Where("u.id > ?", 1).Limit(0, 2).Select() - if err == nil { - fmt.Println(r) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式查询操作2 -func linkopSelect2() { - fmt.Println("linkopSelect2:") - r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Fields("u.*,ud.site").Where("u.id=?", 1).One() - if err == nil { - fmt.Println(r) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式查询操作3 -func linkopSelect3() { - fmt.Println("linkopSelect3:") - r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Fields("ud.site").Where("u.id=?", 1).Value() - if err == nil { - fmt.Println(r.String()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式查询数量1 -func linkopCount1() { - fmt.Println("linkopCount1:") - r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Where("name like ?", "john").Count() - if err == nil { - fmt.Println(r) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 错误操作 -func linkopUpdate1() { - fmt.Println("linkopUpdate1:") - r, err := db.Table("henghe_setting").Update() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println("error", err) - } - fmt.Println() -} - -// 通过Map指针方式传参方式 -func linkopUpdate2() { - fmt.Println("linkopUpdate2:") - r, err := db.Table("aa_user").Data(gdb.Map{"name": "john2"}).Where("name=?", "john").Update() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 通过字符串方式传参 -func linkopUpdate3() { - fmt.Println("linkopUpdate3:") - r, err := db.Table("aa_user").Data("name='john3'").Where("name=?", "john2").Update() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// Where条件使用Map -func linkopUpdate4() { - fmt.Println("linkopUpdate4:") - r, err := db.Table("aa_user").Data(gdb.Map{"name": "john11111"}).Where(g.Map{"id": 1}).Update() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式批量写入 -func linkopBatchInsert1() { - fmt.Println("linkopBatchInsert1:") - r, err := db.Table("aa_user").Filter().Data(gdb.List{ - {"id": 21, "name": "linkopBatchInsert1_john_1", "amt": 21.21, "tt": "haha"}, - {"id": 22, "name": "linkopBatchInsert1_john_2", "amt": 22.22, "cc": "hahacc"}, - {"id": 23, "name": "linkopBatchInsert1_john_3", "amt": 23.23, "bb": "hahabb"}, - {"id": 24, "name": "linkopBatchInsert1_john_4", "amt": 24.24, "aa": "hahaaa"}, - }).Insert() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式批量写入,指定每批次写入的条数 -func linkopBatchInsert2() { - fmt.Println("linkopBatchInsert2:") - r, err := db.Table("aa_user").Data(gdb.List{ - {"id": 25, "name": "linkopBatchInsert2john_1"}, - {"id": 26, "name": "linkopBatchInsert2john_2"}, - {"id": 27, "name": "linkopBatchInsert2john_3"}, - {"id": 28, "name": "linkopBatchInsert2john_4"}, - }).Batch(2).Insert() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式批量保存 -func linkopBatchSave() { - fmt.Println("linkopBatchSave:") - r, err := db.Table("aa_user").Data(gdb.List{ - {"id": 1, "name": "john_1"}, - {"id": 2, "name": "john_2"}, - {"id": 3, "name": "john_3"}, - {"id": 4, "name": "john_4"}, - }).Save() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 事务操作示例1 -func transaction1() { - fmt.Println("transaction1:") - if tx, err := db.Begin(); err == nil { - r, err := tx.Insert("aa_user", gdb.Map{ - "id": 30, - "name": "transaction1", - }) - tx.Rollback() - fmt.Println(r, err) - } - fmt.Println() -} - -// 事务操作示例2 -func transaction2() { - fmt.Println("transaction2:") - if tx, err := db.Begin(); err == nil { - r, err := tx.Table("user_detail").Data(gdb.Map{"id": 5, "site": "www.baidu.com哈哈哈*?~!@#$%^&*()"}).Insert() - tx.Commit() - fmt.Println(r, err) - } - fmt.Println() -} - -// 主从io复用测试,在mysql中使用 show full processlist 查看链接信息 -func keepPing() { - fmt.Println("keepPing:") - for i := 0; i < 30; i++ { - fmt.Println("ping...", i) - err := db.PingMaster() - if err != nil { - fmt.Println(err) - return - } - err = db.PingSlave() - if err != nil { - fmt.Println(err) - return - } - time.Sleep(1 * time.Second) - } -} - -// like语句查询 -func likeQuery() { - fmt.Println("likeQuery:") - if r, err := db.Table("aa_user").Where("name like ?", "%john%").Select(); err == nil { - fmt.Println(r) - } else { - fmt.Println(err) - } -} - -// mapToStruct -func mapToStruct() { - type User struct { - Id int - Name string - Age int - Addr string - } - fmt.Println("mapToStruct:") - if r, err := db.Table("aa_user").Where("id=?", 1).One(); err == nil { - u := User{} - if err := r.ToStruct(&u); err == nil { - fmt.Println(r) - fmt.Println(u) - } else { - fmt.Println(err) - } - } else { - fmt.Println(err) - } -} - -func main() { - - db.PingMaster() - db.SetDebug(true) - /*err := create() - if err != nil { - return - }*/ - - //test1 - /*for i := 1; i < 5; i++ { - insert(i) - } - query() - */ - - //batchInsert() - //query() - - //replace() - //save() - - //update1() - //update2() - //update3() - - /*linkopSelect1() - linkopSelect2() - linkopSelect3() - linkopCount1() - */ - - /*linkopUpdate1() - linkopUpdate2() - linkopUpdate3() - linkopUpdate4() - */ - - linkopBatchInsert1() - query() - //linkopBatchInsert2() - - //transaction1() - //transaction2() - // - //keepPing() - //likeQuery() - //mapToStruct() - //getQueriedSqls() -} diff --git a/.example/database/gdb/sqlite/sqlite.go b/.example/database/gdb/sqlite/sqlite.go deleted file mode 100644 index 4160d5f4d..000000000 --- a/.example/database/gdb/sqlite/sqlite.go +++ /dev/null @@ -1,47 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/database/gdb" - "github.com/gogf/gf/v2/frame/g" - _ "github.com/mattn/go-sqlite3" -) - -func main() { - gdb.SetConfig(gdb.Config{ - "default": gdb.ConfigGroup{ - gdb.ConfigNode{ - Name: "/tmp/my.db", - Type: "sqlite", - }, - }, - }) - db := g.DB() - if db == nil { - panic("db create failed") - } - - // 创建表 - sql := `CREATE TABLE user ( - uid INT PRIMARY KEY NOT NULL, - name VARCHAR(30) NOT NULL - );` - if _, err := db.Exec(sql); err != nil { - fmt.Println(err) - } - - // 写入数据 - result, err := db.Table("user").Data(g.Map{"uid": 1, "name": "john"}).Save() - if err == nil { - fmt.Println(result.RowsAffected()) - } else { - fmt.Println(err) - } - - // 删除表 - sql = `DROP TABLE user;` - if _, err := db.Exec(sql); err != nil { - fmt.Println(err) - } -} diff --git a/.example/database/gredis/config.toml b/.example/database/gredis/config.toml deleted file mode 100644 index 5632e6444..000000000 --- a/.example/database/gredis/config.toml +++ /dev/null @@ -1,4 +0,0 @@ -# Redis数据库配置 -[redis] - default = "127.0.0.1:6379,0" - cache = "127.0.0.1:6379,1" \ No newline at end of file diff --git a/.example/database/gredis/gredis.go b/.example/database/gredis/gredis.go deleted file mode 100644 index 32815d06c..000000000 --- a/.example/database/gredis/gredis.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/database/gredis" - "github.com/gogf/gf/v2/util/gconv" -) - -// 使用原生gredis.New操作redis,但是注意需要自己调用Close方法关闭redis链接池 -func main() { - config := &gredis.Config{ - Host: "127.0.0.1", - Port: 6379, - } - redis := gredis.New(config) - defer redis.Close() - redis.Do("SET", "k", "v") - v, _ := redis.Do("GET", "k") - fmt.Println(gconv.String(v)) -} diff --git a/.example/database/gredis/gredis2.go b/.example/database/gredis/gredis2.go deleted file mode 100644 index e141cb06e..000000000 --- a/.example/database/gredis/gredis2.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -// 使用框架封装的g.Redis()方法获得redis操作对象单例,不需要开发者显示调用Close方法 -func main() { - g.Redis().Do("SET", "k", "v") - v, _ := g.Redis().Do("GET", "k") - fmt.Println(gconv.String(v)) -} diff --git a/.example/database/gredis/gredis_conn_do.go b/.example/database/gredis/gredis_conn_do.go deleted file mode 100644 index 6f3f2c6a2..000000000 --- a/.example/database/gredis/gredis_conn_do.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - conn := g.Redis().Conn() - defer conn.Close() - conn.Do("SET", "k", "v") - v, _ := conn.Do("GET", "k") - fmt.Println(gconv.String(v)) -} diff --git a/.example/database/gredis/gredis_conn_do_var.go b/.example/database/gredis/gredis_conn_do_var.go deleted file mode 100644 index 363d762ed..000000000 --- a/.example/database/gredis/gredis_conn_do_var.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - conn := g.Redis().Conn() - defer conn.Close() - if _, err := conn.Do("SET", "k", "v"); err != nil { - panic(err) - } - v, _ := conn.DoVar("GET", "k") - fmt.Println(v.String()) -} diff --git a/.example/database/gredis/gredis_conn_send.go b/.example/database/gredis/gredis_conn_send.go deleted file mode 100644 index 727e38ffc..000000000 --- a/.example/database/gredis/gredis_conn_send.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - conn := g.Redis().Conn() - defer conn.Close() - conn.Send("SET", "foo", "bar") - conn.Send("GET", "foo") - conn.Flush() - // reply from SET - conn.Receive() - // reply from GET - v, _ := conn.Receive() - fmt.Println(gconv.String(v)) -} diff --git a/.example/database/gredis/gredis_conn_send_var.go b/.example/database/gredis/gredis_conn_send_var.go deleted file mode 100644 index 019582ddd..000000000 --- a/.example/database/gredis/gredis_conn_send_var.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - conn := g.Redis().Conn() - defer conn.Close() - conn.Send("SET", "foo", "bar") - conn.Send("GET", "foo") - conn.Flush() - // reply from SET - conn.Receive() - // reply from GET - v, _ := conn.ReceiveVar() - fmt.Println(v.String()) -} diff --git a/.example/database/gredis/gredis_conn_subscribe.go b/.example/database/gredis/gredis_conn_subscribe.go deleted file mode 100644 index 7baf3a62d..000000000 --- a/.example/database/gredis/gredis_conn_subscribe.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - conn := g.Redis().Conn() - defer conn.Close() - _, err := conn.Do("SUBSCRIBE", "channel") - if err != nil { - panic(err) - } - for { - reply, err := conn.Receive() - if err != nil { - panic(err) - } - fmt.Println(gconv.Strings(reply)) - } -} diff --git a/.example/database/gredis/gredis_conn_subscribe_var.go b/.example/database/gredis/gredis_conn_subscribe_var.go deleted file mode 100644 index d171d2cac..000000000 --- a/.example/database/gredis/gredis_conn_subscribe_var.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - conn := g.Redis().Conn() - defer conn.Close() - _, err := conn.Do("SUBSCRIBE", "channel") - if err != nil { - panic(err) - } - for { - reply, err := conn.ReceiveVar() - if err != nil { - panic(err) - } - fmt.Println(reply.Strings()) - } -} diff --git a/.example/debug/gdebug/gdebug.go b/.example/debug/gdebug/gdebug.go deleted file mode 100644 index 2c67adf32..000000000 --- a/.example/debug/gdebug/gdebug.go +++ /dev/null @@ -1,12 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/debug/gdebug" -) - -func main() { - gdebug.PrintStack() - fmt.Println(gdebug.CallerPackage()) - fmt.Println(gdebug.CallerFunction()) -} diff --git a/.example/debug/gdebug/gdebug_info.go b/.example/debug/gdebug/gdebug_info.go deleted file mode 100644 index a829d8a7f..000000000 --- a/.example/debug/gdebug/gdebug_info.go +++ /dev/null @@ -1,10 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/debug/gdebug" -) - -func main() { - fmt.Println(gdebug.BuildInfo()) -} diff --git a/.example/encoding/gbase64/gbase64.go b/.example/encoding/gbase64/gbase64.go deleted file mode 100644 index e87206a9c..000000000 --- a/.example/encoding/gbase64/gbase64.go +++ /dev/null @@ -1,16 +0,0 @@ -package gbase64 - -import ( - "fmt" - - "github.com/gogf/gf/v2/encoding/gbase64" -) - -func main() { - s := "john" - b := gbase64.Encode(s) - c, e := gbase64.Decode(b) - fmt.Println(b) - fmt.Println(c) - fmt.Println(e) -} diff --git a/.example/encoding/gbinary/binary.go b/.example/encoding/gbinary/binary.go deleted file mode 100644 index 53e1e81de..000000000 --- a/.example/encoding/gbinary/binary.go +++ /dev/null @@ -1,55 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/encoding/gbinary" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - // 使用gbinary.Encoded对基本数据类型进行二进制打包 - fmt.Println(gbinary.Encode(18, 300, 1.01)) - - // 使用gbinary.Decode对整形二进制解包,注意第二个及其后参数为字长确定的整形变量的指针地址,字长确定的类型, - // 例如:int8/16/32/64、uint8/16/32/64、float32/64 - // 这里的1.01默认为float64类型(64位系统下) - buffer := gbinary.Encode(18, 300, 1.01) - var i1 int8 - var i2 int16 - var f3 float64 - if err := gbinary.Decode(buffer, &i1, &i2, &f3); err != nil { - glog.Error(err) - } else { - fmt.Println(i1, i2, f3) - } - - // 编码/解析 int,自动识别变量长度 - fmt.Println(gbinary.DecodeToInt(gbinary.EncodeInt(1))) - fmt.Println(gbinary.DecodeToInt(gbinary.EncodeInt(300))) - fmt.Println(gbinary.DecodeToInt(gbinary.EncodeInt(70000))) - fmt.Println(gbinary.DecodeToInt(gbinary.EncodeInt(2000000000))) - fmt.Println(gbinary.DecodeToInt(gbinary.EncodeInt(500000000000))) - - // 编码/解析 uint,自动识别变量长度 - fmt.Println(gbinary.DecodeToUint(gbinary.EncodeUint(1))) - fmt.Println(gbinary.DecodeToUint(gbinary.EncodeUint(300))) - fmt.Println(gbinary.DecodeToUint(gbinary.EncodeUint(70000))) - fmt.Println(gbinary.DecodeToUint(gbinary.EncodeUint(2000000000))) - fmt.Println(gbinary.DecodeToUint(gbinary.EncodeUint(500000000000))) - - // 编码/解析 int8/16/32/64 - fmt.Println(gbinary.DecodeToInt8(gbinary.EncodeInt8(int8(100)))) - fmt.Println(gbinary.DecodeToInt16(gbinary.EncodeInt16(int16(100)))) - fmt.Println(gbinary.DecodeToInt32(gbinary.EncodeInt32(int32(100)))) - fmt.Println(gbinary.DecodeToInt64(gbinary.EncodeInt64(int64(100)))) - - // 编码/解析 uint8/16/32/64 - fmt.Println(gbinary.DecodeToUint8(gbinary.EncodeUint8(uint8(100)))) - fmt.Println(gbinary.DecodeToUint16(gbinary.EncodeUint16(uint16(100)))) - fmt.Println(gbinary.DecodeToUint32(gbinary.EncodeUint32(uint32(100)))) - fmt.Println(gbinary.DecodeToUint64(gbinary.EncodeUint64(uint64(100)))) - - // 编码/解析 string - fmt.Println(gbinary.DecodeToString(gbinary.EncodeString("I'm string!"))) -} diff --git a/.example/encoding/gbinary/bits1.go b/.example/encoding/gbinary/bits1.go deleted file mode 100644 index 6d2696157..000000000 --- a/.example/encoding/gbinary/bits1.go +++ /dev/null @@ -1,33 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/encoding/gbinary" -) - -func main() { - // 传感器状态,0:已下线, 1:开启, 2:关闭, 3:待机 - count := 100 - status := 1 - - // 网关编码 - bits := make([]gbinary.Bit, 0) - for i := 0; i < count; i++ { - bits = gbinary.EncodeBits(bits, status, 2) - } - buffer := gbinary.EncodeBitsToBytes(bits) - fmt.Println("buffer length:", len(buffer)) - - /* 上报过程忽略,这里只展示编码/解码示例 */ - - // 平台解码 - alivecount := 0 - sensorbits := gbinary.DecodeBytesToBits(buffer) - for i := 0; i < len(sensorbits); i += 2 { - if gbinary.DecodeBits(sensorbits[i:i+2]) == 1 { - alivecount++ - } - } - fmt.Println("alived sensor:", alivecount) -} diff --git a/.example/encoding/gbinary/bits2.go b/.example/encoding/gbinary/bits2.go deleted file mode 100644 index d85d04cb8..000000000 --- a/.example/encoding/gbinary/bits2.go +++ /dev/null @@ -1,33 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/encoding/gbinary" -) - -func main() { - // Meta元数据文件数据结构:[键名哈希64(64bit,8byte) 键名长度(8bit,1byte) 键值长度(24bit,3byte) 数据文件偏移量(40bit,5byte)](变长) - hash := 521369841259754125 - klen := 12 - vlen := 35535 - offset := 80000000 - - // 编码 - bits := make([]gbinary.Bit, 0) - bits = gbinary.EncodeBits(bits, hash, 64) - bits = gbinary.EncodeBits(bits, klen, 8) - bits = gbinary.EncodeBits(bits, vlen, 24) - bits = gbinary.EncodeBits(bits, offset, 40) - buffer := gbinary.EncodeBitsToBytes(bits) - fmt.Println("meta length:", len(buffer)) - - /* 文件存储及数据查询过程忽略,这里只展示元数据编码/解码示例 */ - - // 解码 - metabits := gbinary.DecodeBytesToBits(buffer) - fmt.Println("hash :", gbinary.DecodeBits(metabits[0:64])) - fmt.Println("klen :", gbinary.DecodeBits(metabits[64:72])) - fmt.Println("vlen :", gbinary.DecodeBits(metabits[72:96])) - fmt.Println("offset:", gbinary.DecodeBits(metabits[96:136])) -} diff --git a/.example/encoding/gcfg/config.toml b/.example/encoding/gcfg/config.toml deleted file mode 100644 index d58ffea7c..000000000 --- a/.example/encoding/gcfg/config.toml +++ /dev/null @@ -1,28 +0,0 @@ -# 模板引擎目录 -viewpath = "/home/www/templates/" -# MySQL数据库配置 -[database] - [[database.default]] - host = "127.0.0.1" - port = "3306" - user = "root" - pass = "123456" - name = "test" - type = "mysql" - role = "master" - charset = "utf8" - priority = "1" - [[database.default]] - host = "127.0.0.1" - port = "3306" - user = "root" - pass = "123456" - name = "test" - type = "mysql" - role = "master" - charset = "utf8" - priority = "1" -# Redis数据库配置 -[redis] - disk = "127.0.0.1:6379,0" - cache = "127.0.0.1:6379,1" \ No newline at end of file diff --git a/.example/encoding/gcfg/gcfg1.go b/.example/encoding/gcfg/gcfg1.go deleted file mode 100644 index b59e0af91..000000000 --- a/.example/encoding/gcfg/gcfg1.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - fmt.Println(g.Config().Get("redis")) - - type RedisConfig struct { - Disk string - Cache string - } - - redisCfg := new(RedisConfig) - fmt.Println(g.Config().GetStruct("redis", redisCfg)) - fmt.Println(redisCfg) -} diff --git a/.example/encoding/gcharset/gcharset.go b/.example/encoding/gcharset/gcharset.go deleted file mode 100644 index cf3a8017a..000000000 --- a/.example/encoding/gcharset/gcharset.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/encoding/gcharset" -) - -func main() { - src := "~{;(F#,6@WCN^O`GW!#" - srcCharset := "GB2312" - dstCharset := "UTF-8" - str, err := gcharset.Convert(dstCharset, srcCharset, src) - if err != nil { - panic(err) - } - fmt.Println(str) - // output: - // 花间一壶酒,独酌无相亲。 -} diff --git a/.example/encoding/gcompress/unzip.go b/.example/encoding/gcompress/unzip.go deleted file mode 100644 index 112b1977f..000000000 --- a/.example/encoding/gcompress/unzip.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/encoding/gcompress" -) - -func main() { - err := gcompress.UnZipFile( - `D:\Workspace\Go\GOPATH\src\github.com\gogf\gf\geg\encoding\gcompress\data.zip`, - `D:\Workspace\Go\GOPATH\src\github.com\gogf\gf\geg`, - ) - fmt.Println(err) -} diff --git a/.example/encoding/gcompress/unzip_content.go b/.example/encoding/gcompress/unzip_content.go deleted file mode 100644 index b5d464998..000000000 --- a/.example/encoding/gcompress/unzip_content.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/encoding/gcompress" - "github.com/gogf/gf/v2/os/gfile" -) - -func main() { - err := gcompress.UnZipContent( - gfile.GetBytes(`D:\Workspace\Go\GOPATH\src\github.com\gogf\gf\geg\encoding\gcompress\data.zip`), - `D:\Workspace\Go\GOPATH\src\github.com\gogf\gf\geg`, - ) - fmt.Println(err) -} diff --git a/.example/encoding/gcompress/zip.go b/.example/encoding/gcompress/zip.go deleted file mode 100644 index 6e055200d..000000000 --- a/.example/encoding/gcompress/zip.go +++ /dev/null @@ -1,68 +0,0 @@ -package main - -import ( - "archive/zip" - "fmt" - "github.com/gogf/gf/v2/encoding/gcompress" - "io" - "os" - "path/filepath" - "strings" -) - -// srcFile could be a single file or a directory -func Zip(srcFile string, destZip string) error { - zipfile, err := os.Create(destZip) - if err != nil { - return err - } - defer zipfile.Close() - - archive := zip.NewWriter(zipfile) - defer archive.Close() - - filepath.Walk(srcFile, func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - - header, err := zip.FileInfoHeader(info) - if err != nil { - return err - } - - header.Name = strings.TrimPrefix(path, filepath.Dir(srcFile)+"/") - // header.Name = path - if info.IsDir() { - header.Name += "/" - } else { - header.Method = zip.Deflate - } - - writer, err := archive.CreateHeader(header) - if err != nil { - return err - } - - if !info.IsDir() { - file, err := os.Open(path) - if err != nil { - return err - } - defer file.Close() - _, err = io.Copy(writer, file) - } - return err - }) - - return err -} - -func main() { - src := `/Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/test` - dst := `/Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/test.zip` - //src := `/Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/README.MD` - //dst := `/Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/README.MD.zip` - fmt.Println(gcompress.ZipPath(src, dst)) - //fmt.Println(Zip(src, dst)) -} diff --git a/.example/encoding/ghash/ghash_repeat_check.go b/.example/encoding/ghash/ghash_repeat_check.go deleted file mode 100644 index 8451b1bc6..000000000 --- a/.example/encoding/ghash/ghash_repeat_check.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "fmt" - "strconv" - - "github.com/gogf/gf/v2/encoding/ghash" -) - -func main() { - m := make(map[uint64]bool) - for i := 0; i < 100000000; i++ { - hash := ghash.BKDRHash64([]byte("key_" + strconv.Itoa(i))) - if _, ok := m[hash]; ok { - fmt.Printf("duplicated hash %d\n", hash) - } else { - m[hash] = true - } - } -} diff --git a/.example/encoding/gini/gini.go b/.example/encoding/gini/gini.go deleted file mode 100644 index 9e6c55a58..000000000 --- a/.example/encoding/gini/gini.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/encoding/gini" -) - -func main() { - s := ` -a = b - -` - m, err := gini.Decode([]byte(s)) - fmt.Println(err) - fmt.Println(m) -} diff --git a/.example/encoding/gjson/gjson.go b/.example/encoding/gjson/gjson.go deleted file mode 100644 index 07da40f89..000000000 --- a/.example/encoding/gjson/gjson.go +++ /dev/null @@ -1,155 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/encoding/gjson" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtime" -) - -func getByPattern() { - data := - `{ - "users" : { - "count" : 100, - "list" : [ - {"name" : "小明", "score" : 60}, - {"name" : "John", "score" : 99.5} - ] - } - }` - j, err := gjson.DecodeToJson([]byte(data)) - if err != nil { - glog.Error(err) - } else { - fmt.Println("John Score:", j.GetFloat32("users.list.1.score")) - } -} - -// 当键名存在"."号时,检索优先级:键名->层级,因此不会引起歧义 -func testMultiDots() { - data := - `{ - "users" : { - "count" : 100 - }, - "users.count" : 101 - }` - j, err := gjson.DecodeToJson([]byte(data)) - if err != nil { - glog.Error(err) - } else { - fmt.Println("Users Count:", j.GetInt("users.count")) - } -} - -// 设置数据 -func testSet() { - data := - `{ - "users" : { - "count" : 100 - } - }` - j, err := gjson.DecodeToJson([]byte(data)) - if err != nil { - glog.Error(err) - } else { - j.Set("users.count", 1) - j.Set("users.list", []string{"John", "小明"}) - c, _ := j.ToJson() - fmt.Println(string(c)) - } -} - -// 将Json数据转换为其他数据格式 -func testConvert() { - data := - `{ - "users" : { - "count" : 100, - "list" : ["John", "小明"] - } - }` - j, err := gjson.DecodeToJson([]byte(data)) - if err != nil { - glog.Error(err) - } else { - c, _ := j.ToJson() - fmt.Println("JSON:") - fmt.Println(string(c)) - fmt.Println("======================") - - fmt.Println("XML:") - c, _ = j.ToXmlIndent() - fmt.Println(string(c)) - fmt.Println("======================") - - fmt.Println("YAML:") - c, _ = j.ToYaml() - fmt.Println(string(c)) - fmt.Println("======================") - - fmt.Println("TOML:") - c, _ = j.ToToml() - fmt.Println(string(c)) - } -} - -func testSplitChar() { - var v interface{} - j := gjson.New(nil) - t1 := gtime.TimestampNano() - j.Set("a.b.c.d.e.f.g.h.i.j.k", 1) - t2 := gtime.TimestampNano() - fmt.Println(t2 - t1) - - t5 := gtime.TimestampNano() - v = j.Get("a.b.c.d.e.f.g.h.i.j.k") - t6 := gtime.TimestampNano() - fmt.Println(v) - fmt.Println(t6 - t5) - - j.SetSplitChar('#') - - t7 := gtime.TimestampNano() - v = j.Get("a#b#c#d#e#f#g#h#i#j#k") - t8 := gtime.TimestampNano() - fmt.Println(v) - fmt.Println(t8 - t7) -} - -func testViolenceCheck() { - j := gjson.New(nil) - t1 := gtime.TimestampNano() - j.Set("a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a", 1) - t2 := gtime.TimestampNano() - fmt.Println(t2 - t1) - - t3 := gtime.TimestampNano() - j.Set("a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a", 1) - t4 := gtime.TimestampNano() - fmt.Println(t4 - t3) - - t5 := gtime.TimestampNano() - j.Get("a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a") - t6 := gtime.TimestampNano() - fmt.Println(t6 - t5) - - j.SetViolenceCheck(false) - - t7 := gtime.TimestampNano() - j.Set("a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a", 1) - t8 := gtime.TimestampNano() - fmt.Println(t8 - t7) - - t9 := gtime.TimestampNano() - j.Get("a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a") - t10 := gtime.TimestampNano() - fmt.Println(t10 - t9) -} - -func main() { - testViolenceCheck() -} diff --git a/.example/encoding/gjson/issue#IZXU2.go b/.example/encoding/gjson/issue#IZXU2.go deleted file mode 100644 index abbbc7fd9..000000000 --- a/.example/encoding/gjson/issue#IZXU2.go +++ /dev/null @@ -1,156 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - - "github.com/gogf/gf/v2/encoding/gjson" -) - -type XinYanModel struct { - Success bool `json:"success"` - Data Data `json:"data"` - ErrorCode interface{} `json:"errorCode"` - ErrorMsg interface{} `json:"errorMsg"` -} -type ApplyReportDetail struct { - ApplyScore string `json:"apply_score"` - ApplyCredibility string `json:"apply_credibility"` - QueryOrgCount string `json:"apply_query_org_count"` - QueryFinanceCount string `json:"apply_query_finance_count"` - QueryCashCount string `json:"apply_query_cash_count"` - QuerySumCount string `json:"apply_query_sum_count"` - LatestQueryTime string `json:"apply_latest_query_time"` - LatestOneMonth string `json:"apply_latest_one_month"` - LatestThreeMonth string `json:"apply_latest_three_month"` - LatestSixMonth string `json:"apply_latest_six_month"` -} -type BehaviorReportDetail struct { - LoansScore string `json:"behavior_report_detailloans_score"` - LoansCredibility string `json:"behavior_report_detailloans_credibility"` - LoansCount string `json:"behavior_report_detailloans_count"` - LoansSettleCount string `json:"behavior_report_detailloans_settle_count"` - LoansOverdueCount string `json:"behavior_report_detailloans_overdue_count"` - LoansOrgCount string `json:"behavior_report_detailloans_org_count"` - ConsfinOrgCount string `json:"behavior_report_detailconsfin_org_count"` - LoansCashCount string `json:"behavior_report_detailloans_cash_count"` - LatestOneMonth string `json:"behavior_report_detaillatest_one_month"` - LatestThreeMonth string `json:"behavior_report_detaillatest_three_month"` - LatestSixMonth string `json:"behavior_report_detaillatest_six_month"` - HistorySucFee string `json:"behavior_report_detailhistory_suc_fee"` - HistoryFailFee string `json:"behavior_report_detailhistory_fail_fee"` - LatestOneMonthSuc string `json:"behavior_report_detaillatest_one_month_suc"` - LatestOneMonthFail string `json:"behavior_report_detaillatest_one_month_fail"` - LoansLongTime string `json:"behavior_report_detailloans_long_time"` - LoansLatestTime string `json:"behavior_report_detailloans_latest_time"` -} -type CurrentReportDetail struct { - LoansCreditLimit string `json:"current_report_detailloans_credit_limit"` - LoansCredibility string `json:"current_report_detailloans_credibility"` - LoansOrgCount string `json:"current_report_detailloans_org_count"` - LoansProductCount string `json:"current_report_detailloans_product_count"` - LoansMaxLimit string `json:"current_report_detailloans_max_limit"` - LoansAvgLimit string `json:"current_report_detailloans_avg_limit"` - ConsfinCreditLimit string `json:"current_report_detailconsfin_credit_limit"` - ConsfinCredibility string `json:"current_report_detailconsfin_credibility"` - ConsfinOrgCount string `json:"current_report_detailconsfin_org_count"` - ConsfinProductCount string `json:"current_report_detailconsfin_product_count"` - ConsfinMaxLimit string `json:"current_report_detailconsfin_max_limit"` - ConsfinAvgLimit string `json:"current_report_detailconsfin_avg_limit"` -} -type ResultDetail struct { - ApplyReportDetail ApplyReportDetail `json:"apply_report_detail"` - BehaviorReportDetail BehaviorReportDetail `json:"behavior_report_detail"` - CurrentReportDetail CurrentReportDetail `json:"current_report_detail"` -} -type Data struct { - Code string `json:"code"` - Desc string `json:"desc1"` - TransID string `json:"trans_id"` - TradeNo string `json:"trade_no"` - Fee string `json:"fee"` - IDNo string `json:"id_no"` - IDName string `json:"id_name"` - Versions string `json:"versions"` - ResultDetail ResultDetail `json:"result_detail"` -} - -var data = `{ - "success": true, - "data": { - "code": "0", - "desc": "查询成功", - "trans_id": "14910304379231213", - "trade_no": "201704011507240100057329", - "fee": "Y", - "id_no": "0783231bcc39f4957e99907e02ae401c", - "id_name": "dd67a5943781369ddd7c594e231e9e70 ", - "versions": "1.0.0", - "result_detail":{ - "apply_report_detail": { - "apply_score": "189", - "apply_credibility": "84", - "query_org_count": "7", - "query_finance_count": "2", - "query_cash_count": "2", - "query_sum_count": "13", - "latest_query_time": "2017-09-03", - "latest_one_month": "1", - "latest_three_month": "5", - "latest_six_month": "12" - }, - "behavior_report_detail": { - "loans_score": "199", - "loans_credibility": "90", - "loans_count": "300", - "loans_settle_count": "280", - "loans_overdue_count": "20", - "loans_org_count": "5", - "consfin_org_count": "3", - "loans_cash_count": "2", - "latest_one_month": "3", - "latest_three_month": "20", - "latest_six_month": "23", - "history_suc_fee": "30", - "history_fail_fee": "25", - "latest_one_month_suc": "5", - "latest_one_month_fail": "20", - "loans_long_time": "130", - "loans_latest_time": "2017-09-16" - }, - "current_report_detail": { - "loans_credit_limit": "1400", - "loans_credibility": "80", - "loans_org_count": "7", - "loans_product_count": "8", - "loans_max_limit": "2000", - "loans_avg_limit": "1000", - "consfin_credit_limit": "1500", - "consfin_credibility": "90", - "consfin_org_count": "8", - "consfin_product_count": "5", - "consfin_max_limit": "5000", - "consfin_avg_limit": "3000" - } - } - }, - "errorCode": null, - "errorMsg": null -}` - -func main() { - struct1 := new(XinYanModel) - err := json.Unmarshal([]byte(data), struct1) - fmt.Println(err) - fmt.Println(struct1) - - fmt.Println() - - struct2 := new(XinYanModel) - j, err := gjson.DecodeToJson(data) - fmt.Println(err) - fmt.Println(j.Get("data.desc")) - err = j.ToStruct(struct2) - fmt.Println(err) - fmt.Println(struct2) -} diff --git a/.example/encoding/gjson/issue283.go b/.example/encoding/gjson/issue283.go deleted file mode 100644 index 52b20a274..000000000 --- a/.example/encoding/gjson/issue283.go +++ /dev/null @@ -1,69 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/encoding/gjson" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/glog" -) - -type GameUser struct { - Uid int `json:"uid"` - Account string `json:"account"` - Tel string `json:"tel"` - Role string `json:"role"` - Vip int `json:"vip"` - GameLevel int `json:"gamelevel"` - Diamond int `json:"diamond"` - Coin int `json:"coin"` - Value int `json:"value"` - Area string `json:"area"` - ServerName string `json:"servername"` - Time int `json:"time"` - ClientInfo *ClientInfo `json:"client_info"` -} - -type ClientInfo struct { - ClientGuid string `json:"client_guid"` - ClientType int `json:"client_type"` - ClientSDKVersion string `json:"client_sdk_version"` - ClientVersion string `json:"client_version"` - PackageId string `json:"packageid"` - PhoneType string `json:"phone_type"` - DevicesId string `json:"devices_id"` - ClientMac string `json:"client_mac"` -} - -func main() { - s := `{ - "uid":9527, - "account":"zhangsan", - "tel":"15248787", - "role":"test", - "vip":7, - "gamelevel":59, - "diamond ":59, - "coin ":59, - "value ":99, - "area":"s", - "servername":"灵动", - "time":15454878787, - "client_info": { - "client_guid": "aaaa", - "client_type": 1, - "client_sdk_version": "1.0.1", - "client_version": "1.0.1", - "packageid":"", - "phone_type": "vivi", - "devices_id":"", - "client_mac":"" - } -}` - - gameUser := &GameUser{} - err := gjson.DecodeTo(s, gameUser) - if err != nil { - glog.Error(err) - } - g.Dump(gameUser) - -} diff --git a/.example/encoding/gjson/issue360.go b/.example/encoding/gjson/issue360.go deleted file mode 100644 index 7b753f312..000000000 --- a/.example/encoding/gjson/issue360.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/encoding/gjson" -) - -func main() { - s := ` -{"apiVersion":"v1","kind":"Service","metadata":{"labels":{"name":"http-daemon"},"name":"http-daemon","namespace":"default"},"spec":{"ports":[{"name":"http-daemon","port":8080,"protocol":"TCP","targetPort":9212}],"selector":{"app":"http-daemon","version":"v0930-082326"}}} -` - js, err := gjson.DecodeToJson(s) - if err != nil { - panic(err) - } - //g.Dump(js.ToMap()) - y, _ := js.ToYamlString() - fmt.Println(y) -} diff --git a/.example/encoding/gyaml/gyaml.go b/.example/encoding/gyaml/gyaml.go deleted file mode 100644 index fc6380291..000000000 --- a/.example/encoding/gyaml/gyaml.go +++ /dev/null @@ -1,30 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/encoding/gyaml" -) - -func main() { - var yamlStr string = ` -#即表示url属性值; -url: http://www.wolfcode.cn -#即表示server.host属性的值; -server: - host: http://www.wolfcode.cn -#数组,即表示server为[a,b,c] -server: - - 120.168.117.21 - - 120.168.117.22 - - 120.168.117.23 -#常量 -pi: 3.14 #定义一个数值3.14 -hasChild: true #定义一个boolean值 -name: '你好YAML' #定义一个字符串 -` - - i, err := gyaml.Decode([]byte(yamlStr)) - fmt.Println(err) - fmt.Println(i) -} diff --git a/.example/errors/gerror/gerror1.go b/.example/errors/gerror/gerror1.go deleted file mode 100644 index 32ed092e3..000000000 --- a/.example/errors/gerror/gerror1.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import ( - "errors" - "fmt" - - "github.com/gogf/gf/v2/errors/gerror" -) - -func Error1() error { - return errors.New("test1") -} - -func Error2() error { - return gerror.New("test2") -} - -func main() { - err1 := Error1() - err2 := Error2() - fmt.Printf("%s, %-s, %+s\n", err1, err1, err1) - fmt.Printf("%v, %-v, %+v\n", err1, err1, err1) - fmt.Printf("%s, %-s, %+s\n", err2, err2, err2) - fmt.Printf("%v, %-v, %+v\n", err2, err2, err2) -} diff --git a/.example/errors/gerror/gerror2.go b/.example/errors/gerror/gerror2.go deleted file mode 100644 index 0d78edd99..000000000 --- a/.example/errors/gerror/gerror2.go +++ /dev/null @@ -1,26 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/errors/gerror" -) - -func OpenFile() error { - return gerror.New("permission denied") -} - -func OpenConfig() error { - return gerror.Wrap(OpenFile(), "configuration file opening failed") -} - -func ReadConfig() error { - return gerror.Wrap(OpenConfig(), "reading configuration failed") -} - -func main() { - //err := ReadConfig() - //glog.Printf("%s\n%+s", err, err) - //glog.Printf("%+v", err) - fmt.Printf("%+v", ReadConfig()) -} diff --git a/.example/errors/gerror/gerror3.go b/.example/errors/gerror/gerror3.go deleted file mode 100644 index 007db4f0a..000000000 --- a/.example/errors/gerror/gerror3.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "errors" - "fmt" - - "github.com/gogf/gf/v2/errors/gerror" -) - -func Error1() error { - return errors.New("test1") -} - -func Error2() error { - return gerror.New("test2") -} - -func main() { - err1 := Error1() - err2 := Error2() - fmt.Println("err1:\n", gerror.Stack(err1)) - fmt.Println("err2:\n", gerror.Stack(err2)) -} diff --git a/.example/errors/gerror/gerror4.go b/.example/errors/gerror/gerror4.go deleted file mode 100644 index 03a10ac2e..000000000 --- a/.example/errors/gerror/gerror4.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/errors/gerror" -) - -func OpenFile() error { - return gerror.New("permission denied") -} - -func OpenConfig() error { - return gerror.Wrap(OpenFile(), "configuration file opening failed") -} - -func ReadConfig() error { - return gerror.Wrap(OpenConfig(), "reading configuration failed") -} - -func main() { - fmt.Println(gerror.Cause(ReadConfig())) -} diff --git a/.example/errors/gerror/gerror5.go b/.example/errors/gerror/gerror5.go deleted file mode 100644 index 56426ae37..000000000 --- a/.example/errors/gerror/gerror5.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "errors" - - "github.com/gogf/gf/v2/os/glog" - - "github.com/gogf/gf/v2/errors/gerror" -) - -func Error1() error { - return errors.New("test1") -} - -func Error2() error { - return gerror.New("test2") -} - -func main() { - glog.Print(Error1()) - glog.Print(Error2()) -} diff --git a/.example/i18n/gi18n/gi18n-dir.go b/.example/i18n/gi18n/gi18n-dir.go deleted file mode 100644 index f05751e85..000000000 --- a/.example/i18n/gi18n/gi18n-dir.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "context" - "fmt" - - "github.com/gogf/gf/v2/i18n/gi18n" -) - -func main() { - t := gi18n.New() - t.SetLanguage("ja") - err := t.SetPath("./i18n-dir") - if err != nil { - panic(err) - } - fmt.Println(t.Translate(context.TODO(), `hello`)) - fmt.Println(t.Translate(context.TODO(), `{#hello}{#world}!`)) -} diff --git a/.example/i18n/gi18n/gi18n-file.go b/.example/i18n/gi18n/gi18n-file.go deleted file mode 100644 index 3c81bf1f5..000000000 --- a/.example/i18n/gi18n/gi18n-file.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "context" - "fmt" - - "github.com/gogf/gf/v2/i18n/gi18n" -) - -func main() { - t := gi18n.New() - t.SetLanguage("ja") - err := t.SetPath("./i18n-file") - if err != nil { - panic(err) - } - fmt.Println(t.Translate(context.TODO(), `hello`)) - fmt.Println(t.Translate(context.TODO(), `{#hello}{#world}!`)) -} diff --git a/.example/i18n/gi18n/gi18n.go b/.example/i18n/gi18n/gi18n.go deleted file mode 100644 index e54764bbf..000000000 --- a/.example/i18n/gi18n/gi18n.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "context" - "fmt" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/i18n/gi18n" -) - -func main() { - var ( - orderId = 865271654 - orderAmount = 99.8 - ) - fmt.Println(g.I18n().Tf( - gi18n.WithLanguage(context.TODO(), `en`), - `{#OrderPaid}`, orderId, orderAmount, - )) - fmt.Println(g.I18n().Tf( - gi18n.WithLanguage(context.TODO(), `zh-CN`), - `{#OrderPaid}`, orderId, orderAmount, - )) -} diff --git a/.example/i18n/gi18n/http_view_i18n.go b/.example/i18n/gi18n/http_view_i18n.go deleted file mode 100644 index e38340288..000000000 --- a/.example/i18n/gi18n/http_view_i18n.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/i18n/gi18n" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.Group("/", func(group *ghttp.RouterGroup) { - group.Middleware(func(r *ghttp.Request) { - r.SetCtx(gi18n.WithLanguage(r.Context(), r.GetString("lang", "zh-CN"))) - r.Middleware.Next() - }) - group.ALL("/", func(r *ghttp.Request) { - r.Response.WriteTplContent(`{#hello}{#world}!`) - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/i18n/gi18n/i18n-dir/en/hello.toml b/.example/i18n/gi18n/i18n-dir/en/hello.toml deleted file mode 100644 index 1680a362c..000000000 --- a/.example/i18n/gi18n/i18n-dir/en/hello.toml +++ /dev/null @@ -1,2 +0,0 @@ - -hello = "Hello" \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-dir/en/world.toml b/.example/i18n/gi18n/i18n-dir/en/world.toml deleted file mode 100644 index f9afd1e67..000000000 --- a/.example/i18n/gi18n/i18n-dir/en/world.toml +++ /dev/null @@ -1,2 +0,0 @@ - -world = "World" \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-dir/ja/hello.yaml b/.example/i18n/gi18n/i18n-dir/ja/hello.yaml deleted file mode 100644 index ec827cd49..000000000 --- a/.example/i18n/gi18n/i18n-dir/ja/hello.yaml +++ /dev/null @@ -1,2 +0,0 @@ - -hello: "こんにちは" \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-dir/ja/world.yaml b/.example/i18n/gi18n/i18n-dir/ja/world.yaml deleted file mode 100644 index 04e828b42..000000000 --- a/.example/i18n/gi18n/i18n-dir/ja/world.yaml +++ /dev/null @@ -1 +0,0 @@ -world: "世界" \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-dir/ru/hello.ini b/.example/i18n/gi18n/i18n-dir/ru/hello.ini deleted file mode 100644 index c65ec2155..000000000 --- a/.example/i18n/gi18n/i18n-dir/ru/hello.ini +++ /dev/null @@ -1 +0,0 @@ -hello = "Привет" \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-dir/ru/world.ini b/.example/i18n/gi18n/i18n-dir/ru/world.ini deleted file mode 100644 index 7e9e60499..000000000 --- a/.example/i18n/gi18n/i18n-dir/ru/world.ini +++ /dev/null @@ -1 +0,0 @@ -world = "мир" \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-dir/zh-CN/hello.json b/.example/i18n/gi18n/i18n-dir/zh-CN/hello.json deleted file mode 100644 index b8eb10e94..000000000 --- a/.example/i18n/gi18n/i18n-dir/zh-CN/hello.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "hello": "你好" -} \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-dir/zh-CN/world.json b/.example/i18n/gi18n/i18n-dir/zh-CN/world.json deleted file mode 100644 index 9d6392149..000000000 --- a/.example/i18n/gi18n/i18n-dir/zh-CN/world.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "world": "世界" -} \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-dir/zh-TW/hello.xml b/.example/i18n/gi18n/i18n-dir/zh-TW/hello.xml deleted file mode 100644 index a4e52ef07..000000000 --- a/.example/i18n/gi18n/i18n-dir/zh-TW/hello.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - 你好 - \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-dir/zh-TW/world.xml b/.example/i18n/gi18n/i18n-dir/zh-TW/world.xml deleted file mode 100644 index 877b402c5..000000000 --- a/.example/i18n/gi18n/i18n-dir/zh-TW/world.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - 世界 - \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-file/en.toml b/.example/i18n/gi18n/i18n-file/en.toml deleted file mode 100644 index 17df41597..000000000 --- a/.example/i18n/gi18n/i18n-file/en.toml +++ /dev/null @@ -1,3 +0,0 @@ - -hello = "Hello" -world = "World" \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-file/ja.yaml b/.example/i18n/gi18n/i18n-file/ja.yaml deleted file mode 100644 index 0166fcefb..000000000 --- a/.example/i18n/gi18n/i18n-file/ja.yaml +++ /dev/null @@ -1,3 +0,0 @@ - -hello: "こんにちは" -world: "世界" \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-file/ru.ini b/.example/i18n/gi18n/i18n-file/ru.ini deleted file mode 100644 index fa2df856c..000000000 --- a/.example/i18n/gi18n/i18n-file/ru.ini +++ /dev/null @@ -1,2 +0,0 @@ -hello = "Привет" -world = "мир" \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-file/zh-CN.json b/.example/i18n/gi18n/i18n-file/zh-CN.json deleted file mode 100644 index 1de75ba1a..000000000 --- a/.example/i18n/gi18n/i18n-file/zh-CN.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "hello": "你好", - "world": "世界" -} \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-file/zh-TW.xml b/.example/i18n/gi18n/i18n-file/zh-TW.xml deleted file mode 100644 index 9a4356f4c..000000000 --- a/.example/i18n/gi18n/i18n-file/zh-TW.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - 你好 - 世界 - \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n/en.toml b/.example/i18n/gi18n/i18n/en.toml deleted file mode 100644 index 67762d579..000000000 --- a/.example/i18n/gi18n/i18n/en.toml +++ /dev/null @@ -1 +0,0 @@ -OrderPaid = "You have successfully complete order #%d payment, paid amount: ¥%0.2f." \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n/ja.toml b/.example/i18n/gi18n/i18n/ja.toml deleted file mode 100644 index 8ca47ed7f..000000000 --- a/.example/i18n/gi18n/i18n/ja.toml +++ /dev/null @@ -1,3 +0,0 @@ - -hello = "こんにちは" -world = "世界" \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n/ru.toml b/.example/i18n/gi18n/i18n/ru.toml deleted file mode 100644 index 938434a5a..000000000 --- a/.example/i18n/gi18n/i18n/ru.toml +++ /dev/null @@ -1,3 +0,0 @@ - -hello = "Привет" -world = "мир" \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n/zh-CN.toml b/.example/i18n/gi18n/i18n/zh-CN.toml deleted file mode 100644 index 20406d93a..000000000 --- a/.example/i18n/gi18n/i18n/zh-CN.toml +++ /dev/null @@ -1,3 +0,0 @@ -OrderPaid = "您已成功完成订单号 #%d 支付,支付金额¥%.2f。" -hello = "你好" -world = "世界" \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n/zh-TW.toml b/.example/i18n/gi18n/i18n/zh-TW.toml deleted file mode 100644 index b3a52c527..000000000 --- a/.example/i18n/gi18n/i18n/zh-TW.toml +++ /dev/null @@ -1,2 +0,0 @@ -hello = "你好" -world = "世界" \ No newline at end of file diff --git a/.example/i18n/gi18n/resource/gi18n-resource.go b/.example/i18n/gi18n/resource/gi18n-resource.go deleted file mode 100644 index 7867b202c..000000000 --- a/.example/i18n/gi18n/resource/gi18n-resource.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - - _ "github.com/gogf/gf/v2/os/gres/testdata" -) - -func main() { - m := g.I18n() - m.SetLanguage("ja") - err := m.SetPath("/i18n-dir") - if err != nil { - panic(err) - } - fmt.Println(m.Translate(`hello`)) - fmt.Println(m.Translate(`{#hello}{#world}!`)) -} diff --git a/.example/i18n/gi18n/template/index.html b/.example/i18n/gi18n/template/index.html deleted file mode 100644 index e2a2a6b43..000000000 --- a/.example/i18n/gi18n/template/index.html +++ /dev/null @@ -1 +0,0 @@ -{{T "hello" "你好"}} {{T "world" "世界"}}! \ No newline at end of file diff --git a/.example/net/ghttp/client/cookie/client.go b/.example/net/ghttp/client/cookie/client.go deleted file mode 100644 index 212a81f6b..000000000 --- a/.example/net/ghttp/client/cookie/client.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - c := ghttp.NewClient() - c.SetHeader("Cookie", "name=john; score=100") - if r, e := c.Get("http://127.0.0.1:8199/"); e != nil { - glog.Error(e) - } else { - fmt.Println(string(r.ReadAll())) - } -} diff --git a/.example/net/ghttp/client/cookie/server.go b/.example/net/ghttp/client/cookie/server.go deleted file mode 100644 index e262d9097..000000000 --- a/.example/net/ghttp/client/cookie/server.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln(r.Cookie.Map()) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/client/get.go b/.example/net/ghttp/client/get.go deleted file mode 100644 index 623073f3d..000000000 --- a/.example/net/ghttp/client/get.go +++ /dev/null @@ -1,12 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - r, err := ghttp.Get("http://127.0.0.1:8199/11111/11122") - fmt.Println(err) - fmt.Println(r.Header) -} diff --git a/.example/net/ghttp/client/middleware/client.go b/.example/net/ghttp/client/middleware/client.go deleted file mode 100644 index babba4fa5..000000000 --- a/.example/net/ghttp/client/middleware/client.go +++ /dev/null @@ -1,64 +0,0 @@ -package main - -import ( - "bytes" - "fmt" - "github.com/gogf/gf/v2/container/garray" - "github.com/gogf/gf/v2/crypto/gmd5" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/util/gconv" - "github.com/gogf/gf/v2/util/guid" - "github.com/gogf/gf/v2/util/gutil" - "io/ioutil" - "net/http" -) - -const ( - appId = "123" - appSecret = "456" -) - -// 注入统一的接口签名参数 -func injectSignature(jsonContent []byte) []byte { - var m map[string]interface{} - _ = json.Unmarshal(jsonContent, &m) - if len(m) > 0 { - m["appid"] = appId - m["nonce"] = guid.S() - m["timestamp"] = gtime.Timestamp() - var ( - keyArray = garray.NewSortedStrArrayFrom(gutil.Keys(m)) - sigContent string - ) - keyArray.Iterator(func(k int, v string) bool { - sigContent += v - sigContent += gconv.String(m[v]) - return true - }) - m["signature"] = gmd5.MustEncryptString(gmd5.MustEncryptString(sigContent) + appSecret) - jsonContent, _ = json.Marshal(m) - } - return jsonContent -} - -func main() { - c := g.Client() - c.Use(func(c *ghttp.Client, r *http.Request) (resp *ghttp.ClientResponse, err error) { - bodyBytes, _ := ioutil.ReadAll(r.Body) - if len(bodyBytes) > 0 { - // 注入签名相关参数,修改Request原有的提交参数 - bodyBytes = injectSignature(bodyBytes) - r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) - r.ContentLength = int64(len(bodyBytes)) - } - return c.Next(r) - }) - content := c.ContentJson().PostContent("http://127.0.0.1:8199/", g.Map{ - "name": "goframe", - "site": "https://goframe.org", - }) - fmt.Println(content) -} diff --git a/.example/net/ghttp/client/middleware/server.go b/.example/net/ghttp/client/middleware/server.go deleted file mode 100644 index 8b431f89b..000000000 --- a/.example/net/ghttp/client/middleware/server.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.Group("/", func(group *ghttp.RouterGroup) { - group.ALL("/", func(r *ghttp.Request) { - r.Response.Write(r.GetMap()) - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/client/upload-batch/client.go b/.example/net/ghttp/client/upload-batch/client.go deleted file mode 100644 index d8176b703..000000000 --- a/.example/net/ghttp/client/upload-batch/client.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - path1 := "/Users/john/Pictures/logo1.png" - path2 := "/Users/john/Pictures/logo2.png" - r, e := ghttp.Post( - "http://127.0.0.1:8199/upload", - fmt.Sprintf(`upload-file=@file:%s&upload-file=@file:%s`, path1, path2), - ) - if e != nil { - glog.Error(e) - } else { - fmt.Println(string(r.ReadAll())) - r.Close() - } -} diff --git a/.example/net/ghttp/client/upload-batch/client2.go b/.example/net/ghttp/client/upload-batch/client2.go deleted file mode 100644 index 7cc2963e5..000000000 --- a/.example/net/ghttp/client/upload-batch/client2.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - path1 := "/Users/john/Pictures/logo1.png" - path2 := "/Users/john/Pictures/logo2.png" - r, e := ghttp.Post( - "http://127.0.0.1:8199/upload", - fmt.Sprintf(`upload-file[]=@file:%s&upload-file[]=@file:%s`, path1, path2), - ) - if e != nil { - glog.Error(e) - } else { - fmt.Println(string(r.ReadAll())) - r.Close() - } -} diff --git a/.example/net/ghttp/client/upload-batch/server.go b/.example/net/ghttp/client/upload-batch/server.go deleted file mode 100644 index 5443dc298..000000000 --- a/.example/net/ghttp/client/upload-batch/server.go +++ /dev/null @@ -1,62 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -// Upload uploads files to /tmp . -func Upload(r *ghttp.Request) { - saveDirPath := "/tmp/" - files := r.GetUploadFiles("upload-file") - if _, err := files.Save(saveDirPath); err != nil { - r.Response.WriteExit(err) - } - r.Response.WriteExit("upload successfully") -} - -// UploadShow shows uploading simgle file page. -func UploadShow(r *ghttp.Request) { - r.Response.Write(` - - - GF Upload File Demo - - -
- - -
- - - `) -} - -// UploadShowBatch shows uploading multiple files page. -func UploadShowBatch(r *ghttp.Request) { - r.Response.Write(` - - - GF Upload Files Demo - - -
- - - -
- - - `) -} - -func main() { - s := g.Server() - s.Group("/upload", func(group *ghttp.RouterGroup) { - group.POST("/", Upload) - group.ALL("/show", UploadShow) - group.ALL("/batch", UploadShowBatch) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/client/upload/client.go b/.example/net/ghttp/client/upload/client.go deleted file mode 100644 index 606c5252a..000000000 --- a/.example/net/ghttp/client/upload/client.go +++ /dev/null @@ -1,41 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/frame/g" - "path/filepath" - - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/glog" -) - -func SendXmlFile(gameId int, areaName string, filePath string) error { - path := filepath.FromSlash(filePath) - fmt.Println(path) - data := g.Map{ - "gameName": gameId, - "area": areaName, - "file": "@file:" + path, - "contentType": "json", - } - if r, err := ghttp.Post("http://127.0.0.1:8199/upload", data); err != nil { - panic(err) - } else { - defer r.Close() - fmt.Println("ok") - } - return nil -} - -func main() { - SendXmlFile(1, "xxx", "/Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/.example/net/ghttp/server/session.go") - return - path := "/home/john/Workspace/Go/github.com/gogf/gf/version.go" - r, e := ghttp.Post("http://127.0.0.1:8199/upload", "upload-file=@file:"+path) - if e != nil { - glog.Error(e) - } else { - fmt.Println(string(r.ReadAll())) - r.Close() - } -} diff --git a/.example/net/ghttp/client/upload/server.go b/.example/net/ghttp/client/upload/server.go deleted file mode 100644 index 4573fae51..000000000 --- a/.example/net/ghttp/client/upload/server.go +++ /dev/null @@ -1,62 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -// Upload uploads files to /tmp . -func Upload(r *ghttp.Request) { - saveDirPath := "/tmp/" - files := r.GetUploadFiles("file") - if _, err := files.Save(saveDirPath); err != nil { - r.Response.WriteExit(err) - } - r.Response.WriteExit("upload successfully") -} - -// UploadShow shows uploading simgle file page. -func UploadShow(r *ghttp.Request) { - r.Response.Write(` - - - GF Upload File Demo - - -
- - -
- - - `) -} - -// UploadShowBatch shows uploading multiple files page. -func UploadShowBatch(r *ghttp.Request) { - r.Response.Write(` - - - GF Upload Files Demo - - -
- - - -
- - - `) -} - -func main() { - s := g.Server() - s.Group("/upload", func(group *ghttp.RouterGroup) { - group.POST("/", Upload) - group.ALL("/show", UploadShow) - group.ALL("/batch", UploadShowBatch) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/admin/admin.go b/.example/net/ghttp/server/admin/admin.go deleted file mode 100644 index 640954823..000000000 --- a/.example/net/ghttp/server/admin/admin.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.SetNameToUriType(ghttp.URI_TYPE_FULLNAME) - s.EnableAdmin() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Write("hello world") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/body.go b/.example/net/ghttp/server/body.go deleted file mode 100644 index ea762fd54..000000000 --- a/.example/net/ghttp/server/body.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "io/ioutil" -) - -func main() { - s := g.Server() - s.SetIndexFolder(true) - s.BindHandler("/", func(r *ghttp.Request) { - body1 := r.GetBody() - body2, _ := ioutil.ReadAll(r.Body) - fmt.Println(body1) - fmt.Println(body2) - r.Response.Write("hello world") - }) - s.SetPort(8999) - s.Run() -} diff --git a/.example/net/ghttp/server/controller/template/footer.html b/.example/net/ghttp/server/controller/template/footer.html deleted file mode 100644 index 83ae25b65..000000000 --- a/.example/net/ghttp/server/controller/template/footer.html +++ /dev/null @@ -1 +0,0 @@ -

FOOTER

\ No newline at end of file diff --git a/.example/net/ghttp/server/controller/template/header.html b/.example/net/ghttp/server/controller/template/header.html deleted file mode 100644 index b9cb0a77c..000000000 --- a/.example/net/ghttp/server/controller/template/header.html +++ /dev/null @@ -1 +0,0 @@ -

HEADER

\ No newline at end of file diff --git a/.example/net/ghttp/server/controller/template/layout.html b/.example/net/ghttp/server/controller/template/layout.html deleted file mode 100644 index 9f58c21a0..000000000 --- a/.example/net/ghttp/server/controller/template/layout.html +++ /dev/null @@ -1,3 +0,0 @@ -{{include "header.html" .}} -{{include .mainTpl .}} -{{include "footer.html" .}} \ No newline at end of file diff --git a/.example/net/ghttp/server/controller/template/main/main1.html b/.example/net/ghttp/server/controller/template/main/main1.html deleted file mode 100644 index ac8fb6186..000000000 --- a/.example/net/ghttp/server/controller/template/main/main1.html +++ /dev/null @@ -1,2 +0,0 @@ -

MAIN1

-

Name: {{.name}}

\ No newline at end of file diff --git a/.example/net/ghttp/server/controller/template/main/main2.html b/.example/net/ghttp/server/controller/template/main/main2.html deleted file mode 100644 index 3d2351aea..000000000 --- a/.example/net/ghttp/server/controller/template/main/main2.html +++ /dev/null @@ -1,2 +0,0 @@ -

MAIN2

-

Name: {{.name}}

\ No newline at end of file diff --git a/.example/net/ghttp/server/controller/user.go b/.example/net/ghttp/server/controller/user.go deleted file mode 100644 index 1fe010bbf..000000000 --- a/.example/net/ghttp/server/controller/user.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/frame/gmvc" -) - -type User struct { - gmvc.Controller -} - -func (c *User) Index() { - c.View.Display("index.html") -} - -// 不符合规范,不会被自动注册 -func (c *User) Test(value interface{}) { - c.View.Display("index.html") -} - -func main() { - //g.View().SetPath("C:/www/static") - s := g.Server() - s.BindController("/user", new(User)) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/controller/view.go b/.example/net/ghttp/server/controller/view.go deleted file mode 100644 index 70f3f96c3..000000000 --- a/.example/net/ghttp/server/controller/view.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/frame/gmvc" -) - -type Controller struct { - gmvc.Controller -} - -func (c *Controller) Index() { - c.View.Assign("name", "john") - c.View.Assign("mainTpl", "main/main2.html") - c.View.Display("layout.html") -} - -func main() { - s := g.Server() - s.BindController("/view", new(Controller)) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/cookie.go b/.example/net/ghttp/server/cookie.go deleted file mode 100644 index 7702456cb..000000000 --- a/.example/net/ghttp/server/cookie.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - s := g.Server() - s.BindHandler("/cookie", func(r *ghttp.Request) { - datetime := r.Cookie.Get("datetime") - r.Cookie.Set("datetime", gtime.Datetime()) - r.Response.Write("datetime:", datetime) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/cors/cors1.go b/.example/net/ghttp/server/cors/cors1.go deleted file mode 100644 index 03c50b6aa..000000000 --- a/.example/net/ghttp/server/cors/cors1.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/glog" -) - -func MiddlewareCORS(r *ghttp.Request) { - r.Response.CORSDefault() - r.Middleware.Next() -} - -func Order(r *ghttp.Request) { - glog.Print("order") - r.Response.Write("GET") -} - -func main() { - s := g.Server() - s.Group("/api.v1", func(group *ghttp.RouterGroup) { - group.Middleware(MiddlewareCORS) - group.GET("/order", Order) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/cors/cors2.go b/.example/net/ghttp/server/cors/cors2.go deleted file mode 100644 index 307ab1ddf..000000000 --- a/.example/net/ghttp/server/cors/cors2.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func MiddlewareCORS(r *ghttp.Request) { - corsOptions := r.Response.DefaultCORSOptions() - corsOptions.AllowDomain = []string{"goframe.org", "baidu.com"} - r.Response.CORS(corsOptions) - r.Middleware.Next() -} - -func Order(r *ghttp.Request) { - r.Response.Write("GET") -} - -func main() { - s := g.Server() - s.Group("/api.v1", func(group *ghttp.RouterGroup) { - group.Middleware(MiddlewareCORS) - group.GET("/order", Order) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/cors/cors3.go b/.example/net/ghttp/server/cors/cors3.go deleted file mode 100644 index 499e75d28..000000000 --- a/.example/net/ghttp/server/cors/cors3.go +++ /dev/null @@ -1,33 +0,0 @@ -package main - -import ( - "net/http" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func MiddlewareCORS(r *ghttp.Request) { - corsOptions := r.Response.DefaultCORSOptions() - corsOptions.AllowDomain = []string{"goframe.org"} - if !r.Response.CORSAllowedOrigin(corsOptions) { - r.Response.WriteStatus(http.StatusForbidden) - return - } - r.Response.CORS(corsOptions) - r.Middleware.Next() -} - -func Order(r *ghttp.Request) { - r.Response.Write("GET") -} - -func main() { - s := g.Server() - s.Group("/api.v1", func(group *ghttp.RouterGroup) { - group.Middleware(MiddlewareCORS) - group.GET("/order", Order) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/denyroutes/config.toml b/.example/net/ghttp/server/denyroutes/config.toml deleted file mode 100644 index 0e7810036..000000000 --- a/.example/net/ghttp/server/denyroutes/config.toml +++ /dev/null @@ -1 +0,0 @@ -You're not supposed to view this \ No newline at end of file diff --git a/.example/net/ghttp/server/denyroutes/denyroutes.go b/.example/net/ghttp/server/denyroutes/denyroutes.go deleted file mode 100644 index 4dc0020f0..000000000 --- a/.example/net/ghttp/server/denyroutes/denyroutes.go +++ /dev/null @@ -1,12 +0,0 @@ -package main - -import "github.com/gogf/gf/v2/frame/g" - -func main() { - s := g.Server() - s.SetDenyRoutes([]string{ - "/config*", - }) - s.SetPort(8299) - s.Run() -} diff --git a/.example/net/ghttp/server/domain.go b/.example/net/ghttp/server/domain.go deleted file mode 100644 index f43bc4611..000000000 --- a/.example/net/ghttp/server/domain.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import "github.com/gogf/gf/v2/net/ghttp" - -func Hello1(r *ghttp.Request) { - r.Response.Write("127.0.0.1: Hello World1!") -} - -func Hello2(r *ghttp.Request) { - r.Response.Write("localhost: Hello World2!") -} - -func main() { - s := ghttp.GetServer() - s.Domain("127.0.0.1").BindHandler("/", Hello1) - s.Domain("localhost, local").BindHandler("/", Hello2) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/download/download.go b/.example/net/ghttp/server/download/download.go deleted file mode 100644 index cc1ebee35..000000000 --- a/.example/net/ghttp/server/download/download.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/download", func(r *ghttp.Request) { - r.Response.Header().Set("Content-Type", "text/html;charset=utf-8") - r.Response.Header().Set("Content-type", "application/force-download") - r.Response.Header().Set("Content-Type", "application/octet-stream") - r.Response.Header().Set("Accept-Ranges", "bytes") - r.Response.Header().Set("Content-Disposition", "attachment;filename=\"下载文件名称.txt\"") - r.Response.ServeFile("text.txt") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/download/text.txt b/.example/net/ghttp/server/download/text.txt deleted file mode 100644 index 7e7566d8c..000000000 --- a/.example/net/ghttp/server/download/text.txt +++ /dev/null @@ -1 +0,0 @@ -下载文件内容。 \ No newline at end of file diff --git a/.example/net/ghttp/server/duplicate/duplicate1.go b/.example/net/ghttp/server/duplicate/duplicate1.go deleted file mode 100644 index 65b506465..000000000 --- a/.example/net/ghttp/server/duplicate/duplicate1.go +++ /dev/null @@ -1,19 +0,0 @@ -// 路由重复注册检查 - handler -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln("哈喽世界!") - }) - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln("哈喽世界!") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/duplicate/duplicate2.go b/.example/net/ghttp/server/duplicate/duplicate2.go deleted file mode 100644 index 85bcae9a3..000000000 --- a/.example/net/ghttp/server/duplicate/duplicate2.go +++ /dev/null @@ -1,33 +0,0 @@ -// 路由重复注册检查 - controller -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/frame/gmvc" -) - -type User struct { - gmvc.Controller -} - -func (u *User) Index() { - u.Response.Write("User") -} - -func (u *User) Info() { - u.Response.Write("Info - Uid: ", u.Request.Get("uid")) -} - -func (u *User) List() { - u.Response.Write("List - Page: ", u.Request.Get("page")) -} - -func main() { - s := g.Server() - s.BindController("/user", new(User)) - s.BindController("/user/{.method}/{uid}", new(User), "Info") - s.BindController("/user/{.method}/{page}.html", new(User), "List") - s.BindController("/user/{.method}/{page}.html", new(User), "List") - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/duplicate/duplicate3.go b/.example/net/ghttp/server/duplicate/duplicate3.go deleted file mode 100644 index e2b870f6c..000000000 --- a/.example/net/ghttp/server/duplicate/duplicate3.go +++ /dev/null @@ -1,25 +0,0 @@ -// 路由重复注册检查 - object -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -type Object struct{} - -func (o *Object) Index(r *ghttp.Request) { - r.Response.Write("object index") -} - -func (o *Object) Show(r *ghttp.Request) { - r.Response.Write("object show") -} - -func main() { - s := g.Server() - g.Server().BindObject("/object", new(Object)) - g.Server().BindObject("/object", new(Object)) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/exit.go b/.example/net/ghttp/server/exit.go deleted file mode 100644 index c000f3270..000000000 --- a/.example/net/ghttp/server/exit.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - p := "/" - s := g.Server() - s.BindHandler(p, func(r *ghttp.Request) { - r.Response.Writeln("start") - r.Exit() - r.Response.Writeln("end") - }) - s.BindHookHandlerByMap(p, map[string]ghttp.HandlerFunc{ - ghttp.HookBeforeServe: func(r *ghttp.Request) { - glog.To(r.Response.Writer).Print(r.Context(), "BeforeServe") - }, - ghttp.HookAfterServe: func(r *ghttp.Request) { - glog.To(r.Response.Writer).Print(r.Context(), "AfterServe") - }, - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/form/form-client.go b/.example/net/ghttp/server/form/form-client.go deleted file mode 100644 index 9a7e29bce..000000000 --- a/.example/net/ghttp/server/form/form-client.go +++ /dev/null @@ -1,9 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - ghttp.PostContent("http://127.0.0.1:8199/", "array[]=1&array[]=2") -} diff --git a/.example/net/ghttp/server/form/form.go b/.example/net/ghttp/server/form/form.go deleted file mode 100644 index 447ea6d78..000000000 --- a/.example/net/ghttp/server/form/form.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - g.Dump(r.GetForm("array")) - r.Response.WriteTpl("form.html") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/form/form.html b/.example/net/ghttp/server/form/form.html deleted file mode 100644 index 2619de805..000000000 --- a/.example/net/ghttp/server/form/form.html +++ /dev/null @@ -1,30 +0,0 @@ - - - - form test - - -

form1

-
-

-

-

-

-

-

-

-

-

- -
- -

form2

-
-

-

-

-

-

- -
- \ No newline at end of file diff --git a/.example/net/ghttp/server/hello.go b/.example/net/ghttp/server/hello.go deleted file mode 100644 index 98bb79771..000000000 --- a/.example/net/ghttp/server/hello.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Write("Hello World") - }) - s.SetPort(8999) - s.Run() -} diff --git a/.example/net/ghttp/server/hooks/cors1.go b/.example/net/ghttp/server/hooks/cors1.go deleted file mode 100644 index 352bac573..000000000 --- a/.example/net/ghttp/server/hooks/cors1.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func Order(r *ghttp.Request) { - r.Response.Write("GET") -} - -func main() { - s := g.Server() - s.Group("/api.v1", func(group *ghttp.RouterGroup) { - g.GET("/order", Order) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/hooks/cors2.go b/.example/net/ghttp/server/hooks/cors2.go deleted file mode 100644 index dfa1d170b..000000000 --- a/.example/net/ghttp/server/hooks/cors2.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func Order(r *ghttp.Request) { - r.Response.Write("GET") -} - -func main() { - s := g.Server() - s.Group("/api.v1", func(group *ghttp.RouterGroup) { - group.Hook("/*any", ghttp.HookBeforeServe, func(r *ghttp.Request) { - r.Response.CORSDefault() - }) - g.GET("/order", Order) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/hooks/hooks1.go b/.example/net/ghttp/server/hooks/hooks1.go deleted file mode 100644 index 817a11eca..000000000 --- a/.example/net/ghttp/server/hooks/hooks1.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - // 基本事件回调使用 - p := "/:name/info/{uid}" - s := g.Server() - s.BindHookHandlerByMap(p, map[string]ghttp.HandlerFunc{ - ghttp.HookBeforeServe: func(r *ghttp.Request) { glog.Print(ghttp.HookBeforeServe) }, - ghttp.HookAfterServe: func(r *ghttp.Request) { glog.Print(ghttp.HookAfterServe) }, - ghttp.HookBeforeOutput: func(r *ghttp.Request) { glog.Print(ghttp.HookBeforeOutput) }, - ghttp.HookAfterOutput: func(r *ghttp.Request) { glog.Print(ghttp.HookAfterOutput) }, - }) - s.BindHandler(p, func(r *ghttp.Request) { - r.Response.Write("用户:", r.Get("name"), ", uid:", r.Get("uid")) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/hooks/hooks4.go b/.example/net/ghttp/server/hooks/hooks4.go deleted file mode 100644 index b13b8de69..000000000 --- a/.example/net/ghttp/server/hooks/hooks4.go +++ /dev/null @@ -1,36 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - // 多事件回调示例,事件1 - pattern1 := "/:name/info" - s.BindHookHandlerByMap(pattern1, map[string]ghttp.HandlerFunc{ - ghttp.HookBeforeServe: func(r *ghttp.Request) { - r.SetParam("uid", 1000) - }, - }) - s.BindHandler(pattern1, func(r *ghttp.Request) { - r.Response.Write("用户:", r.Get("name"), ", uid:", r.Get("uid")) - }) - - // 多事件回调示例,事件2 - pattern2 := "/{object}/list/{page}.java" - s.BindHookHandlerByMap(pattern2, map[string]ghttp.HandlerFunc{ - ghttp.HookBeforeOutput: func(r *ghttp.Request) { - r.Response.SetBuffer([]byte( - fmt.Sprintf("通过事件修改输出内容, object:%s, page:%s", r.Get("object"), r.GetRouterString("page"))), - ) - }, - }) - s.BindHandler(pattern2, func(r *ghttp.Request) { - r.Response.Write(r.Router.Uri) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/hooks/hooks5.go b/.example/net/ghttp/server/hooks/hooks5.go deleted file mode 100644 index c61a6b167..000000000 --- a/.example/net/ghttp/server/hooks/hooks5.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHookHandler("/*any", ghttp.HookBeforeServe, func(r *ghttp.Request) { - r.Response.Writeln("/*any") - }) - s.BindHookHandler("/v1/*", ghttp.HookBeforeServe, func(r *ghttp.Request) { - r.Response.Writeln("/v1/*") - r.ExitHook() - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/hooks/hooks_param.go b/.example/net/ghttp/server/hooks/hooks_param.go deleted file mode 100644 index 2670e276a..000000000 --- a/.example/net/ghttp/server/hooks/hooks_param.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln(r.Get("name")) - }) - s.BindHookHandlerByMap("/", map[string]ghttp.HandlerFunc{ - ghttp.HookBeforeServe: func(r *ghttp.Request) { - r.SetParam("name", "john") - }, - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/hooks/same_route_multi_hook.go b/.example/net/ghttp/server/hooks/same_route_multi_hook.go deleted file mode 100644 index bd448bcb2..000000000 --- a/.example/net/ghttp/server/hooks/same_route_multi_hook.go +++ /dev/null @@ -1,31 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/priority/show", func(r *ghttp.Request) { - r.Response.Writeln("priority service") - }) - - s.BindHookHandlerByMap("/priority/:name", map[string]ghttp.HandlerFunc{ - ghttp.HookBeforeServe: func(r *ghttp.Request) { - r.Response.Writeln("/priority/:name") - }, - }) - s.BindHookHandlerByMap("/priority/*any", map[string]ghttp.HandlerFunc{ - ghttp.HookBeforeServe: func(r *ghttp.Request) { - r.Response.Writeln("/priority/*any") - }, - }) - s.BindHookHandlerByMap("/priority/show", map[string]ghttp.HandlerFunc{ - ghttp.HookBeforeServe: func(r *ghttp.Request) { - r.Response.Writeln("/priority/show") - }, - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/https/https.go b/.example/net/ghttp/server/https/https.go deleted file mode 100644 index 5ccb9ab49..000000000 --- a/.example/net/ghttp/server/https/https.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln("来自于HTTPS的:哈喽世界!") - }) - s.EnableHTTPS("./server.crt", "./server.key") - s.SetAccessLogEnabled(true) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/https/https_http.go b/.example/net/ghttp/server/https/https_http.go deleted file mode 100644 index dc5c3ff0e..000000000 --- a/.example/net/ghttp/server/https/https_http.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln("您可以同时通过HTTP和HTTPS方式看到该内容!") - }) - s.EnableHTTPS("./server.crt", "./server.key") - s.SetHTTPSPort(8100, 8200) - s.SetPort(8300, 8400) - s.EnableAdmin() - s.Run() -} diff --git a/.example/net/ghttp/server/https/server.crt b/.example/net/ghttp/server/https/server.crt deleted file mode 100644 index 4d254ea21..000000000 --- a/.example/net/ghttp/server/https/server.crt +++ /dev/null @@ -1,23 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDzzCCAregAwIBAgIJAJYpWLkC2lEXMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNV -BAYTAkNIMRAwDgYDVQQIDAdTaUNodWFuMRAwDgYDVQQHDAdDaGVuZ2R1MRAwDgYD -VQQKDAdKb2huLmNuMQwwCgYDVQQLDANEZXYxDTALBgNVBAMMBEpvaG4xHDAaBgkq -hkiG9w0BCQEWDWpvaG5Aam9obmcuY24wHhcNMTgwNDIzMTMyNjA4WhcNMTkwNDIz -MTMyNjA4WjB+MQswCQYDVQQGEwJDSDEQMA4GA1UECAwHU2lDaHVhbjEQMA4GA1UE -BwwHQ2hlbmdkdTEQMA4GA1UECgwHSm9obi5jbjEMMAoGA1UECwwDRGV2MQ0wCwYD -VQQDDARKb2huMRwwGgYJKoZIhvcNAQkBFg1qb2huQGpvaG5nLmNuMIIBIjANBgkq -hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6cngPUrDgBhiNfn+7MMHPzOoO+oVavlS -F/tCPyKINhsePGqHkR4ILkHu9IuoBiPYR1JgrMz5goQ6mkrvq/LMfo4dCuA29ZRg -+Vps/RimBpiz+RU3FDGyqc7d+fk74dElGk6NhJJ6XO3qHqgIg1yc6d5DiZfEnlMz -CRKoZ2dQ+98o5LwES+XJBVWfZiC1pEfyppIh+ci7fXajxkRPJ+5qYWaS5cIHmJIN -DIp5Ypszg1cPs0gIr5EgPeGwZzOeqMMzsbLLE8kjSw59Pt1/+Jkdm1e0GhO18qIO -NcqaHeGaTUVjzX9XwRj8cw+q3kRoqD5aWMjUzAg9+IDrMqvo6VZQ5QIDAQABo1Aw -TjAdBgNVHQ4EFgQU1/tUQpOK0xEwLLlYDiNrckqPlDowHwYDVR0jBBgwFoAU1/tU -QpOK0xEwLLlYDiNrckqPlDowDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC -AQEA5MbG2xU3s/GDU1MV4f0wKhWCNhXfrLaYSwNYGT/eb8ZG2iHSTO0dvl0+pjO2 -EK63PDMvMhUtL1Zlyvl+OqssYcDhVfDzdFoYX6TZNbYxFwSzcx78mO6boAADk9ro -GEQWN+VHsl984SzBRZRJbtNbiw5iVuPruofeKHrrk4dLMiCsStyUaz9lUZxjo2Fi -vVJOY+mRNOBqz1HgU2+RilFTl04zWadCWPJMugQSgJcUPgxRXQ96PkC8uYevEnmR -2DUReSRULIOYEjHw0DZ6yGlqUkJcUGge3XAQEx3LlCpJasOC8Xpsh5i6WBnDPbMh -kPBjRRTooSrJOQJC5v3QW+0Kgw== ------END CERTIFICATE----- diff --git a/.example/net/ghttp/server/https/server.key b/.example/net/ghttp/server/https/server.key deleted file mode 100644 index e0f909629..000000000 --- a/.example/net/ghttp/server/https/server.key +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEA6cngPUrDgBhiNfn+7MMHPzOoO+oVavlSF/tCPyKINhsePGqH -kR4ILkHu9IuoBiPYR1JgrMz5goQ6mkrvq/LMfo4dCuA29ZRg+Vps/RimBpiz+RU3 -FDGyqc7d+fk74dElGk6NhJJ6XO3qHqgIg1yc6d5DiZfEnlMzCRKoZ2dQ+98o5LwE -S+XJBVWfZiC1pEfyppIh+ci7fXajxkRPJ+5qYWaS5cIHmJINDIp5Ypszg1cPs0gI -r5EgPeGwZzOeqMMzsbLLE8kjSw59Pt1/+Jkdm1e0GhO18qIONcqaHeGaTUVjzX9X -wRj8cw+q3kRoqD5aWMjUzAg9+IDrMqvo6VZQ5QIDAQABAoIBAHF7cMHPvL49F88j -nr7GnIntRUhwBB19EIBbknibBotc9nxVKaEjds0dbCSAdfslAyL7tbmrdaIJFXk3 -zsckgGceDLLuyz7B26CuaCEjCdRB43qQ9b9zsEoFBHMGrC6dGul+H+uuPn9FbVOc -NSWumuxa22W6qdJAiJFq4RvwZrsbVnYs5V29Y4Y20IlVUj3siJpAny//UUHequW9 -A/U7RvVssDsEEbbKvCpfcS7STNJKU7GlgV5l5hMKN2xLs1bVG5OKiZN82Zh9r7e1 -m2irxu/ehu6rENxZN0gsfPE4vqoQpbRMNAJlCfq9a3k0PH0TOy5oOVJXPGTIDQab -E3PeAwECgYEA9wh4+bPgMuO04hsAqsoO0DJ9Cwa+BzoDPYOvENobDzmcMErSDLKb -ekl1ej+fBTHRHVaBkuOf/9neLjhjMLad1B+I5gLksqwoMh87odDRCCpkO/B20ln8 -IN6RFiMiNjOaZqjPCCUobgzjbaIz3I69lCQQnMNPwjllSgZs9Lh/PjUCgYEA8kZU -hhUN6ctHIo8ocnmqa4AUPbt2l4qOoBGHCMmhjthyft6g8y6cQlACVJzbco37MhjY -uCOhhOClyUS1tyfds3NXdzAxXPl8SwQJGvl3zqkDQG7/GhCh6AzvHhZR8u7UaweC -kVnAG87Ck6Qqo5ZNbjhMIUm0ujm2cdVd3vyV3fECgYEAmJSMHDck8GnCzLE+/T5m -XeQBZfEZKF+FptYSKId+lS3RMebUzHD5JVQAEqz/LHczoTpQOAkORzorSEMdyPXS -kDWWGfOJjG5XOXYfH/hZVADS/k6tJYnc9/RgitrSg8XlxSjZDz/cM/UT+CBqhf1I -TRrlg94DAoTu8gT8AT9/oE0CgYB5CSPO/JO/2jtGi6iUUC4QmKMEGDRuDt2kID2K -6ViaCY5hzY0xEHcmNdyEMvz7JO16oKkcjUhzHtwUSgxSXUtIDHaE6AGxRj6PJ4v4 -+uqcxxkFxq4Rcn/Acz2+lT4JlMFwWwci4Gi2O7w/kENxCHTUfLGj67OrWYvJIORN -s3iXsQKBgD1I+v+simBvKZKmozzv99EgGfxkRxmrUQsclg1V8a1VTNfE5X9oNaE5 -kjp+dTnwbtmFl3SHVdFUzX/L6FvQIQ9FIwWI2bsszPm4rw8FBeOvH+8lXwVhCwPs -y9him/PhdjBPX0zydDI+h+fmrxH/XbmryZcq1rNmEtFRHBsUs5jg ------END RSA PRIVATE KEY----- diff --git a/.example/net/ghttp/server/https/server.key.public b/.example/net/ghttp/server/https/server.key.public deleted file mode 100644 index e0f909629..000000000 --- a/.example/net/ghttp/server/https/server.key.public +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEA6cngPUrDgBhiNfn+7MMHPzOoO+oVavlSF/tCPyKINhsePGqH -kR4ILkHu9IuoBiPYR1JgrMz5goQ6mkrvq/LMfo4dCuA29ZRg+Vps/RimBpiz+RU3 -FDGyqc7d+fk74dElGk6NhJJ6XO3qHqgIg1yc6d5DiZfEnlMzCRKoZ2dQ+98o5LwE -S+XJBVWfZiC1pEfyppIh+ci7fXajxkRPJ+5qYWaS5cIHmJINDIp5Ypszg1cPs0gI -r5EgPeGwZzOeqMMzsbLLE8kjSw59Pt1/+Jkdm1e0GhO18qIONcqaHeGaTUVjzX9X -wRj8cw+q3kRoqD5aWMjUzAg9+IDrMqvo6VZQ5QIDAQABAoIBAHF7cMHPvL49F88j -nr7GnIntRUhwBB19EIBbknibBotc9nxVKaEjds0dbCSAdfslAyL7tbmrdaIJFXk3 -zsckgGceDLLuyz7B26CuaCEjCdRB43qQ9b9zsEoFBHMGrC6dGul+H+uuPn9FbVOc -NSWumuxa22W6qdJAiJFq4RvwZrsbVnYs5V29Y4Y20IlVUj3siJpAny//UUHequW9 -A/U7RvVssDsEEbbKvCpfcS7STNJKU7GlgV5l5hMKN2xLs1bVG5OKiZN82Zh9r7e1 -m2irxu/ehu6rENxZN0gsfPE4vqoQpbRMNAJlCfq9a3k0PH0TOy5oOVJXPGTIDQab -E3PeAwECgYEA9wh4+bPgMuO04hsAqsoO0DJ9Cwa+BzoDPYOvENobDzmcMErSDLKb -ekl1ej+fBTHRHVaBkuOf/9neLjhjMLad1B+I5gLksqwoMh87odDRCCpkO/B20ln8 -IN6RFiMiNjOaZqjPCCUobgzjbaIz3I69lCQQnMNPwjllSgZs9Lh/PjUCgYEA8kZU -hhUN6ctHIo8ocnmqa4AUPbt2l4qOoBGHCMmhjthyft6g8y6cQlACVJzbco37MhjY -uCOhhOClyUS1tyfds3NXdzAxXPl8SwQJGvl3zqkDQG7/GhCh6AzvHhZR8u7UaweC -kVnAG87Ck6Qqo5ZNbjhMIUm0ujm2cdVd3vyV3fECgYEAmJSMHDck8GnCzLE+/T5m -XeQBZfEZKF+FptYSKId+lS3RMebUzHD5JVQAEqz/LHczoTpQOAkORzorSEMdyPXS -kDWWGfOJjG5XOXYfH/hZVADS/k6tJYnc9/RgitrSg8XlxSjZDz/cM/UT+CBqhf1I -TRrlg94DAoTu8gT8AT9/oE0CgYB5CSPO/JO/2jtGi6iUUC4QmKMEGDRuDt2kID2K -6ViaCY5hzY0xEHcmNdyEMvz7JO16oKkcjUhzHtwUSgxSXUtIDHaE6AGxRj6PJ4v4 -+uqcxxkFxq4Rcn/Acz2+lT4JlMFwWwci4Gi2O7w/kENxCHTUfLGj67OrWYvJIORN -s3iXsQKBgD1I+v+simBvKZKmozzv99EgGfxkRxmrUQsclg1V8a1VTNfE5X9oNaE5 -kjp+dTnwbtmFl3SHVdFUzX/L6FvQIQ9FIwWI2bsszPm4rw8FBeOvH+8lXwVhCwPs -y9him/PhdjBPX0zydDI+h+fmrxH/XbmryZcq1rNmEtFRHBsUs5jg ------END RSA PRIVATE KEY----- diff --git a/.example/net/ghttp/server/log/config.toml b/.example/net/ghttp/server/log/config.toml deleted file mode 100644 index 32a428e4d..000000000 --- a/.example/net/ghttp/server/log/config.toml +++ /dev/null @@ -1,7 +0,0 @@ -[server] - LogPath = "/tmp/gflog/server" - LogStdout = true - ErrorLogEnabled = true - ErrorLogPattern = "error.log" - AccessLogEnabled = true - AccessLogPattern = "access.log" \ No newline at end of file diff --git a/.example/net/ghttp/server/log/log.go b/.example/net/ghttp/server/log/log.go deleted file mode 100644 index 613a2c881..000000000 --- a/.example/net/ghttp/server/log/log.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "net/http" -) - -func main() { - s := g.Server() - s.Group("/", func(group *ghttp.RouterGroup) { - group.ALL("/", func(r *ghttp.Request) { - r.Response.Write("halo world!") - }) - group.ALL("/log/handler", func(r *ghttp.Request) { - r.Response.WriteStatus(http.StatusNotFound, "File Not Found!") - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/log/log_error.go b/.example/net/ghttp/server/log/log_error.go deleted file mode 100644 index 727592f21..000000000 --- a/.example/net/ghttp/server/log/log_error.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := ghttp.GetServer() - s.BindHandler("/log/error", func(r *ghttp.Request) { - panic("OMG") - }) - s.SetErrorLogEnabled(true) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/middleware/auth.go b/.example/net/ghttp/server/middleware/auth.go deleted file mode 100644 index d4d4efdfd..000000000 --- a/.example/net/ghttp/server/middleware/auth.go +++ /dev/null @@ -1,34 +0,0 @@ -package main - -import ( - "net/http" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func MiddlewareAuth(r *ghttp.Request) { - token := r.Get("token") - if token == "123456" { - r.Middleware.Next() - } else { - r.Response.WriteStatus(http.StatusForbidden) - } -} - -func MiddlewareCORS(r *ghttp.Request) { - r.Response.CORSDefault() - r.Middleware.Next() -} - -func main() { - s := g.Server() - s.Group("/api.v2", func(group *ghttp.RouterGroup) { - group.Middleware(MiddlewareAuth, MiddlewareCORS) - group.ALL("/user/list", func(r *ghttp.Request) { - r.Response.Write("list") - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/middleware/auth_exception.go b/.example/net/ghttp/server/middleware/auth_exception.go deleted file mode 100644 index 2dbfbcc4f..000000000 --- a/.example/net/ghttp/server/middleware/auth_exception.go +++ /dev/null @@ -1,41 +0,0 @@ -package main - -import ( - "net/http" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func MiddlewareAuth(r *ghttp.Request) { - token := r.Get("token") - if token == "123456" { - r.Middleware.Next() - } else { - r.Response.WriteStatus(http.StatusForbidden) - } -} - -func main() { - s := g.Server() - s.Group("/admin", func(group *ghttp.RouterGroup) { - group.Middleware(func(r *ghttp.Request) { - if action := r.GetRouterString("action"); action != "" { - switch action { - case "login": - r.Middleware.Next() - return - } - } - MiddlewareAuth(r) - }) - group.ALL("/login", func(r *ghttp.Request) { - r.Response.Write("login") - }) - group.ALL("/dashboard", func(r *ghttp.Request) { - r.Response.Write("dashboard") - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/middleware/cors.go b/.example/net/ghttp/server/middleware/cors.go deleted file mode 100644 index 761d7f458..000000000 --- a/.example/net/ghttp/server/middleware/cors.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func MiddlewareCORS(r *ghttp.Request) { - r.Response.CORSDefault() - r.Middleware.Next() -} - -func main() { - s := g.Server() - s.Group("/api.v2", func(group *ghttp.RouterGroup) { - group.Middleware(MiddlewareCORS) - group.ALL("/user/list", func(r *ghttp.Request) { - r.Response.Write("list") - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/middleware/error_handling.go b/.example/net/ghttp/server/middleware/error_handling.go deleted file mode 100644 index 9eee48fe3..000000000 --- a/.example/net/ghttp/server/middleware/error_handling.go +++ /dev/null @@ -1,42 +0,0 @@ -package main - -import ( - "net/http" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func MiddlewareAuth(r *ghttp.Request) { - token := r.Get("token") - if token == "123456" { - r.Middleware.Next() - } else { - r.Response.WriteStatus(http.StatusForbidden) - } -} - -func MiddlewareCORS(r *ghttp.Request) { - r.Response.CORSDefault() - r.Middleware.Next() -} - -func MiddlewareError(r *ghttp.Request) { - r.Middleware.Next() - if r.Response.Status >= http.StatusInternalServerError { - r.Response.ClearBuffer() - r.Response.Write("Internal error occurred, please try again later.") - } -} - -func main() { - s := g.Server() - s.Group("/api.v2", func(group *ghttp.RouterGroup) { - group.Middleware(MiddlewareAuth, MiddlewareCORS, MiddlewareError) - group.ALL("/user/list", func(r *ghttp.Request) { - panic("db error: sql is xxxxxxx") - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/middleware/issue355.go b/.example/net/ghttp/server/middleware/issue355.go deleted file mode 100644 index 048530a70..000000000 --- a/.example/net/ghttp/server/middleware/issue355.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindMiddlewareDefault(func(r *ghttp.Request) { - fmt.Println("cors") - r.Response.CORSDefault() - r.Middleware.Next() - }) - s.BindHandler("/api/captcha", func(r *ghttp.Request) { - r.Response.Write("captcha") - }) - s.SetPort(8010) - s.Run() -} diff --git a/.example/net/ghttp/server/middleware/log.go b/.example/net/ghttp/server/middleware/log.go deleted file mode 100644 index 09869d7ad..000000000 --- a/.example/net/ghttp/server/middleware/log.go +++ /dev/null @@ -1,42 +0,0 @@ -package main - -import ( - "net/http" - - "github.com/gogf/gf/v2/os/glog" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func MiddlewareAuth(r *ghttp.Request) { - token := r.Get("token") - if token == "123456" { - r.Middleware.Next() - } else { - r.Response.WriteStatus(http.StatusForbidden) - } -} - -func MiddlewareCORS(r *ghttp.Request) { - r.Response.CORSDefault() - r.Middleware.Next() -} - -func MiddlewareLog(r *ghttp.Request) { - r.Middleware.Next() - g.Log().Print(r.Response.Status, r.URL.Path) -} - -func main() { - s := g.Server() - s.Use(MiddlewareLog) - s.Group("/api.v2", func(group *ghttp.RouterGroup) { - group.Middleware(MiddlewareAuth, MiddlewareCORS) - group.ALL("/user/list", func(r *ghttp.Request) { - panic("custom error") - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/middleware/middleware.go b/.example/net/ghttp/server/middleware/middleware.go deleted file mode 100644 index 7ebad3f37..000000000 --- a/.example/net/ghttp/server/middleware/middleware.go +++ /dev/null @@ -1,40 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.Group("/api.v2", func(group *ghttp.RouterGroup) { - group.Middleware(func(r *ghttp.Request) { - r.Response.Write("start") - r.Middleware.Next() - r.Response.Write("end") - }) - group.Group("/order", func(group *ghttp.RouterGroup) { - group.GET("/list", func(r *ghttp.Request) { - r.Response.Write("list") - }) - }) - group.Group("/user", func(group *ghttp.RouterGroup) { - group.GET("/info", func(r *ghttp.Request) { - r.Response.Write("info") - }) - group.POST("/edit", func(r *ghttp.Request) { - r.Response.Write("edit") - }) - }) - group.Group("/hook", func(group *ghttp.RouterGroup) { - group.Hook("/*", ghttp.HookBeforeServe, func(r *ghttp.Request) { - r.Response.Write("hook any") - }) - group.Hook("/:name", ghttp.HookBeforeServe, func(r *ghttp.Request) { - r.Response.Write("hook name") - }) - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/middleware/param.go b/.example/net/ghttp/server/middleware/param.go deleted file mode 100644 index 385db1d96..000000000 --- a/.example/net/ghttp/server/middleware/param.go +++ /dev/null @@ -1,36 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -// 前置中间件1 -func MiddlewareBefore1(r *ghttp.Request) { - r.SetParam("name", "GoFrame") - r.Response.Writeln("set name") - r.Middleware.Next() -} - -// 前置中间件2 -func MiddlewareBefore2(r *ghttp.Request) { - r.SetParam("site", "https://goframe.org") - r.Response.Writeln("set site") - r.Middleware.Next() -} - -func main() { - s := g.Server() - s.Group("/", func(group *ghttp.RouterGroup) { - group.Middleware(MiddlewareBefore1, MiddlewareBefore2) - group.ALL("/", func(r *ghttp.Request) { - r.Response.Writefln( - "%s: %s", - r.GetParamVar("name").String(), - r.GetParamVar("site").String(), - ) - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/name.go b/.example/net/ghttp/server/name.go deleted file mode 100644 index fc5d5499b..000000000 --- a/.example/net/ghttp/server/name.go +++ /dev/null @@ -1,41 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -type User struct{} - -func (u *User) ShowList(r *ghttp.Request) { - r.Response.Write("list") -} - -func main() { - s1 := g.Server(1) - s2 := g.Server(2) - s3 := g.Server(3) - s4 := g.Server(4) - - s1.SetNameToUriType(ghttp.URI_TYPE_DEFAULT) - s2.SetNameToUriType(ghttp.URI_TYPE_FULLNAME) - s3.SetNameToUriType(ghttp.URI_TYPE_ALLLOWER) - s4.SetNameToUriType(ghttp.URI_TYPE_CAMEL) - - s1.BindObject("/{.struct}/{.method}", new(User)) - s2.BindObject("/{.struct}/{.method}", new(User)) - s3.BindObject("/{.struct}/{.method}", new(User)) - s4.BindObject("/{.struct}/{.method}", new(User)) - - s1.SetPort(8100) - s2.SetPort(8200) - s3.SetPort(8300) - s4.SetPort(8400) - - s1.Start() - s2.Start() - s3.Start() - s4.Start() - - g.Wait() -} diff --git a/.example/net/ghttp/server/nethttp_server.go b/.example/net/ghttp/server/nethttp_server.go deleted file mode 100644 index ec30e5608..000000000 --- a/.example/net/ghttp/server/nethttp_server.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "net/http" - "time" -) - -func main() { - s := &http.Server{ - Addr: ":8199", - ReadTimeout: 2 * time.Second, - WriteTimeout: 2 * time.Second, - } - http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("hi")) - time.Sleep(3 * time.Second) - }) - s.ListenAndServe() -} diff --git a/.example/net/ghttp/server/object/user.go b/.example/net/ghttp/server/object/user.go deleted file mode 100644 index 89215b840..000000000 --- a/.example/net/ghttp/server/object/user.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -type User struct{} - -func (c *User) Test(r *ghttp.Request) { - r.Response.Write("Test") -} - -func main() { - s := g.Server() - u := new(User) - s.Group("/", func(group *ghttp.RouterGroup) { - group.GET("/db-{table}/{id}", u, "Test") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/openapi/openapi.go b/.example/net/ghttp/server/openapi/openapi.go deleted file mode 100644 index 1cad75843..000000000 --- a/.example/net/ghttp/server/openapi/openapi.go +++ /dev/null @@ -1,33 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -type HelloReq struct { - g.Meta `path:"/hello" tags:"Test" method:"get" description:"Hello world handler for test"` - Content string `json:"content" in:"query"` -} - -type HelloRes struct { - Content string `json:"content" description:"Hello response content for test"` -} - -// Hello is an example handler. -func Hello(ctx context.Context, req *HelloReq) (res *HelloRes, err error) { - return &HelloRes{Content: req.Content}, nil -} - -func main() { - s := g.Server() - s.Use( - ghttp.MiddlewareHandlerResponse, - ) - s.BindHandler("/hello", Hello) - s.SetOpenApiPath("/api.json") - s.SetSwaggerPath("/swagger") - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/ports.go b/.example/net/ghttp/server/ports.go deleted file mode 100644 index dfb187c66..000000000 --- a/.example/net/ghttp/server/ports.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := ghttp.GetServer() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln("go frame!") - }) - s.SetPort(8100, 8200, 8300) - s.Run() -} diff --git a/.example/net/ghttp/server/pprof.go b/.example/net/ghttp/server/pprof.go deleted file mode 100644 index 800f098f0..000000000 --- a/.example/net/ghttp/server/pprof.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.Domain("localhost").EnablePProf() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln("哈喽世界!") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/redirect/redirect_back.go b/.example/net/ghttp/server/redirect/redirect_back.go deleted file mode 100644 index 2e2f93e15..000000000 --- a/.example/net/ghttp/server/redirect/redirect_back.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/page", func(r *ghttp.Request) { - r.Response.Writeln(`back`) - }) - s.BindHandler("/back", func(r *ghttp.Request) { - r.Response.RedirectBack() - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/redirect/redirect_to.go b/.example/net/ghttp/server/redirect/redirect_to.go deleted file mode 100644 index b67b5a3c6..000000000 --- a/.example/net/ghttp/server/redirect/redirect_to.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.RedirectTo("/login") - }) - s.BindHandler("/login", func(r *ghttp.Request) { - r.Response.Writeln("Login First") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/reload/admin.go b/.example/net/ghttp/server/reload/admin.go deleted file mode 100644 index eff842a5a..000000000 --- a/.example/net/ghttp/server/reload/admin.go +++ /dev/null @@ -1,13 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - s := g.Server() - s.SetConfigWithMap(g.Map{"Graceful": true}) - s.EnableAdmin() - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/reload/https.go b/.example/net/ghttp/server/reload/https.go deleted file mode 100644 index ace087ee6..000000000 --- a/.example/net/ghttp/server/reload/https.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln("哈罗!") - }) - s.EnableHTTPS("/home/john/temp/server.crt", "/home/john/temp/server.key") - s.EnableAdmin() - s.SetPort(8200) - s.Run() -} diff --git a/.example/net/ghttp/server/reload/https_http.go b/.example/net/ghttp/server/reload/https_http.go deleted file mode 100644 index b0e8de1e8..000000000 --- a/.example/net/ghttp/server/reload/https_http.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := ghttp.GetServer() - s.EnableAdmin() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln("您可以同时通过HTTP和HTTPS方式看到该内容!") - }) - s.EnableHTTPS("/home/john/temp/server.crt", "/home/john/temp/server.key") - s.SetHTTPSPort(8198, 8199) - s.SetPort(8200, 8300) - s.EnableAdmin() - s.Run() -} diff --git a/.example/net/ghttp/server/reload/multi_port_and_server.go b/.example/net/ghttp/server/reload/multi_port_and_server.go deleted file mode 100644 index e6c4b5233..000000000 --- a/.example/net/ghttp/server/reload/multi_port_and_server.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - s1 := g.Server("s1") - s1.EnableAdmin() - s1.SetPort(8100, 8200) - s1.Start() - - s2 := g.Server("s2") - s2.EnableAdmin() - s2.SetPort(8300, 8400) - s2.Start() - - g.Wait() -} diff --git a/.example/net/ghttp/server/reload/simple.go b/.example/net/ghttp/server/reload/simple.go deleted file mode 100644 index a5b06250b..000000000 --- a/.example/net/ghttp/server/reload/simple.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gproc" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln("哈喽!") - }) - s.BindHandler("/pid", func(r *ghttp.Request) { - r.Response.Writeln(gproc.Pid()) - }) - s.BindHandler("/sleep", func(r *ghttp.Request) { - r.Response.Writeln(gproc.Pid()) - time.Sleep(10 * time.Second) - r.Response.Writeln(gproc.Pid()) - }) - s.EnableAdmin() - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/basic.go b/.example/net/ghttp/server/request/basic.go deleted file mode 100644 index 3c4aedf28..000000000 --- a/.example/net/ghttp/server/request/basic.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln(r.Get("amount")) - r.Response.Writeln(r.GetInt("amount")) - r.Response.Writeln(r.GetFloat32("amount")) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/exit/exit.go b/.example/net/ghttp/server/request/exit/exit.go deleted file mode 100644 index 57d43e0d2..000000000 --- a/.example/net/ghttp/server/request/exit/exit.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - if r.GetInt("type") == 1 { - r.Response.Writeln("john") - } - r.Response.Writeln("smith") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/json-xml/test1.go b/.example/net/ghttp/server/request/json-xml/test1.go deleted file mode 100644 index aabe06e5a..000000000 --- a/.example/net/ghttp/server/request/json-xml/test1.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writef("name: %v, pass: %v", r.Get("name"), r.Get("pass")) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/json-xml/test2.go b/.example/net/ghttp/server/request/json-xml/test2.go deleted file mode 100644 index 21b8de109..000000000 --- a/.example/net/ghttp/server/request/json-xml/test2.go +++ /dev/null @@ -1,47 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/util/gvalid" -) - -type RegisterReq struct { - Name string `p:"username" v:"required|length:6,30#请输入账号|账号长度为:min到:max位"` - Pass string `p:"password1" v:"required|length:6,30#请输入密码|密码长度不够"` - Pass2 string `p:"password2" v:"required|length:6,30|same:password1#请确认密码|两次密码不一致"` -} - -type RegisterRes struct { - Code int `json:"code"` - Error string `json:"error"` - Data interface{} `json:"data"` -} - -func main() { - s := g.Server() - s.BindHandler("/register", func(r *ghttp.Request) { - var req *RegisterReq - //fmt.Println(r.GetBody()) - if err := r.Parse(&req); err != nil { - // Validation error. - if v, ok := err.(gvalid.Error); ok { - r.Response.WriteJsonExit(RegisterRes{ - Code: 1, - Error: v.FirstString(), - }) - } - // Other error. - r.Response.WriteJsonExit(RegisterRes{ - Code: 1, - Error: err.Error(), - }) - } - // ... - r.Response.WriteJsonExit(RegisterRes{ - Data: req, - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/params/array.go b/.example/net/ghttp/server/request/params/array.go deleted file mode 100644 index 36ba6055f..000000000 --- a/.example/net/ghttp/server/request/params/array.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Write(r.Get("array")) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/params/map.go b/.example/net/ghttp/server/request/params/map.go deleted file mode 100644 index bc913ae33..000000000 --- a/.example/net/ghttp/server/request/params/map.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Write(r.Get("map")) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/params/repeat.go b/.example/net/ghttp/server/request/params/repeat.go deleted file mode 100644 index ba8f18e63..000000000 --- a/.example/net/ghttp/server/request/params/repeat.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Write(r.Get("name")) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/priority.go b/.example/net/ghttp/server/request/priority.go deleted file mode 100644 index 93ced6777..000000000 --- a/.example/net/ghttp/server/request/priority.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/input", func(r *ghttp.Request) { - r.Response.Writeln(r.Get("amount")) - }) - s.BindHandler("/query", func(r *ghttp.Request) { - r.Response.Writeln(r.GetQuery("amount")) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/request_struct.go b/.example/net/ghttp/server/request/request_struct.go deleted file mode 100644 index dfc15e349..000000000 --- a/.example/net/ghttp/server/request/request_struct.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - type User struct { - Uid int `json:"uid"` - Name string `json:"name" p:"username"` - Pass1 string `json:"pass1" p:"password1"` - Pass2 string `json:"pass2" p:"password2"` - } - - s := g.Server() - s.BindHandler("/user", func(r *ghttp.Request) { - var user *User - if err := r.Parse(&user); err != nil { - panic(err) - } - r.Response.WriteJson(user) - }) - s.SetPort(8199) - s.Run() - - // http://127.0.0.1:8199/user?uid=1&name=john&password1=123&userpass2=123 - // {"name":"john","pass1":"123","pass2":"123","uid":1} -} diff --git a/.example/net/ghttp/server/request/request_validation.go b/.example/net/ghttp/server/request/request_validation.go deleted file mode 100644 index a6ab6185f..000000000 --- a/.example/net/ghttp/server/request/request_validation.go +++ /dev/null @@ -1,41 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/util/gvalid" -) - -type User struct { - Uid int `gvalid:"uid@min:1"` - Name string `params:"username" gvalid:"username @required|length:6,30"` - Pass1 string `params:"password1" gvalid:"password1@required|password3"` - Pass2 string `params:"password2" gvalid:"password2@required|password3|same:password1#||两次密码不一致,请重新输入"` -} - -func main() { - s := g.Server() - s.Group("/", func(rgroup *ghttp.RouterGroup) { - rgroup.ALL("/user", func(r *ghttp.Request) { - user := new(User) - if err := r.GetStruct(user); err != nil { - r.Response.WriteJsonExit(g.Map{ - "message": err, - "errcode": 1, - }) - } - if err := gvalid.CheckStruct(r.Context(), user, nil); err != nil { - r.Response.WriteJsonExit(g.Map{ - "message": err.Maps(), - "errcode": 1, - }) - } - r.Response.WriteJsonExit(g.Map{ - "message": "ok", - "errcode": 0, - }) - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/struct/parse1.go b/.example/net/ghttp/server/request/struct/parse1.go deleted file mode 100644 index f00d79c81..000000000 --- a/.example/net/ghttp/server/request/struct/parse1.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - type User struct { - Id int `json:"id"` - Name string `json:"name"` - Pass1 string `json:"password1" p:"password1"` - Pass2 string `json:"password2" p:"password2"` - } - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - var user *User - if err := r.Parse(&user); err != nil { - r.Response.WriteExit(err) - } - r.Response.WriteExit(user) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/struct/parse2.go b/.example/net/ghttp/server/request/struct/parse2.go deleted file mode 100644 index 8d5f19786..000000000 --- a/.example/net/ghttp/server/request/struct/parse2.go +++ /dev/null @@ -1,37 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -type RegisterReq struct { - Name string - Pass string `p:"password1"` - Pass2 string `p:"password2"` -} - -type RegisterRes struct { - Code int `json:"code"` - Error string `json:"error"` - Data interface{} `json:"data"` -} - -func main() { - s := g.Server() - s.BindHandler("/register", func(r *ghttp.Request) { - var req *RegisterReq - if err := r.Parse(&req); err != nil { - r.Response.WriteJsonExit(RegisterRes{ - Code: 1, - Error: err.Error(), - }) - } - // ... - r.Response.WriteJsonExit(RegisterRes{ - Data: req, - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/validation/validation1/validation1.go b/.example/net/ghttp/server/request/validation/validation1/validation1.go deleted file mode 100644 index 759115fa1..000000000 --- a/.example/net/ghttp/server/request/validation/validation1/validation1.go +++ /dev/null @@ -1,37 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -type RegisterReq struct { - Name string `p:"username" v:"required|length:6,30#请输入账号|账号长度为:min到:max位"` - Pass string `p:"password1" v:"required|length:6,30#请输入密码|密码长度不够"` - Pass2 string `p:"password2" v:"required|length:6,30|same:password1#请确认密码|两次密码不一致"` -} - -type RegisterRes struct { - Code int `json:"code"` - Error string `json:"error"` - Data interface{} `json:"data"` -} - -func main() { - s := g.Server() - s.BindHandler("/register", func(r *ghttp.Request) { - var req *RegisterReq - if err := r.Parse(&req); err != nil { - r.Response.WriteJsonExit(RegisterRes{ - Code: 1, - Error: err.Error(), - }) - } - // ... - r.Response.WriteJsonExit(RegisterRes{ - Data: req, - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/validation/validation2/validation2.go b/.example/net/ghttp/server/request/validation/validation2/validation2.go deleted file mode 100644 index 93f5d021f..000000000 --- a/.example/net/ghttp/server/request/validation/validation2/validation2.go +++ /dev/null @@ -1,46 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/util/gvalid" -) - -type RegisterReq struct { - Name string `p:"username" v:"required|length:6,30#请输入账号|账号长度为:min到:max位"` - Pass string `p:"password1" v:"required|length:6,30#请输入密码|密码长度不够"` - Pass2 string `p:"password2" v:"required|length:6,30|same:password1#请确认密码|两次密码不一致"` -} - -type RegisterRes struct { - Code int `json:"code"` - Error string `json:"error"` - Data interface{} `json:"data"` -} - -func main() { - s := g.Server() - s.BindHandler("/register", func(r *ghttp.Request) { - var req *RegisterReq - if err := r.Parse(&req); err != nil { - // Validation error. - if v, ok := err.(gvalid.Error); ok { - r.Response.WriteJsonExit(RegisterRes{ - Code: 1, - Error: v.FirstString(), - }) - } - // Other error. - r.Response.WriteJsonExit(RegisterRes{ - Code: 1, - Error: err.Error(), - }) - } - // ... - r.Response.WriteJsonExit(RegisterRes{ - Data: req, - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/resource/resource.go b/.example/net/ghttp/server/resource/resource.go deleted file mode 100644 index c5b63fec9..000000000 --- a/.example/net/ghttp/server/resource/resource.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gres" - _ "github.com/gogf/gf/v2/os/gres/testdata/data" -) - -func main() { - gres.Dump() - - //v := g.View() - //v.SetPath("template/layout1") - - s := g.Server() - s.SetIndexFolder(true) - s.SetServerRoot("root") - s.BindHookHandler("/*", ghttp.HookBeforeServe, func(r *ghttp.Request) { - fmt.Println(r.URL.Path, r.IsFileRequest()) - }) - s.BindHandler("/template", func(r *ghttp.Request) { - r.Response.WriteTpl("layout1/layout.html") - }) - s.SetPort(8198) - s.Run() -} diff --git a/.example/net/ghttp/server/reuseport/reuseport.go b/.example/net/ghttp/server/reuseport/reuseport.go deleted file mode 100644 index a3d3764fa..000000000 --- a/.example/net/ghttp/server/reuseport/reuseport.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - s1 := ghttp.GetServer("s1") - s1.SetPort(8882) - s1.BindHandler("/", func(r *ghttp.Request) { - glog.Print(r.Context(), "s1") - r.Response.Writeln("s1") - }) - s1.Start() - - s2 := ghttp.GetServer("s2") - s2.SetPort(8882) - s2.BindHandler("/", func(r *ghttp.Request) { - glog.Print(r.Context(), "s2") - r.Response.Writeln("s2") - }) - s2.Start() - - g.Wait() -} diff --git a/.example/net/ghttp/server/router/duplicated/duplicated.go b/.example/net/ghttp/server/router/duplicated/duplicated.go deleted file mode 100644 index fb23d03a2..000000000 --- a/.example/net/ghttp/server/router/duplicated/duplicated.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.Group("/", func(group *ghttp.RouterGroup) { - group.ALL("/test", func(r *ghttp.Request) { - r.Response.Writeln(1) - }) - group.ALL("/test", func(r *ghttp.Request) { - r.Response.Writeln(2) - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/router/group/basic.go b/.example/net/ghttp/server/router/group/basic.go deleted file mode 100644 index bd87d6867..000000000 --- a/.example/net/ghttp/server/router/group/basic.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - group := s.Group("/api") - group.ALL("/all", func(r *ghttp.Request) { - r.Response.Write("all") - }) - group.GET("/get", func(r *ghttp.Request) { - r.Response.Write("get") - }) - group.POST("/post", func(r *ghttp.Request) { - r.Response.Write("post") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/router/group/batch.go b/.example/net/ghttp/server/router/group/batch.go deleted file mode 100644 index 185393e7f..000000000 --- a/.example/net/ghttp/server/router/group/batch.go +++ /dev/null @@ -1,38 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -type Object struct{} - -func (o *Object) Show(r *ghttp.Request) { - r.Response.Writeln("Show") -} - -func (o *Object) Delete(r *ghttp.Request) { - r.Response.Writeln("REST Delete") -} - -func Handler(r *ghttp.Request) { - r.Response.Writeln("Handler") -} - -func HookHandler(r *ghttp.Request) { - r.Response.Writeln("HOOK Handler") -} - -func main() { - s := g.Server() - obj := new(Object) - s.Group("/api").Bind([]ghttp.GroupItem{ - {"ALL", "*", HookHandler, ghttp.HookBeforeServe}, - {"ALL", "/handler", Handler}, - {"ALL", "/obj", obj}, - {"GET", "/obj/show", obj, "Show"}, - {"REST", "/obj/rest", obj}, - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/router/group/level.go b/.example/net/ghttp/server/router/group/level.go deleted file mode 100644 index f0563e671..000000000 --- a/.example/net/ghttp/server/router/group/level.go +++ /dev/null @@ -1,67 +0,0 @@ -package main - -import ( - "net/http" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func MiddlewareAuth(r *ghttp.Request) { - token := r.Get("token") - if token == "123456" { - r.Middleware.Next() - } else { - r.Response.WriteStatus(http.StatusForbidden) - } -} - -func MiddlewareCORS(r *ghttp.Request) { - r.Response.CORSDefault() - r.Middleware.Next() -} - -func MiddlewareLog(r *ghttp.Request) { - r.Middleware.Next() - g.Log().Print(r.Response.Status, r.URL.Path) -} - -func main() { - s := g.Server() - s.Use(MiddlewareLog) - s.Group("/api.v2", func(group *ghttp.RouterGroup) { - group.Middleware(MiddlewareAuth, MiddlewareCORS) - group.GET("/test", func(r *ghttp.Request) { - r.Response.Write("test") - }) - group.Group("/order", func(group *ghttp.RouterGroup) { - group.GET("/list", func(r *ghttp.Request) { - r.Response.Write("list") - }) - group.PUT("/update", func(r *ghttp.Request) { - r.Response.Write("update") - }) - }) - group.Group("/user", func(group *ghttp.RouterGroup) { - group.GET("/info", func(r *ghttp.Request) { - r.Response.Write("info") - }) - group.POST("/edit", func(r *ghttp.Request) { - r.Response.Write("edit") - }) - group.DELETE("/drop", func(r *ghttp.Request) { - r.Response.Write("drop") - }) - }) - group.Group("/hook", func(group *ghttp.RouterGroup) { - group.Hook("/*", ghttp.HookBeforeServe, func(r *ghttp.Request) { - r.Response.Write("hook any") - }) - group.Hook("/:name", ghttp.HookBeforeServe, func(r *ghttp.Request) { - r.Response.Write("hook name") - }) - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/router/router1.go b/.example/net/ghttp/server/router/router1.go deleted file mode 100644 index ce2276266..000000000 --- a/.example/net/ghttp/server/router/router1.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/:name", func(r *ghttp.Request) { - r.Response.Writeln(r.Router.Uri) - }) - s.BindHandler("/:name/update", func(r *ghttp.Request) { - r.Response.Writeln(r.Router.Uri) - }) - s.BindHandler("/:name/:action", func(r *ghttp.Request) { - r.Response.Writeln(r.Router.Uri) - }) - s.BindHandler("/:name/*any", func(r *ghttp.Request) { - r.Response.Writeln(r.Router.Uri) - }) - s.BindHandler("/user/list/{field}.html", func(r *ghttp.Request) { - r.Response.Writeln(r.Router.Uri) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/router/router2.go b/.example/net/ghttp/server/router/router2.go deleted file mode 100644 index 3732e8026..000000000 --- a/.example/net/ghttp/server/router/router2.go +++ /dev/null @@ -1,33 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/user/:name", func(r *ghttp.Request) { - r.Response.Writeln(r.Router.Uri) - }) - s.BindHandler("/user/member/:name/*any", func(r *ghttp.Request) { - r.Response.Writeln(r.Router.Uri) - }) - s.BindHandler("/user/member/:name/edit/*any", func(r *ghttp.Request) { - r.Response.Writeln(r.Router.Uri) - }) - s.BindHandler("/user/member/:name/edit/sex", func(r *ghttp.Request) { - r.Response.Writeln(r.Router.Uri) - }) - s.BindHandler("/user/member/:name/edit/info/*any", func(r *ghttp.Request) { - r.Response.Writeln(r.Router.Uri) - }) - s.BindHandler("/user/community/female/:name", func(r *ghttp.Request) { - r.Response.Writeln(r.Router.Uri) - }) - s.BindHandler("/admin/stats/today/:hour", func(r *ghttp.Request) { - r.Response.Writeln(r.Router.Uri) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/router/router3.go b/.example/net/ghttp/server/router/router3.go deleted file mode 100644 index dbf6ba73d..000000000 --- a/.example/net/ghttp/server/router/router3.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - // 一个简单的分页路由示例 - s.BindHandler("/user/list/{page}.html", func(r *ghttp.Request) { - r.Response.Writeln(r.Get("page")) - }) - // {xxx} 规则与 :xxx 规则混合使用 - s.BindHandler("/{object}/:attr/{act}.php", func(r *ghttp.Request) { - r.Response.Writeln(r.Get("object")) - r.Response.Writeln(r.Get("attr")) - r.Response.Writeln(r.Get("act")) - }) - // 多种模糊匹配规则混合使用 - s.BindHandler("/{class}-{course}/:name/*act", func(r *ghttp.Request) { - r.Response.Writeln(r.Get("class")) - r.Response.Writeln(r.Get("course")) - r.Response.Writeln(r.Get("name")) - r.Response.Writeln(r.Get("act")) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/router/router4.go b/.example/net/ghttp/server/router/router4.go deleted file mode 100644 index 3218be3ea..000000000 --- a/.example/net/ghttp/server/router/router4.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - // 该路由规则仅会在GET请求下有效 - s.BindHandler("GET:/{table}/list/{page}.html", func(r *ghttp.Request) { - r.Response.WriteJson(r.Router) - }) - // 该路由规则仅会在GET请求及localhost域名下有效 - s.BindHandler("GET:/order/info/{order_id}@localhost", func(r *ghttp.Request) { - r.Response.WriteJson(r.Router) - }) - // 该路由规则仅会在DELETE请求下有效 - s.BindHandler("DELETE:/comment/{id}", func(r *ghttp.Request) { - r.Response.WriteJson(r.Router) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/router/router5.go b/.example/net/ghttp/server/router/router5.go deleted file mode 100644 index 06664e3b5..000000000 --- a/.example/net/ghttp/server/router/router5.go +++ /dev/null @@ -1,26 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHookHandler("/*any", ghttp.HookBeforeServe, func(r *ghttp.Request) { - fmt.Println(r.Router) - fmt.Println(r.Get("customer_id")) - }) - s.BindHandler("/admin/customer/{customer_id}/edit", func(r *ghttp.Request) { - r.Response.Writeln(r.Get("customer_id")) - r.Response.Writeln(r.Router.Uri) - }) - s.BindHandler("/admin/customer/{customer_id}/disable", func(r *ghttp.Request) { - r.Response.Writeln(r.Get("customer_id")) - r.Response.Writeln(r.Router.Uri) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/router/router6.go b/.example/net/ghttp/server/router/router6.go deleted file mode 100644 index 548acfc5e..000000000 --- a/.example/net/ghttp/server/router/router6.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -// 试试模糊匹配规则不带名称会怎么样 -func main() { - s := g.Server() - s.BindHandler("/hello/*", func(r *ghttp.Request) { - r.Response.Writeln("哈喽世界!") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/servefile/servefile.go b/.example/net/ghttp/server/servefile/servefile.go deleted file mode 100644 index 85d52b650..000000000 --- a/.example/net/ghttp/server/servefile/servefile.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.ServeFile("test.txt") - }) - s.SetPort(8999) - s.Run() -} diff --git a/.example/net/ghttp/server/servefile/servefiledownload.go b/.example/net/ghttp/server/servefile/servefiledownload.go deleted file mode 100644 index 9c9f67ff5..000000000 --- a/.example/net/ghttp/server/servefile/servefiledownload.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.ServeFileDownload("test.txt") - }) - s.SetPort(8999) - s.Run() -} diff --git a/.example/net/ghttp/server/servefile/test.txt b/.example/net/ghttp/server/servefile/test.txt deleted file mode 100644 index 30d74d258..000000000 --- a/.example/net/ghttp/server/servefile/test.txt +++ /dev/null @@ -1 +0,0 @@ -test \ No newline at end of file diff --git a/.example/net/ghttp/server/server2.go b/.example/net/ghttp/server/server2.go deleted file mode 100644 index fe96ae6bb..000000000 --- a/.example/net/ghttp/server/server2.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s1 := ghttp.GetServer("s1") - s1.SetAddr(":8080") - s1.SetIndexFolder(true) - s1.SetServerRoot("/home/www/static1") - go s1.Run() - - s2 := ghttp.GetServer("s2") - s2.SetAddr(":8081") - s2.SetIndexFolder(true) - s2.SetServerRoot("/home/www/static2") - go s2.Run() - - select {} -} diff --git a/.example/net/ghttp/server/session.go b/.example/net/ghttp/server/session.go deleted file mode 100644 index 704bc8a6d..000000000 --- a/.example/net/ghttp/server/session.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - s := g.Server() - s.BindHandler("/session", func(r *ghttp.Request) { - id := r.Session.GetInt("id") - r.Session.Set("id", id+1) - r.Response.Write("id:" + gconv.String(id)) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/session/basic/session.go b/.example/net/ghttp/server/session/basic/session.go deleted file mode 100644 index b2d101845..000000000 --- a/.example/net/ghttp/server/session/basic/session.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - s := g.Server() - s.Group("/", func(group *ghttp.RouterGroup) { - group.GET("/set", func(r *ghttp.Request) { - r.Session.Set("time", gtime.Timestamp()) - r.Response.Write("ok") - }) - group.GET("/get", func(r *ghttp.Request) { - r.Response.WriteJson(r.Session.Map()) - }) - group.GET("/clear", func(r *ghttp.Request) { - r.Session.Clear() - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/session/redis/config.toml b/.example/net/ghttp/server/session/redis/config.toml deleted file mode 100644 index d5195ad6d..000000000 --- a/.example/net/ghttp/server/session/redis/config.toml +++ /dev/null @@ -1,2 +0,0 @@ -[redis] - default = "127.0.0.1:6379,10" \ No newline at end of file diff --git a/.example/net/ghttp/server/session/redis/redis.go b/.example/net/ghttp/server/session/redis/redis.go deleted file mode 100644 index f581dcdcd..000000000 --- a/.example/net/ghttp/server/session/redis/redis.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gsession" - "github.com/gogf/gf/v2/os/gtime" - "time" -) - -func main() { - s := g.Server() - s.SetSessionMaxAge(2 * time.Minute) - s.SetSessionStorage(gsession.NewStorageRedis(g.Redis())) - s.Group("/", func(group *ghttp.RouterGroup) { - group.GET("/set", func(r *ghttp.Request) { - r.Session.Set("time", gtime.Timestamp()) - r.Response.Write("ok") - }) - group.GET("/get", func(r *ghttp.Request) { - r.Response.WriteJson(r.Session.Map()) - }) - group.GET("/clear", func(r *ghttp.Request) { - r.Session.Clear() - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/session/redis/redis_bigint.go b/.example/net/ghttp/server/session/redis/redis_bigint.go deleted file mode 100644 index 07580bbfd..000000000 --- a/.example/net/ghttp/server/session/redis/redis_bigint.go +++ /dev/null @@ -1,36 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gsession" -) - -func main() { - type User struct { - Id int64 - Name string - } - s := g.Server() - s.SetSessionStorage(gsession.NewStorageRedis(g.Redis())) - s.Group("/", func(group *ghttp.RouterGroup) { - group.GET("/set", func(r *ghttp.Request) { - user := &User{ - Id: 1265476890672672808, - Name: "john", - } - if err := r.Session.Set("user", user); err != nil { - panic(err) - } - r.Response.Write("ok") - }) - group.GET("/get", func(r *ghttp.Request) { - r.Response.WriteJson(r.Session.Get("user")) - }) - group.GET("/clear", func(r *ghttp.Request) { - r.Session.Clear() - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/static/static.go b/.example/net/ghttp/server/static/static.go deleted file mode 100644 index 2a06b196d..000000000 --- a/.example/net/ghttp/server/static/static.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import "github.com/gogf/gf/v2/frame/g" - -// 静态文件服务器基本使用 -func main() { - s := g.Server() - s.SetIndexFolder(true) - s.SetServerRoot("/Users/john/Downloads") - //s.AddSearchPath("/Users/john/Documents") - s.SetErrorLogEnabled(true) - s.SetAccessLogEnabled(true) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/static/static_path.go b/.example/net/ghttp/server/static/static_path.go deleted file mode 100644 index 30579ec53..000000000 --- a/.example/net/ghttp/server/static/static_path.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import "github.com/gogf/gf/v2/frame/g" - -// 静态文件服务器,支持自定义静态目录映射 -func main() { - s := g.Server() - s.SetIndexFolder(true) - s.SetServerRoot("/Users/john/Temp") - s.AddSearchPath("/Users/john/Documents") - s.AddStaticPath("/my-doc", "/Users/john/Documents") - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/static/static_path2.go b/.example/net/ghttp/server/static/static_path2.go deleted file mode 100644 index 30c5c3258..000000000 --- a/.example/net/ghttp/server/static/static_path2.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import "github.com/gogf/gf/v2/frame/g" - -// 静态文件服务器,支持自定义静态目录映射 -func main() { - s := g.Server() - s.SetIndexFolder(true) - s.SetServerRoot("/Users/john/Temp") - s.AddSearchPath("/Users/john/Documents") - s.AddStaticPath("/my-doc", "/Users/john/Documents") - s.AddStaticPath("/my-doc/test", "/Users/john/Temp") - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/status.go b/.example/net/ghttp/server/status.go deleted file mode 100644 index c06feca06..000000000 --- a/.example/net/ghttp/server/status.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln("halo 世界!") - }) - s.BindStatusHandler(404, func(r *ghttp.Request) { - r.Response.Writeln("This is customized 404 page") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/status_map.go b/.example/net/ghttp/server/status_map.go deleted file mode 100644 index 517af3fc8..000000000 --- a/.example/net/ghttp/server/status_map.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindStatusHandlerByMap(map[int]ghttp.HandlerFunc{ - 403: func(r *ghttp.Request) { r.Response.Writeln("403") }, - 404: func(r *ghttp.Request) { r.Response.Writeln("404") }, - 500: func(r *ghttp.Request) { r.Response.Writeln("500") }, - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/status_redirect.go b/.example/net/ghttp/server/status_redirect.go deleted file mode 100644 index 5658a3109..000000000 --- a/.example/net/ghttp/server/status_redirect.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/status/:status", func(r *ghttp.Request) { - r.Response.Write("woops, status ", r.Get("status"), " found") - }) - s.BindStatusHandler(404, func(r *ghttp.Request) { - r.Response.RedirectTo("/status/404") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/template/build-in/objects/objects.go b/.example/net/ghttp/server/template/build-in/objects/objects.go deleted file mode 100644 index 69d1311e5..000000000 --- a/.example/net/ghttp/server/template/build-in/objects/objects.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - content := `{{.Request.Get "name"}}` - r.Response.WriteTplContent(content) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/template/build-in/vars/config.toml b/.example/net/ghttp/server/template/build-in/vars/config.toml deleted file mode 100644 index cf3c1cdf6..000000000 --- a/.example/net/ghttp/server/template/build-in/vars/config.toml +++ /dev/null @@ -1,4 +0,0 @@ -# Redis数据库配置 -[redis] - disk = "127.0.0.1:6379,0" - cache = "127.0.0.1:6379,1" \ No newline at end of file diff --git a/.example/net/ghttp/server/template/build-in/vars/vars.go b/.example/net/ghttp/server/template/build-in/vars/vars.go deleted file mode 100644 index 0d6544202..000000000 --- a/.example/net/ghttp/server/template/build-in/vars/vars.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Cookie.Set("theme", "default") - r.Session.Set("name", "john") - content := ` -Get: {{.Get.name}} -Post: {{.Post.name}} -Config: {{.Config.redis}} -Cookie: {{.Cookie.theme}}, -Session: {{.Session.name}}` - r.Response.WriteTplContent(content) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/template/config/config.go b/.example/net/ghttp/server/template/config/config.go deleted file mode 100644 index 94eaa48d6..000000000 --- a/.example/net/ghttp/server/template/config/config.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.WriteTplContent(`${.name}`, g.Map{ - "name": "john", - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/template/config/config.toml b/.example/net/ghttp/server/template/config/config.toml deleted file mode 100644 index 1d5fc0dbb..000000000 --- a/.example/net/ghttp/server/template/config/config.toml +++ /dev/null @@ -1,2 +0,0 @@ -[viewer] - delimiters = ["${", "}"] \ No newline at end of file diff --git a/.example/net/ghttp/server/template/conflicts-name/client.go b/.example/net/ghttp/server/template/conflicts-name/client.go deleted file mode 100644 index c82e35f1a..000000000 --- a/.example/net/ghttp/server/template/conflicts-name/client.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -// https://github.com/gogf/gf/issues/437 -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.WriteTpl("client/layout.html") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/template/conflicts-name/template/client/layout.html b/.example/net/ghttp/server/template/conflicts-name/template/client/layout.html deleted file mode 100644 index 56a6051ca..000000000 --- a/.example/net/ghttp/server/template/conflicts-name/template/client/layout.html +++ /dev/null @@ -1 +0,0 @@ -1 \ No newline at end of file diff --git a/.example/net/ghttp/server/template/layout/main.go b/.example/net/ghttp/server/template/layout/main.go deleted file mode 100644 index 9040ced33..000000000 --- a/.example/net/ghttp/server/template/layout/main.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/main1", func(r *ghttp.Request) { - r.Response.WriteTpl("layout.html", g.Map{ - "mainTpl": "main/main1.html", - }) - }) - s.BindHandler("/main2", func(r *ghttp.Request) { - r.Response.WriteTpl("layout.html", g.Map{ - "mainTpl": "main/main2.html", - }) - }) - g.View().SetPath("template") - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/template/layout/template/footer.html b/.example/net/ghttp/server/template/layout/template/footer.html deleted file mode 100644 index 83ae25b65..000000000 --- a/.example/net/ghttp/server/template/layout/template/footer.html +++ /dev/null @@ -1 +0,0 @@ -

FOOTER

\ No newline at end of file diff --git a/.example/net/ghttp/server/template/layout/template/header.html b/.example/net/ghttp/server/template/layout/template/header.html deleted file mode 100644 index b9cb0a77c..000000000 --- a/.example/net/ghttp/server/template/layout/template/header.html +++ /dev/null @@ -1 +0,0 @@ -

HEADER

\ No newline at end of file diff --git a/.example/net/ghttp/server/template/layout/template/layout.html b/.example/net/ghttp/server/template/layout/template/layout.html deleted file mode 100644 index 9f58c21a0..000000000 --- a/.example/net/ghttp/server/template/layout/template/layout.html +++ /dev/null @@ -1,3 +0,0 @@ -{{include "header.html" .}} -{{include .mainTpl .}} -{{include "footer.html" .}} \ No newline at end of file diff --git a/.example/net/ghttp/server/template/layout/template/main/main1.html b/.example/net/ghttp/server/template/layout/template/main/main1.html deleted file mode 100644 index fdb0016f3..000000000 --- a/.example/net/ghttp/server/template/layout/template/main/main1.html +++ /dev/null @@ -1 +0,0 @@ -

MAIN1

\ No newline at end of file diff --git a/.example/net/ghttp/server/template/layout/template/main/main2.html b/.example/net/ghttp/server/template/layout/template/main/main2.html deleted file mode 100644 index 608512269..000000000 --- a/.example/net/ghttp/server/template/layout/template/main/main2.html +++ /dev/null @@ -1 +0,0 @@ -

MAIN2

\ No newline at end of file diff --git a/.example/net/ghttp/server/template/tpl1/index.tpl b/.example/net/ghttp/server/template/tpl1/index.tpl deleted file mode 100644 index 0dbd0a075..000000000 --- a/.example/net/ghttp/server/template/tpl1/index.tpl +++ /dev/null @@ -1,10 +0,0 @@ - - - - - {{.title}} - - -

{{.name}}: {{.score}}

- - \ No newline at end of file diff --git a/.example/net/ghttp/server/template/tpl1/tpl1.go b/.example/net/ghttp/server/template/tpl1/tpl1.go deleted file mode 100644 index da6d18b0e..000000000 --- a/.example/net/ghttp/server/template/tpl1/tpl1.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := ghttp.GetServer() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.WriteTpl("index.tpl", g.Map{ - "title": "Test", - "name": "John", - "score": 100, - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/template/tpl2/main.go b/.example/net/ghttp/server/template/tpl2/main.go deleted file mode 100644 index 8489511eb..000000000 --- a/.example/net/ghttp/server/template/tpl2/main.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/frame/gins" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.SetServerRoot("public") - s.SetNameToUriType(ghttp.URI_TYPE_ALLLOWER) - s.SetErrorLogEnabled(true) - s.SetAccessLogEnabled(true) - s.SetPort(2333) - - s.BindHandler("/", func(r *ghttp.Request) { - content, _ := gins.View().Parse("test.html", nil) - r.Response.Write(content) - }) - - s.Run() -} diff --git a/.example/net/ghttp/server/template/tpl2/public/test.html b/.example/net/ghttp/server/template/tpl2/public/test.html deleted file mode 100644 index 29c9de328..000000000 --- a/.example/net/ghttp/server/template/tpl2/public/test.html +++ /dev/null @@ -1 +0,0 @@ -hello gf! \ No newline at end of file diff --git a/.example/net/ghttp/server/template/tpl2/template/test.html b/.example/net/ghttp/server/template/tpl2/template/test.html deleted file mode 100644 index 4632e068d..000000000 --- a/.example/net/ghttp/server/template/tpl2/template/test.html +++ /dev/null @@ -1 +0,0 @@ -123456 \ No newline at end of file diff --git a/.example/net/ghttp/server/websocket/echo-wss/index.html b/.example/net/ghttp/server/websocket/echo-wss/index.html deleted file mode 100644 index 6b1f50583..000000000 --- a/.example/net/ghttp/server/websocket/echo-wss/index.html +++ /dev/null @@ -1,93 +0,0 @@ - - - - gf websocket echo server - - - - -
-
-
-
-
-
-
- - - - \ No newline at end of file diff --git a/.example/net/ghttp/server/websocket/echo-wss/main.go b/.example/net/ghttp/server/websocket/echo-wss/main.go deleted file mode 100644 index 32689e893..000000000 --- a/.example/net/ghttp/server/websocket/echo-wss/main.go +++ /dev/null @@ -1,32 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - s := g.Server() - s.BindHandler("/wss", func(r *ghttp.Request) { - ws, err := r.WebSocket() - if err != nil { - glog.Error(err) - r.Exit() - } - for { - msgType, msg, err := ws.ReadMessage() - if err != nil { - return - } - if err = ws.WriteMessage(msgType, msg); err != nil { - return - } - } - }) - s.SetServerRoot(gfile.MainPkgPath()) - s.EnableHTTPS("../../https/server.crt", "../../https/server.key") - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/websocket/echo/index.html b/.example/net/ghttp/server/websocket/echo/index.html deleted file mode 100644 index 1accbfdfb..000000000 --- a/.example/net/ghttp/server/websocket/echo/index.html +++ /dev/null @@ -1,93 +0,0 @@ - - - - gf websocket echo server - - - - -
-
-
-
-
-
-
- - - - \ No newline at end of file diff --git a/.example/net/ghttp/server/websocket/echo/main-group.go b/.example/net/ghttp/server/websocket/echo/main-group.go deleted file mode 100644 index 5a6cd8285..000000000 --- a/.example/net/ghttp/server/websocket/echo/main-group.go +++ /dev/null @@ -1,36 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/os/glog" -) - -func ws(r *ghttp.Request) { - ws, err := r.WebSocket() - if err != nil { - glog.Error(err) - return - } - for { - msgType, msg, err := ws.ReadMessage() - if err != nil { - return - } - if err = ws.WriteMessage(msgType, msg); err != nil { - return - } - } -} - -func main() { - s := g.Server() - s.Group("").Bind([]ghttp.GroupItem{ - {"ALL", "/ws", ws}, - }) - s.SetAccessLogEnabled(true) - s.SetServerRoot(gfile.MainPkgPath()) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/websocket/echo/main.go b/.example/net/ghttp/server/websocket/echo/main.go deleted file mode 100644 index 61e45cebb..000000000 --- a/.example/net/ghttp/server/websocket/echo/main.go +++ /dev/null @@ -1,31 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - s := g.Server() - s.BindHandler("/ws", func(r *ghttp.Request) { - ws, err := r.WebSocket() - if err != nil { - glog.Error(err) - return - } - for { - msgType, msg, err := ws.ReadMessage() - if err != nil { - return - } - if err = ws.WriteMessage(msgType, msg); err != nil { - return - } - } - }) - s.SetServerRoot(gfile.MainPkgPath()) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/gsmtp/gsmtp_sendMail.go b/.example/net/gsmtp/gsmtp_sendMail.go deleted file mode 100644 index 307dbe24f..000000000 --- a/.example/net/gsmtp/gsmtp_sendMail.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. -// -// This Source Code Form is subject to the terms of the MIT License. -// If a copy of the MIT was not distributed with this file, -// You can obtain one at https://github.com/gogf/gf. -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/net/gsmtp" -) - -func main() { - - // create the SMTP connection - smtpConnection := gsmtp.New("smtp.exmail.qq.com", "smtpUser@smtp.exmail.qq.com", "smtpPassword") - // or you can specify the port explicitly - // smtpConnection := smtp.New("smtp.exmail.qq.com:25", "smtpUser@smtp.exmail.qq.com", "smtpPassword") - - // send the Email - fmt.Println(smtpConnection.SendMail("sender@local.host", "recipient1@domain.com;recipientN@anotherDomain.cn", "This is subject", "Hi!

This is body")) - -} diff --git a/.example/net/gtcp/gtcp_conn.go b/.example/net/gtcp/gtcp_conn.go deleted file mode 100644 index 855c10901..000000000 --- a/.example/net/gtcp/gtcp_conn.go +++ /dev/null @@ -1,56 +0,0 @@ -package main - -import ( - "bytes" - "fmt" - "os" - - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - conn, err := gtcp.NewConn("www.baidu.com:80") - if err != nil { - panic(err) - } - defer conn.Close() - - if err := conn.Send([]byte("GET / HTTP/1.1\r\n\r\n")); err != nil { - panic(err) - } - - header := make([]byte, 0) - content := make([]byte, 0) - contentLength := 0 - for { - data, err := conn.RecvLine() - // header读取,解析文本长度 - if len(data) > 0 { - array := bytes.Split(data, []byte(": ")) - // 获得页面内容长度 - if contentLength == 0 && len(array) == 2 && bytes.EqualFold([]byte("Content-Length"), array[0]) { - // http 以\r\n换行,需要把\r也去掉 - contentLength = gconv.Int(string(array[1][:len(array[1])-1])) - } - header = append(header, data...) - header = append(header, '\n') - } - // header读取完毕,读取文本内容, 1为\r - if contentLength > 0 && len(data) == 1 { - content, _ = conn.Recv(contentLength) - break - } - if err != nil { - fmt.Fprintf(os.Stderr, "ERROR: %s\n", err.Error()) - break - } - } - - if len(header) > 0 { - fmt.Println(string(header)) - } - if len(content) > 0 { - fmt.Println(string(content)) - } -} diff --git a/.example/net/gtcp/gtcp_echo_server.go b/.example/net/gtcp/gtcp_echo_server.go deleted file mode 100644 index 85f60832c..000000000 --- a/.example/net/gtcp/gtcp_echo_server.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/net/gtcp" -) - -func main() { - gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) { - defer conn.Close() - for { - data, err := conn.Recv(-1) - if len(data) > 0 { - if err := conn.Send(append([]byte("> "), data...)); err != nil { - fmt.Println(err) - } - } - if err != nil { - break - } - } - }).Run() -} diff --git a/.example/net/gtcp/gtcp_func.go b/.example/net/gtcp/gtcp_func.go deleted file mode 100644 index 79217a973..000000000 --- a/.example/net/gtcp/gtcp_func.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "fmt" - "os" - - "github.com/gogf/gf/v2/net/gtcp" -) - -func main() { - dstConn, err := gtcp.NewPoolConn("www.medlinker.com:80") - _, err = dstConn.Write([]byte("HEAD / HTTP/1.1\n\n")) - if err != nil { - fmt.Fprintf(os.Stderr, "ERROR: %s\n", err.Error()) - } - fmt.Println(dstConn.RecvLine()) -} diff --git a/.example/net/gtcp/gtcp_pool1.go b/.example/net/gtcp/gtcp_pool1.go deleted file mode 100644 index 200d5e5dd..000000000 --- a/.example/net/gtcp/gtcp_pool1.go +++ /dev/null @@ -1,45 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - // Server - go gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) { - defer conn.Close() - for { - data, err := conn.Recv(-1) - if len(data) > 0 { - if err := conn.Send(append([]byte("> "), data...)); err != nil { - fmt.Println(err) - } - } - if err != nil { - break - } - } - }).Run() - - time.Sleep(time.Second) - - // Client - for { - if conn, err := gtcp.NewPoolConn("127.0.0.1:8999"); err == nil { - if b, err := conn.SendRecv([]byte(gtime.Datetime()), -1); err == nil { - fmt.Println(string(b), conn.LocalAddr(), conn.RemoteAddr()) - } else { - fmt.Println(err) - } - conn.Close() - } else { - glog.Error(err) - } - time.Sleep(time.Second) - } -} diff --git a/.example/net/gtcp/gtcp_pool2.go b/.example/net/gtcp/gtcp_pool2.go deleted file mode 100644 index 3032ebfa9..000000000 --- a/.example/net/gtcp/gtcp_pool2.go +++ /dev/null @@ -1,46 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - // Server - go gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) { - defer conn.Close() - for { - data, err := conn.Recv(-1) - if len(data) > 0 { - if err := conn.Send(append([]byte("> "), data...)); err != nil { - fmt.Println(err) - } - } - if err != nil { - break - } - return - } - }).Run() - - time.Sleep(time.Second) - - // Client - for { - if conn, err := gtcp.NewPoolConn("127.0.0.1:8999"); err == nil { - if b, err := conn.SendRecv([]byte(gtime.Datetime()), -1); err == nil { - fmt.Println(string(b), conn.LocalAddr(), conn.RemoteAddr()) - } else { - fmt.Println(err) - } - conn.Close() - } else { - glog.Error(err) - } - time.Sleep(time.Second) - } -} diff --git a/.example/net/gtcp/gtcp_server_client1.go b/.example/net/gtcp/gtcp_server_client1.go deleted file mode 100644 index 076d455d6..000000000 --- a/.example/net/gtcp/gtcp_server_client1.go +++ /dev/null @@ -1,50 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - // Server - go gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) { - defer conn.Close() - for { - data, err := conn.Recv(-1) - if len(data) > 0 { - fmt.Println(string(data)) - } - if err != nil { - // client closed, err will be: EOF - fmt.Println(err) - break - } - } - }).Run() - - time.Sleep(time.Second) - - // Client - conn, err := gtcp.NewConn("127.0.0.1:8999") - if err != nil { - panic(err) - } - defer conn.Close() - for i := 0; i < 10000; i++ { - if err := conn.Send([]byte(gconv.String(i))); err != nil { - glog.Error(err) - } - time.Sleep(time.Second) - if i == 5 { - conn.Close() - break - } - } - - // exit after 5 seconds - time.Sleep(5 * time.Second) -} diff --git a/.example/net/gtcp/gtcp_server_client2.go b/.example/net/gtcp/gtcp_server_client2.go deleted file mode 100644 index 5ff8fc79d..000000000 --- a/.example/net/gtcp/gtcp_server_client2.go +++ /dev/null @@ -1,45 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - // Server - go gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) { - defer conn.Close() - for { - data, err := conn.Recv(-1) - if len(data) > 0 { - if err := conn.Send(append([]byte("> "), data...)); err != nil { - fmt.Println(err) - } - } - if err != nil { - break - } - } - }).Run() - - time.Sleep(time.Second) - - // Client - for { - if conn, err := gtcp.NewConn("127.0.0.1:8999"); err == nil { - if b, err := conn.SendRecv([]byte(gtime.Datetime()), -1); err == nil { - fmt.Println(string(b), conn.LocalAddr(), conn.RemoteAddr()) - } else { - fmt.Println(err) - } - conn.Close() - } else { - glog.Error(err) - } - time.Sleep(time.Second) - } -} diff --git a/.example/net/gtcp/gtcp_timeout_client.go b/.example/net/gtcp/gtcp_timeout_client.go deleted file mode 100644 index b3777f72f..000000000 --- a/.example/net/gtcp/gtcp_timeout_client.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - conn, err := gtcp.NewConn("127.0.0.1:8999") - if err != nil { - panic(err) - } - defer conn.Close() - - if err := conn.Send([]byte(gtime.Now().String())); err != nil { - glog.Error(err) - } - - time.Sleep(time.Minute) -} diff --git a/.example/net/gtcp/gtcp_timeout_server.go b/.example/net/gtcp/gtcp_timeout_server.go deleted file mode 100644 index 69c8592da..000000000 --- a/.example/net/gtcp/gtcp_timeout_server.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/net/gtcp" -) - -func main() { - gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) { - defer conn.Close() - conn.SetRecvDeadline(time.Now().Add(10 * time.Second)) - for { - data, err := conn.Recv(-1) - fmt.Println(err) - if len(data) > 0 { - fmt.Println(string(data)) - } - if err != nil { - break - } - } - }).Run() -} diff --git a/.example/net/gtcp/pkg_operations/common/funcs/funcs.go b/.example/net/gtcp/pkg_operations/common/funcs/funcs.go deleted file mode 100644 index dfa2eb883..000000000 --- a/.example/net/gtcp/pkg_operations/common/funcs/funcs.go +++ /dev/null @@ -1,39 +0,0 @@ -package funcs - -import ( - "encoding/json" - "fmt" - - "github.com/gogf/gf/v2/.example/net/gtcp/pkg_operations/common/types" - "github.com/gogf/gf/v2/net/gtcp" -) - -// 自定义格式发送消息包 -func SendPkg(conn *gtcp.Conn, act string, data ...string) error { - s := "" - if len(data) > 0 { - s = data[0] - } - msg, err := json.Marshal(types.Msg{ - Act: act, - Data: s, - }) - if err != nil { - panic(err) - } - return conn.SendPkg(msg) -} - -// 自定义格式接收消息包 -func RecvPkg(conn *gtcp.Conn) (msg *types.Msg, err error) { - if data, err := conn.RecvPkg(); err != nil { - return nil, err - } else { - msg = &types.Msg{} - err = json.Unmarshal(data, msg) - if err != nil { - return nil, fmt.Errorf("invalid package structure: %s", err.Error()) - } - return msg, err - } -} diff --git a/.example/net/gtcp/pkg_operations/common/gtcp_common_client.go b/.example/net/gtcp/pkg_operations/common/gtcp_common_client.go deleted file mode 100644 index 160878d39..000000000 --- a/.example/net/gtcp/pkg_operations/common/gtcp_common_client.go +++ /dev/null @@ -1,64 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/.example/net/gtcp/pkg_operations/common/funcs" - "github.com/gogf/gf/v2/.example/net/gtcp/pkg_operations/common/types" - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - conn, err := gtcp.NewConn("127.0.0.1:8999") - if err != nil { - panic(err) - } - defer conn.Close() - // 心跳消息 - gtimer.SetInterval(time.Second, func() { - if err := funcs.SendPkg(conn, "heartbeat"); err != nil { - panic(err) - } - }) - // 测试消息, 3秒后向服务端发送hello消息 - gtimer.SetTimeout(3*time.Second, func() { - if err := funcs.SendPkg(conn, "hello", "My name's John!"); err != nil { - panic(err) - } - }) - for { - msg, err := funcs.RecvPkg(conn) - if err != nil { - if err.Error() == "EOF" { - glog.Print("server closed") - } - break - } - switch msg.Act { - case "hello": - onServerHello(conn, msg) - case "doexit": - onServerDoExit(conn, msg) - case "heartbeat": - onServerHeartBeat(conn, msg) - default: - glog.Errorf("invalid message: %v", msg) - break - } - } -} - -func onServerHello(conn *gtcp.Conn, msg *types.Msg) { - glog.Printf("hello response message from [%s]: %s", conn.RemoteAddr().String(), msg.Data) -} - -func onServerHeartBeat(conn *gtcp.Conn, msg *types.Msg) { - glog.Printf("heartbeat from [%s]", conn.RemoteAddr().String()) -} - -func onServerDoExit(conn *gtcp.Conn, msg *types.Msg) { - glog.Printf("exit command from [%s]", conn.RemoteAddr().String()) - conn.Close() -} diff --git a/.example/net/gtcp/pkg_operations/common/gtcp_common_server.go b/.example/net/gtcp/pkg_operations/common/gtcp_common_server.go deleted file mode 100644 index b335db92e..000000000 --- a/.example/net/gtcp/pkg_operations/common/gtcp_common_server.go +++ /dev/null @@ -1,48 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/.example/net/gtcp/pkg_operations/common/funcs" - "github.com/gogf/gf/v2/.example/net/gtcp/pkg_operations/common/types" - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) { - defer conn.Close() - // 测试消息, 10秒后让客户端主动退出 - gtimer.SetTimeout(10*time.Second, func() { - funcs.SendPkg(conn, "doexit") - }) - for { - msg, err := funcs.RecvPkg(conn) - if err != nil { - if err.Error() == "EOF" { - glog.Print("client closed") - } - break - } - switch msg.Act { - case "hello": - onClientHello(conn, msg) - case "heartbeat": - onClientHeartBeat(conn, msg) - default: - glog.Errorf("invalid message: %v", msg) - break - } - } - }).Run() -} - -func onClientHello(conn *gtcp.Conn, msg *types.Msg) { - glog.Printf("hello message from [%s]: %s", conn.RemoteAddr().String(), msg.Data) - funcs.SendPkg(conn, msg.Act, "Nice to meet you!") -} - -func onClientHeartBeat(conn *gtcp.Conn, msg *types.Msg) { - glog.Printf("heartbeat from [%s]", conn.RemoteAddr().String()) -} diff --git a/.example/net/gtcp/pkg_operations/common/types/types.go b/.example/net/gtcp/pkg_operations/common/types/types.go deleted file mode 100644 index f2f712fe4..000000000 --- a/.example/net/gtcp/pkg_operations/common/types/types.go +++ /dev/null @@ -1,6 +0,0 @@ -package types - -type Msg struct { - Act string // 操作 - Data string // 数据 -} diff --git a/.example/net/gtcp/pkg_operations/gtcp_basic.go b/.example/net/gtcp/pkg_operations/gtcp_basic.go deleted file mode 100644 index 88c314b50..000000000 --- a/.example/net/gtcp/pkg_operations/gtcp_basic.go +++ /dev/null @@ -1,40 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - // Server - go gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) { - defer conn.Close() - for { - data, err := conn.RecvPkg() - if err != nil { - fmt.Println(err) - break - } - fmt.Println("receive:", data) - } - }).Run() - - time.Sleep(time.Second) - - // Client - conn, err := gtcp.NewConn("127.0.0.1:8999") - if err != nil { - panic(err) - } - defer conn.Close() - for i := 0; i < 10000; i++ { - if err := conn.SendPkg([]byte(gconv.String(i))); err != nil { - glog.Error(err.Error()) - } - time.Sleep(1 * time.Second) - } -} diff --git a/.example/net/gtcp/pkg_operations/gtcp_empty_data.go b/.example/net/gtcp/pkg_operations/gtcp_empty_data.go deleted file mode 100644 index ba20cbad6..000000000 --- a/.example/net/gtcp/pkg_operations/gtcp_empty_data.go +++ /dev/null @@ -1,39 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - // Server - go gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) { - defer conn.Close() - for { - data, err := conn.RecvPkg() - if err != nil { - fmt.Println(err) - break - } - fmt.Println("RecvPkg:", string(data)) - } - }).Run() - - time.Sleep(time.Second) - - // Client - conn, err := gtcp.NewConn("127.0.0.1:8999") - if err != nil { - panic(err) - } - defer conn.Close() - for i := 0; i < 10000; i++ { - if err := conn.SendPkg(nil); err != nil { - glog.Error(err) - } - time.Sleep(1 * time.Second) - } -} diff --git a/.example/net/gtcp/pkg_operations/gtcp_pkg_option.go b/.example/net/gtcp/pkg_operations/gtcp_pkg_option.go deleted file mode 100644 index 41c6ba20b..000000000 --- a/.example/net/gtcp/pkg_operations/gtcp_pkg_option.go +++ /dev/null @@ -1,40 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - // Server - go gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) { - defer conn.Close() - for { - data, err := conn.RecvPkg(gtcp.PkgOption{MaxSize: 1}) - if err != nil { - fmt.Println(err) - break - } - fmt.Println("RecvPkg:", string(data)) - } - }).Run() - - time.Sleep(time.Second) - - // Client - conn, err := gtcp.NewConn("127.0.0.1:8999") - if err != nil { - panic(err) - } - defer conn.Close() - for i := 0; i < 10000; i++ { - if err := conn.SendPkg([]byte(gconv.String(i))); err != nil { - glog.Error(err) - } - time.Sleep(1 * time.Second) - } -} diff --git a/.example/net/gtcp/pkg_operations/monitor/gtcp_monitor_client.go b/.example/net/gtcp/pkg_operations/monitor/gtcp_monitor_client.go deleted file mode 100644 index 6f150f410..000000000 --- a/.example/net/gtcp/pkg_operations/monitor/gtcp_monitor_client.go +++ /dev/null @@ -1,43 +0,0 @@ -package main - -import ( - "encoding/json" - - "github.com/gogf/gf/v2/.example/net/gtcp/pkg_operations/monitor/types" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - // 数据上报客户端 - conn, err := gtcp.NewConn("127.0.0.1:8999") - if err != nil { - panic(err) - } - defer conn.Close() - // 使用JSON格式化数据字段 - info, err := json.Marshal(types.NodeInfo{ - Cpu: float32(66.66), - Host: "localhost", - Ip: g.Map{ - "etho": "192.168.1.100", - "eth1": "114.114.10.11", - }, - MemUsed: 15560320, - MemTotal: 16333788, - Time: int(gtime.Timestamp()), - }) - if err != nil { - panic(err) - } - // 使用 SendRecvPkg 发送消息包并接受返回 - if result, err := conn.SendRecvPkg(info); err != nil { - if err.Error() == "EOF" { - glog.Print("server closed") - } - } else { - glog.Print(string(result)) - } -} diff --git a/.example/net/gtcp/pkg_operations/monitor/gtcp_monitor_server.go b/.example/net/gtcp/pkg_operations/monitor/gtcp_monitor_server.go deleted file mode 100644 index 056c0a498..000000000 --- a/.example/net/gtcp/pkg_operations/monitor/gtcp_monitor_server.go +++ /dev/null @@ -1,32 +0,0 @@ -package main - -import ( - "encoding/json" - - "github.com/gogf/gf/v2/.example/net/gtcp/pkg_operations/monitor/types" - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - // 服务端,接收客户端数据并格式化为指定数据结构,打印 - gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) { - defer conn.Close() - for { - data, err := conn.RecvPkg() - if err != nil { - if err.Error() == "EOF" { - glog.Print("client closed") - } - break - } - info := &types.NodeInfo{} - if err := json.Unmarshal(data, info); err != nil { - glog.Errorf("invalid package structure: %s", err.Error()) - } else { - glog.Print(info) - conn.SendPkg([]byte("ok")) - } - } - }).Run() -} diff --git a/.example/net/gtcp/pkg_operations/monitor/types/types.go b/.example/net/gtcp/pkg_operations/monitor/types/types.go deleted file mode 100644 index 2d6b6b7cf..000000000 --- a/.example/net/gtcp/pkg_operations/monitor/types/types.go +++ /dev/null @@ -1,12 +0,0 @@ -package types - -import "github.com/gogf/gf/v2/frame/g" - -type NodeInfo struct { - Cpu float32 // CPU百分比(%) - Host string // 主机名称 - Ip g.Map // IP地址信息(可能多个) - MemUsed int // 内存使用(byte) - MemTotal int // 内存总量(byte) - Time int // 上报时间(时间戳) -} diff --git a/.example/net/gtcp/server_client/gtcp_client.go b/.example/net/gtcp/server_client/gtcp_client.go deleted file mode 100644 index be580a6ef..000000000 --- a/.example/net/gtcp/server_client/gtcp_client.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - // Client - conn, err := gtcp.NewConn("127.0.0.1:8999") - if err != nil { - panic(err) - } - defer conn.Close() - for i := 0; i < 3; i++ { - if err := conn.Send([]byte(gconv.String(i))); err != nil { - glog.Error(err) - } - time.Sleep(time.Second) - } -} diff --git a/.example/net/gtcp/server_client/gtcp_server.go b/.example/net/gtcp/server_client/gtcp_server.go deleted file mode 100644 index 92df614f7..000000000 --- a/.example/net/gtcp/server_client/gtcp_server.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/net/gtcp" -) - -func main() { - // Server - gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) { - defer conn.Close() - for { - data, err := conn.Recv(-1) - if len(data) > 0 { - fmt.Println(string(data)) - } - if err != nil { - // client closed, err will be: EOF - fmt.Println(err) - break - } - } - }).Run() -} diff --git a/.example/net/gtcp/tcp_server_client.go b/.example/net/gtcp/tcp_server_client.go deleted file mode 100644 index 068ddfb13..000000000 --- a/.example/net/gtcp/tcp_server_client.go +++ /dev/null @@ -1,76 +0,0 @@ -package main - -import ( - "fmt" - "net" - "time" -) - -func main() { - addr := "127.0.0.1:8999" - - // Server - go func() { - tcpaddr, err := net.ResolveTCPAddr("tcp4", addr) - if err != nil { - panic(err) - } - listen, err := net.ListenTCP("tcp", tcpaddr) - if err != nil { - panic(err) - } - for { - if conn, err := listen.Accept(); err != nil { - panic(err) - } else if conn != nil { - go func(conn net.Conn) { - for { - buffer := make([]byte, 1024) - n, err := conn.Read(buffer) - if err != nil { - fmt.Println(err) - break - } else { - fmt.Println(">", string(buffer[0:n])) - conn.Close() - } - } - - }(conn) - } - } - }() - - time.Sleep(time.Second) - - // Client - if conn, err := net.Dial("tcp", addr); err == nil { - // first write - _, err := conn.Write([]byte("hello1")) - if err != nil { - fmt.Println(err) - conn.Close() - return - } else { - fmt.Println("ok") - } - - // sleep 10 seconds and re-send - time.Sleep(10 * time.Second) - - // second write - _, err = conn.Write([]byte("hello2")) - if err != nil { - fmt.Println(err) - conn.Close() - return - } else { - fmt.Println("ok") - } - // sleep 10 seconds and re-send - time.Sleep(10 * time.Second) - } else { - panic(err) - } - -} diff --git a/.example/net/gtcp/tls/gtcp_server_client.go b/.example/net/gtcp/tls/gtcp_server_client.go deleted file mode 100644 index 87d5bb981..000000000 --- a/.example/net/gtcp/tls/gtcp_server_client.go +++ /dev/null @@ -1,59 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - address := "127.0.0.1:8999" - crtFile := "server.crt" - keyFile := "server.key" - // TLS Server - go gtcp.NewServerKeyCrt(address, crtFile, keyFile, func(conn *gtcp.Conn) { - defer conn.Close() - for { - data, err := conn.Recv(-1) - if len(data) > 0 { - fmt.Println(string(data)) - } - if err != nil { - // if client closes, err will be: EOF - glog.Error(err) - break - } - } - }).Run() - - time.Sleep(time.Second) - - // Client - tlsConfig, err := gtcp.LoadKeyCrt(crtFile, keyFile) - if err != nil { - panic(err) - } - tlsConfig.InsecureSkipVerify = true - - conn, err := gtcp.NewConnTLS(address, tlsConfig) - if err != nil { - panic(err) - } - defer conn.Close() - for i := 0; i < 10; i++ { - if err := conn.Send([]byte(gconv.String(i))); err != nil { - glog.Error(err) - } - time.Sleep(time.Second) - if i == 5 { - conn.Close() - break - } - } - - // exit after 5 seconds - time.Sleep(5 * time.Second) -} diff --git a/.example/net/gtcp/tls/server.crt b/.example/net/gtcp/tls/server.crt deleted file mode 100644 index 4d254ea21..000000000 --- a/.example/net/gtcp/tls/server.crt +++ /dev/null @@ -1,23 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDzzCCAregAwIBAgIJAJYpWLkC2lEXMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNV -BAYTAkNIMRAwDgYDVQQIDAdTaUNodWFuMRAwDgYDVQQHDAdDaGVuZ2R1MRAwDgYD -VQQKDAdKb2huLmNuMQwwCgYDVQQLDANEZXYxDTALBgNVBAMMBEpvaG4xHDAaBgkq -hkiG9w0BCQEWDWpvaG5Aam9obmcuY24wHhcNMTgwNDIzMTMyNjA4WhcNMTkwNDIz -MTMyNjA4WjB+MQswCQYDVQQGEwJDSDEQMA4GA1UECAwHU2lDaHVhbjEQMA4GA1UE -BwwHQ2hlbmdkdTEQMA4GA1UECgwHSm9obi5jbjEMMAoGA1UECwwDRGV2MQ0wCwYD -VQQDDARKb2huMRwwGgYJKoZIhvcNAQkBFg1qb2huQGpvaG5nLmNuMIIBIjANBgkq -hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6cngPUrDgBhiNfn+7MMHPzOoO+oVavlS -F/tCPyKINhsePGqHkR4ILkHu9IuoBiPYR1JgrMz5goQ6mkrvq/LMfo4dCuA29ZRg -+Vps/RimBpiz+RU3FDGyqc7d+fk74dElGk6NhJJ6XO3qHqgIg1yc6d5DiZfEnlMz -CRKoZ2dQ+98o5LwES+XJBVWfZiC1pEfyppIh+ci7fXajxkRPJ+5qYWaS5cIHmJIN -DIp5Ypszg1cPs0gIr5EgPeGwZzOeqMMzsbLLE8kjSw59Pt1/+Jkdm1e0GhO18qIO -NcqaHeGaTUVjzX9XwRj8cw+q3kRoqD5aWMjUzAg9+IDrMqvo6VZQ5QIDAQABo1Aw -TjAdBgNVHQ4EFgQU1/tUQpOK0xEwLLlYDiNrckqPlDowHwYDVR0jBBgwFoAU1/tU -QpOK0xEwLLlYDiNrckqPlDowDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC -AQEA5MbG2xU3s/GDU1MV4f0wKhWCNhXfrLaYSwNYGT/eb8ZG2iHSTO0dvl0+pjO2 -EK63PDMvMhUtL1Zlyvl+OqssYcDhVfDzdFoYX6TZNbYxFwSzcx78mO6boAADk9ro -GEQWN+VHsl984SzBRZRJbtNbiw5iVuPruofeKHrrk4dLMiCsStyUaz9lUZxjo2Fi -vVJOY+mRNOBqz1HgU2+RilFTl04zWadCWPJMugQSgJcUPgxRXQ96PkC8uYevEnmR -2DUReSRULIOYEjHw0DZ6yGlqUkJcUGge3XAQEx3LlCpJasOC8Xpsh5i6WBnDPbMh -kPBjRRTooSrJOQJC5v3QW+0Kgw== ------END CERTIFICATE----- diff --git a/.example/net/gtcp/tls/server.key b/.example/net/gtcp/tls/server.key deleted file mode 100644 index e0f909629..000000000 --- a/.example/net/gtcp/tls/server.key +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEA6cngPUrDgBhiNfn+7MMHPzOoO+oVavlSF/tCPyKINhsePGqH -kR4ILkHu9IuoBiPYR1JgrMz5goQ6mkrvq/LMfo4dCuA29ZRg+Vps/RimBpiz+RU3 -FDGyqc7d+fk74dElGk6NhJJ6XO3qHqgIg1yc6d5DiZfEnlMzCRKoZ2dQ+98o5LwE -S+XJBVWfZiC1pEfyppIh+ci7fXajxkRPJ+5qYWaS5cIHmJINDIp5Ypszg1cPs0gI -r5EgPeGwZzOeqMMzsbLLE8kjSw59Pt1/+Jkdm1e0GhO18qIONcqaHeGaTUVjzX9X -wRj8cw+q3kRoqD5aWMjUzAg9+IDrMqvo6VZQ5QIDAQABAoIBAHF7cMHPvL49F88j -nr7GnIntRUhwBB19EIBbknibBotc9nxVKaEjds0dbCSAdfslAyL7tbmrdaIJFXk3 -zsckgGceDLLuyz7B26CuaCEjCdRB43qQ9b9zsEoFBHMGrC6dGul+H+uuPn9FbVOc -NSWumuxa22W6qdJAiJFq4RvwZrsbVnYs5V29Y4Y20IlVUj3siJpAny//UUHequW9 -A/U7RvVssDsEEbbKvCpfcS7STNJKU7GlgV5l5hMKN2xLs1bVG5OKiZN82Zh9r7e1 -m2irxu/ehu6rENxZN0gsfPE4vqoQpbRMNAJlCfq9a3k0PH0TOy5oOVJXPGTIDQab -E3PeAwECgYEA9wh4+bPgMuO04hsAqsoO0DJ9Cwa+BzoDPYOvENobDzmcMErSDLKb -ekl1ej+fBTHRHVaBkuOf/9neLjhjMLad1B+I5gLksqwoMh87odDRCCpkO/B20ln8 -IN6RFiMiNjOaZqjPCCUobgzjbaIz3I69lCQQnMNPwjllSgZs9Lh/PjUCgYEA8kZU -hhUN6ctHIo8ocnmqa4AUPbt2l4qOoBGHCMmhjthyft6g8y6cQlACVJzbco37MhjY -uCOhhOClyUS1tyfds3NXdzAxXPl8SwQJGvl3zqkDQG7/GhCh6AzvHhZR8u7UaweC -kVnAG87Ck6Qqo5ZNbjhMIUm0ujm2cdVd3vyV3fECgYEAmJSMHDck8GnCzLE+/T5m -XeQBZfEZKF+FptYSKId+lS3RMebUzHD5JVQAEqz/LHczoTpQOAkORzorSEMdyPXS -kDWWGfOJjG5XOXYfH/hZVADS/k6tJYnc9/RgitrSg8XlxSjZDz/cM/UT+CBqhf1I -TRrlg94DAoTu8gT8AT9/oE0CgYB5CSPO/JO/2jtGi6iUUC4QmKMEGDRuDt2kID2K -6ViaCY5hzY0xEHcmNdyEMvz7JO16oKkcjUhzHtwUSgxSXUtIDHaE6AGxRj6PJ4v4 -+uqcxxkFxq4Rcn/Acz2+lT4JlMFwWwci4Gi2O7w/kENxCHTUfLGj67OrWYvJIORN -s3iXsQKBgD1I+v+simBvKZKmozzv99EgGfxkRxmrUQsclg1V8a1VTNfE5X9oNaE5 -kjp+dTnwbtmFl3SHVdFUzX/L6FvQIQ9FIwWI2bsszPm4rw8FBeOvH+8lXwVhCwPs -y9him/PhdjBPX0zydDI+h+fmrxH/XbmryZcq1rNmEtFRHBsUs5jg ------END RSA PRIVATE KEY----- diff --git a/.example/net/gtcp/tls/server.key.public b/.example/net/gtcp/tls/server.key.public deleted file mode 100644 index e0f909629..000000000 --- a/.example/net/gtcp/tls/server.key.public +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEA6cngPUrDgBhiNfn+7MMHPzOoO+oVavlSF/tCPyKINhsePGqH -kR4ILkHu9IuoBiPYR1JgrMz5goQ6mkrvq/LMfo4dCuA29ZRg+Vps/RimBpiz+RU3 -FDGyqc7d+fk74dElGk6NhJJ6XO3qHqgIg1yc6d5DiZfEnlMzCRKoZ2dQ+98o5LwE -S+XJBVWfZiC1pEfyppIh+ci7fXajxkRPJ+5qYWaS5cIHmJINDIp5Ypszg1cPs0gI -r5EgPeGwZzOeqMMzsbLLE8kjSw59Pt1/+Jkdm1e0GhO18qIONcqaHeGaTUVjzX9X -wRj8cw+q3kRoqD5aWMjUzAg9+IDrMqvo6VZQ5QIDAQABAoIBAHF7cMHPvL49F88j -nr7GnIntRUhwBB19EIBbknibBotc9nxVKaEjds0dbCSAdfslAyL7tbmrdaIJFXk3 -zsckgGceDLLuyz7B26CuaCEjCdRB43qQ9b9zsEoFBHMGrC6dGul+H+uuPn9FbVOc -NSWumuxa22W6qdJAiJFq4RvwZrsbVnYs5V29Y4Y20IlVUj3siJpAny//UUHequW9 -A/U7RvVssDsEEbbKvCpfcS7STNJKU7GlgV5l5hMKN2xLs1bVG5OKiZN82Zh9r7e1 -m2irxu/ehu6rENxZN0gsfPE4vqoQpbRMNAJlCfq9a3k0PH0TOy5oOVJXPGTIDQab -E3PeAwECgYEA9wh4+bPgMuO04hsAqsoO0DJ9Cwa+BzoDPYOvENobDzmcMErSDLKb -ekl1ej+fBTHRHVaBkuOf/9neLjhjMLad1B+I5gLksqwoMh87odDRCCpkO/B20ln8 -IN6RFiMiNjOaZqjPCCUobgzjbaIz3I69lCQQnMNPwjllSgZs9Lh/PjUCgYEA8kZU -hhUN6ctHIo8ocnmqa4AUPbt2l4qOoBGHCMmhjthyft6g8y6cQlACVJzbco37MhjY -uCOhhOClyUS1tyfds3NXdzAxXPl8SwQJGvl3zqkDQG7/GhCh6AzvHhZR8u7UaweC -kVnAG87Ck6Qqo5ZNbjhMIUm0ujm2cdVd3vyV3fECgYEAmJSMHDck8GnCzLE+/T5m -XeQBZfEZKF+FptYSKId+lS3RMebUzHD5JVQAEqz/LHczoTpQOAkORzorSEMdyPXS -kDWWGfOJjG5XOXYfH/hZVADS/k6tJYnc9/RgitrSg8XlxSjZDz/cM/UT+CBqhf1I -TRrlg94DAoTu8gT8AT9/oE0CgYB5CSPO/JO/2jtGi6iUUC4QmKMEGDRuDt2kID2K -6ViaCY5hzY0xEHcmNdyEMvz7JO16oKkcjUhzHtwUSgxSXUtIDHaE6AGxRj6PJ4v4 -+uqcxxkFxq4Rcn/Acz2+lT4JlMFwWwci4Gi2O7w/kENxCHTUfLGj67OrWYvJIORN -s3iXsQKBgD1I+v+simBvKZKmozzv99EgGfxkRxmrUQsclg1V8a1VTNfE5X9oNaE5 -kjp+dTnwbtmFl3SHVdFUzX/L6FvQIQ9FIwWI2bsszPm4rw8FBeOvH+8lXwVhCwPs -y9him/PhdjBPX0zydDI+h+fmrxH/XbmryZcq1rNmEtFRHBsUs5jg ------END RSA PRIVATE KEY----- diff --git a/.example/net/gudp/gudp_server.go b/.example/net/gudp/gudp_server.go deleted file mode 100644 index ba59eaf75..000000000 --- a/.example/net/gudp/gudp_server.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/net/gudp" -) - -func main() { - gudp.NewServer("127.0.0.1:8999", func(conn *gudp.Conn) { - defer conn.Close() - for { - data, err := conn.Recv(-1) - fmt.Println(err, string(data)) - } - }).Run() -} diff --git a/.example/net/gudp/gudp_server_client.go b/.example/net/gudp/gudp_server_client.go deleted file mode 100644 index a19512ee0..000000000 --- a/.example/net/gudp/gudp_server_client.go +++ /dev/null @@ -1,45 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/net/gudp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - // Server - go gudp.NewServer("127.0.0.1:8999", func(conn *gudp.Conn) { - defer conn.Close() - for { - data, err := conn.Recv(-1) - if len(data) > 0 { - if err := conn.Send(append([]byte("> "), data...)); err != nil { - glog.Error(err) - } - } - if err != nil { - glog.Error(err) - } - } - }).Run() - - time.Sleep(time.Second) - - // Client - for { - if conn, err := gudp.NewConn("127.0.0.1:8999"); err == nil { - if b, err := conn.SendRecv([]byte(gtime.Datetime()), -1); err == nil { - fmt.Println(string(b), conn.LocalAddr(), conn.RemoteAddr()) - } else { - glog.Error(err) - } - conn.Close() - } else { - glog.Error(err) - } - time.Sleep(time.Second) - } -} diff --git a/.example/net/gudp/udp_client.go b/.example/net/gudp/udp_client.go deleted file mode 100644 index a49f1d48e..000000000 --- a/.example/net/gudp/udp_client.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - "net" - "os" -) - -func main() { - conn, err := net.Dial("udp", "127.0.0.1:8999") - defer conn.Close() - if err != nil { - os.Exit(1) - } - - conn.Write([]byte("Hello world!")) - - buffer := make([]byte, 100) - - conn.Read(buffer) - - fmt.Println(string(buffer)) -} diff --git a/.example/net/gudp/udp_server.go b/.example/net/gudp/udp_server.go deleted file mode 100644 index 7ebf85562..000000000 --- a/.example/net/gudp/udp_server.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "fmt" - "net" -) - -func main() { - listener, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: 8999}) - if err != nil { - fmt.Println(err) - return - } - fmt.Println("Local:", listener.LocalAddr().String()) - - data := make([]byte, 1024) - for { - n, remoteAddr, err := listener.ReadFromUDP(data) - if err != nil { - fmt.Println(err) - } - fmt.Println(remoteAddr, string(data[:n])) - - _, err = listener.WriteToUDP([]byte("world"), remoteAddr) - if err != nil { - fmt.Printf(err.Error()) - } - } -} diff --git a/.example/os/gbuild/config.toml b/.example/os/gbuild/config.toml deleted file mode 100644 index db7e02a1c..000000000 --- a/.example/os/gbuild/config.toml +++ /dev/null @@ -1,9 +0,0 @@ - - -# custom gf build setting. -[compiler] - name = "app" - [compiler.varmap] - name = "GoFrame" - version = "1.10.1" - home-site = "https://goframe.org" \ No newline at end of file diff --git a/.example/os/gbuild/gbuild.go b/.example/os/gbuild/gbuild.go deleted file mode 100644 index 5759c3d18..000000000 --- a/.example/os/gbuild/gbuild.go +++ /dev/null @@ -1,11 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gbuild" -) - -func main() { - g.Dump(gbuild.Info()) - g.Dump(gbuild.Map()) -} diff --git a/.example/os/gcache/getorset_func_lock.go b/.example/os/gcache/getorset_func_lock.go deleted file mode 100644 index 1d909597d..000000000 --- a/.example/os/gcache/getorset_func_lock.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/os/gcache" - "github.com/gogf/gf/v2/os/gctx" - "time" -) - -func main() { - var ( - ch = make(chan struct{}, 0) - ctx = gctx.New() - key = `key` - value = `value` - ) - for i := 0; i < 10; i++ { - go func(index int) { - <-ch - _, _ = gcache.Ctx(ctx).GetOrSetFuncLock(key, func() (interface{}, error) { - fmt.Println(index, "entered") - return value, nil - }, 0) - }(i) - } - close(ch) - time.Sleep(time.Second) -} diff --git a/.example/os/gcache/note_interface_key.go b/.example/os/gcache/note_interface_key.go deleted file mode 100644 index 08733d7ec..000000000 --- a/.example/os/gcache/note_interface_key.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/os/gcache" - "github.com/gogf/gf/v2/os/gctx" -) - -func main() { - var ( - ctx = gctx.New() - key1 int32 = 1 - key2 float64 = 1 - value = `value` - ) - _ = gcache.Ctx(ctx).Set(key1, value, 0) - fmt.Println(gcache.Ctx(ctx).Get(key1)) - fmt.Println(gcache.Ctx(ctx).Get(key2)) -} diff --git a/.example/os/gcache/note_interface_value.go b/.example/os/gcache/note_interface_value.go deleted file mode 100644 index 1d121c9ab..000000000 --- a/.example/os/gcache/note_interface_value.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/os/gcache" - "github.com/gogf/gf/v2/os/gctx" -) - -func main() { - type User struct { - Id int - Name string - Site string - } - var ( - ctx = gctx.New() - user *User - key = `UserKey` - value = &User{ - Id: 1, - Name: "GoFrame", - Site: "https://goframe.org", - } - ) - _ = gcache.Ctx(ctx).Set(key, value, 0) - v, _ := gcache.Ctx(ctx).GetVar(key) - _ = v.Scan(&user) - fmt.Printf(`%#v`, user) -} diff --git a/.example/os/gcache/usage_basic.go b/.example/os/gcache/usage_basic.go deleted file mode 100644 index cc1fa632e..000000000 --- a/.example/os/gcache/usage_basic.go +++ /dev/null @@ -1,30 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/os/gcache" -) - -func main() { - // 创建一个缓存对象,当然也可以直接使用gcache包方法 - c := gcache.New() - - // 设置缓存,不过期 - c.Set("k1", "v1", 0) - - // 获取缓存 - fmt.Println(c.Get("k1")) - - // 获取缓存大小 - fmt.Println(c.Size()) - - // 缓存中是否存在指定键名 - fmt.Println(c.Contains("k1")) - - // 删除并返回被删除的键值 - fmt.Println(c.Remove("k1")) - - // 关闭缓存对象,让GC回收资源 - c.Close() -} diff --git a/.example/os/gcache/usage_lru.go b/.example/os/gcache/usage_lru.go deleted file mode 100644 index bbf897530..000000000 --- a/.example/os/gcache/usage_lru.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/os/gcache" -) - -func main() { - // 设置LRU淘汰数量 - c := gcache.New(2) - - // 添加10个元素,不过期 - for i := 0; i < 10; i++ { - c.Set(i, i, 0) - } - fmt.Println(c.Size()) - fmt.Println(c.Keys()) - - // 读取键名1,保证该键名是优先保留 - fmt.Println(c.Get(1)) - - // 等待一定时间后(默认1秒检查一次),元素会被按照从旧到新的顺序进行淘汰 - time.Sleep(2 * time.Second) - fmt.Println(c.Size()) - fmt.Println(c.Keys()) -} diff --git a/.example/os/gcache/usage_senior.go b/.example/os/gcache/usage_senior.go deleted file mode 100644 index ac5b4f113..000000000 --- a/.example/os/gcache/usage_senior.go +++ /dev/null @@ -1,31 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/os/gcache" -) - -func main() { - // 当键名不存在时写入,设置过期时间1000毫秒 - gcache.SetIfNotExist("k1", "v1", 1000) - - // 打印当前的键名列表 - fmt.Println(gcache.Keys()) - - // 打印当前的键值列表 - fmt.Println(gcache.Values()) - - // 获取指定键值,如果不存在时写入,并返回键值 - fmt.Println(gcache.GetOrSet("k2", "v2", 0)) - - // 打印当前的键值对 - fmt.Println(gcache.Data()) - - // 等待1秒,以便k1:v1自动过期 - time.Sleep(time.Second) - - // 再次打印当前的键值对,发现k1:v1已经过期,只剩下k2:v2 - fmt.Println(gcache.Data()) -} diff --git a/.example/os/gcfg/basic/config.json b/.example/os/gcfg/basic/config.json deleted file mode 100644 index c10a4cdb6..000000000 --- a/.example/os/gcfg/basic/config.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "viewpath" : "/home/www/templates/", - "database" : { - "default" : [ - { - "host" : "127.0.0.1", - "port" : "3306", - "user" : "root", - "pass" : "123456", - "name" : "test", - "type" : "mysql", - "role" : "master", - "charset" : "utf8", - "priority" : "1" - }, - { - "host" : "127.0.0.1", - "port" : "3306", - "user" : "root", - "pass" : "123456", - "name" : "test", - "type" : "mysql", - "role" : "master", - "charset" : "utf8", - "priority" : "1" - } - ] - }, - "redis" : { - "disk" : "127.0.0.1:6379,0", - "cache" : "127.0.0.1:6379,1" - } -} \ No newline at end of file diff --git a/.example/os/gcfg/basic/config.toml b/.example/os/gcfg/basic/config.toml deleted file mode 100644 index 384011b2f..000000000 --- a/.example/os/gcfg/basic/config.toml +++ /dev/null @@ -1,33 +0,0 @@ - - -# redis配置 -[[redis-cache]] - db = 0 - host = "192.168.0.100" - port = 6379 - -[[redis-cache]] - db = 1 - host = "192.168.0.100" - port = 6379 - -[[redis-disk]] - db = 0 - host = "192.168.0.100" - port = 6380 - -[[redis-disk]] - db = 1 - host = "192.168.0.100" - port = 6380 - -# memcache配置 -[[memcache]] - host = "192.168.0.101" - port = 11211 - expire = 60 - -[[memcache]] - host = "192.168.0.102" - port = 11211 - expire = 60 \ No newline at end of file diff --git a/.example/os/gcfg/basic/gcfg1.go b/.example/os/gcfg/basic/gcfg1.go deleted file mode 100644 index 2665ebbba..000000000 --- a/.example/os/gcfg/basic/gcfg1.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -// 使用第二个参数指定读取的配置文件 -func main() { - c := g.Config() - redisConfig := c.GetArray("redis-cache", "redis.toml") - memConfig := c.GetArray("", "memcache.yml") - fmt.Println(redisConfig) - fmt.Println(memConfig) -} diff --git a/.example/os/gcfg/basic/gcfg2.go b/.example/os/gcfg/basic/gcfg2.go deleted file mode 100644 index 3ccbe7e12..000000000 --- a/.example/os/gcfg/basic/gcfg2.go +++ /dev/null @@ -1,13 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -// 使用默认的config.toml配置文件读取配置 -func main() { - c := g.Config() - fmt.Println(c.GetArray("memcache")) -} diff --git a/.example/os/gcfg/basic/gcfg3.go b/.example/os/gcfg/basic/gcfg3.go deleted file mode 100644 index fc95f57c1..000000000 --- a/.example/os/gcfg/basic/gcfg3.go +++ /dev/null @@ -1,12 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -// 使用GetVar获取动态变量 -func main() { - fmt.Println(g.Config().GetVar("memcache.0").String()) -} diff --git a/.example/os/gcfg/basic/gcfg4.go b/.example/os/gcfg/basic/gcfg4.go deleted file mode 100644 index a2af5a2d9..000000000 --- a/.example/os/gcfg/basic/gcfg4.go +++ /dev/null @@ -1,12 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -// 使用g.Config方法获取配置管理对象,并指定默认的配置文件名称 -func main() { - fmt.Println(g.Config().Get("viewpath")) -} diff --git a/.example/os/gcfg/basic/gcfg_auto_update.go b/.example/os/gcfg/basic/gcfg_auto_update.go deleted file mode 100644 index cd01884d1..000000000 --- a/.example/os/gcfg/basic/gcfg_auto_update.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/os/gtimer" - - "github.com/gogf/gf/v2/frame/g" -) - -// 配置文件热更新示例 -func main() { - c := g.Config() - // 每隔1秒打印当前配置项值,用户可手动在外部修改文件内容,gcfg读取到的配置项值会即时得到更新 - gtimer.SetInterval(time.Second, func() { - fmt.Println(c.Get("viewpath")) - }) - - select {} -} diff --git a/.example/os/gcfg/basic/gcfg_error.go b/.example/os/gcfg/basic/gcfg_error.go deleted file mode 100644 index 2df606679..000000000 --- a/.example/os/gcfg/basic/gcfg_error.go +++ /dev/null @@ -1,11 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - fmt.Println(g.Config().Get("none")) -} diff --git a/.example/os/gcfg/basic/memcache.yml b/.example/os/gcfg/basic/memcache.yml deleted file mode 100644 index 056433dd1..000000000 --- a/.example/os/gcfg/basic/memcache.yml +++ /dev/null @@ -1,7 +0,0 @@ -# memcache配置 -- host: 192.168.0.101 - port: 11211 - expire: 60 -- host: 192.168.0.102 - port: 11211 - expire: 60 diff --git a/.example/os/gcfg/basic/redis.toml b/.example/os/gcfg/basic/redis.toml deleted file mode 100644 index 61a45a64d..000000000 --- a/.example/os/gcfg/basic/redis.toml +++ /dev/null @@ -1,20 +0,0 @@ -# redis配置 -[[redis-cache]] - db = 0 - host = "192.168.0.100" - port = 6379 - -[[redis-cache]] - db = 1 - host = "192.168.0.100" - port = 6379 - -[[redis-disk]] - db = 0 - host = "192.168.0.100" - port = 6380 - -[[redis-disk]] - db = 1 - host = "192.168.0.100" - port = 6380 \ No newline at end of file diff --git a/.example/os/gcfg/resource/resource.go b/.example/os/gcfg/resource/resource.go deleted file mode 100644 index 9f646fc3e..000000000 --- a/.example/os/gcfg/resource/resource.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - _ "github.com/gogf/gf/v2/os/gres/testdata" -) - -func main() { - g.Res().Dump() - g.Dump(g.Config().Get("redis")) - - g.Config().SetFileName("my.ini") - g.Dump(g.Config().Get("redis")) - - g.Config().SetPath("config-custom") - g.Config().SetFileName("my.ini") - g.Dump(g.Config().Get("redis")) - - g.Config().SetFileName("config.toml") - g.Dump(g.Config().Get("redis")) -} diff --git a/.example/os/gcmd/main.go b/.example/os/gcmd/main.go deleted file mode 100644 index 21f1d1a54..000000000 --- a/.example/os/gcmd/main.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gcmd" -) - -func main() { - p, err := gcmd.Parse(g.MapStrBool{ - "n,name": true, - "p,prefix": true, - "f,force": false, - "t,tail": false, - "i,interactive": false, - }) - if err != nil { - fmt.Println(err) - } - g.Dump(p) -} diff --git a/.example/os/gcron/gcron-log.go b/.example/os/gcron/gcron-log.go deleted file mode 100644 index d77aa1a4b..000000000 --- a/.example/os/gcron/gcron-log.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/os/gcron" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - gcron.SetLogLevel(glog.LEVEL_ALL) - gcron.Add("* * * * * ?", func() { - glog.Print("test") - }) - time.Sleep(3 * time.Second) -} diff --git a/.example/os/gcron/gcron1.go b/.example/os/gcron/gcron1.go deleted file mode 100644 index 6b90aec61..000000000 --- a/.example/os/gcron/gcron1.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/os/gcron" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - gcron.Add("0 30 * * * *", func() { glog.Print("Every hour on the half hour") }) - gcron.Add("* * * * * *", func() { glog.Print("Every second, pattern") }, "second-cron") - gcron.Add("*/5 * * * * *", func() { glog.Print("Every 5 seconds, pattern") }) - - gcron.Add("@hourly", func() { glog.Print("Every hour") }) - gcron.Add("@every 1h30m", func() { glog.Print("Every hour thirty") }) - gcron.Add("@every 1s", func() { glog.Print("Every 1 second") }) - gcron.Add("@every 5s", func() { glog.Print("Every 5 seconds") }) - - time.Sleep(3 * time.Second) - - gcron.Stop("second-cron") - - time.Sleep(3 * time.Second) - - gcron.Start("second-cron") - - time.Sleep(10 * time.Second) -} diff --git a/.example/os/gcron/gcron2.go b/.example/os/gcron/gcron2.go deleted file mode 100644 index bc032dba1..000000000 --- a/.example/os/gcron/gcron2.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/os/gcron" - "github.com/gogf/gf/v2/os/glog" -) - -func test() { - glog.Print(111) -} - -func main() { - _, err := gcron.AddOnce("@every 2s", test) - if err != nil { - panic(err) - } - time.Sleep(10 * time.Second) -} diff --git a/.example/os/gfile/gfile.go b/.example/os/gfile/gfile.go deleted file mode 100644 index b84ca4a97..000000000 --- a/.example/os/gfile/gfile.go +++ /dev/null @@ -1,46 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/util/gutil" -) - -var dirpath1 = "/home/john/Workspace/temp/" -var dirpath2 = "/home/john/Workspace/temp/1" -var filepath1 = "/home/john/Workspace/temp/test.php" -var filepath2 = "/tmp/tmp.test" - -type BinData struct { - name string - age int -} - -func info() { - fmt.Println(gfile.Info(dirpath1)) -} - -func scanDir() { - gutil.Dump(gfile.ScanDir(dirpath1, "*")) -} - -func getContents() { - fmt.Printf("%s\n", gfile.GetContents(filepath1)) -} - -func putContents() { - fmt.Println(gfile.PutContentsAppend(filepath2, "123")) -} - -func putBinContents() { - fmt.Println(gfile.PutBytes(filepath2, []byte("abc"))) -} - -func main() { - //info() - //getContents() - //putContents() - putBinContents() - //scanDir() -} diff --git a/.example/os/gfile/gfile_contents.go b/.example/os/gfile/gfile_contents.go deleted file mode 100644 index cfd8eda7f..000000000 --- a/.example/os/gfile/gfile_contents.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/os/gfile" -) - -func main() { - path := "/tmp/temp" - content := `123 -456 -789 -` - gfile.PutContents(path, content) - fmt.Println(gfile.Size(path)) - fmt.Println(gfile.GetBytesTilCharByPath(path, '\n', 0)) - fmt.Println(gfile.GetBytesTilCharByPath(path, '\n', 3)) - fmt.Println(gfile.GetBytesTilCharByPath(path, '\n', 8)) - fmt.Println(gfile.GetBytesTilCharByPath(path, '\n', 12)) -} diff --git a/.example/os/gfile/gfile_scan.go b/.example/os/gfile/gfile_scan.go deleted file mode 100644 index bb032562a..000000000 --- a/.example/os/gfile/gfile_scan.go +++ /dev/null @@ -1,11 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/util/gutil" -) - -func main() { - gutil.Dump(gfile.ScanDir("/Users/john/Documents", "*.*")) - gutil.Dump(gfile.ScanDir("/home/john/temp/newproject", "*", true)) -} diff --git a/.example/os/gfpool/gfpool.go b/.example/os/gfpool/gfpool.go deleted file mode 100644 index dbbae303f..000000000 --- a/.example/os/gfpool/gfpool.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - "os" - "time" - - "github.com/gogf/gf/v2/os/gfpool" -) - -func main() { - for { - time.Sleep(time.Second) - if f, err := gfpool.Open("/home/john/temp/log.log", os.O_RDONLY, 0666, time.Hour); err == nil { - fmt.Println(f.Name()) - f.Close() - } else { - fmt.Println(err) - } - } -} diff --git a/.example/os/gfsnotify/fsnotify.go b/.example/os/gfsnotify/fsnotify.go deleted file mode 100644 index 833732398..000000000 --- a/.example/os/gfsnotify/fsnotify.go +++ /dev/null @@ -1,41 +0,0 @@ -package main - -import ( - "context" - "log" - - "github.com/fsnotify/fsnotify" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - // 创建一个监控对象 - watch, err := fsnotify.NewWatcher() - if err != nil { - log.Fatal(err) - } - defer watch.Close() - //添加要监控的对象,文件或文件夹 - //err = watch.Add("D:\\Workspace\\Go\\GOPATH\\src\\gitee.com\\johng\\gf\\geg\\other\\test.go") - err = watch.Add("/Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/.example/other/test.go") - if err != nil { - log.Fatal(err) - } - //我们另启一个goroutine来处理监控对象的事件 - go func() { - for { - select { - case ev := <-watch.Events: - glog.Print(context.Background(), ev) - - case err := <-watch.Errors: - log.Println("error : ", err) - return - - } - } - }() - - //循环 - select {} -} diff --git a/.example/os/gfsnotify/gfsnotify.go b/.example/os/gfsnotify/gfsnotify.go deleted file mode 100644 index deedea686..000000000 --- a/.example/os/gfsnotify/gfsnotify.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/os/gfsnotify" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - //path := `D:\temp` - path := "/Users/john/Temp" - _, err := gfsnotify.Add(path, func(event *gfsnotify.Event) { - glog.Print(event) - }) - if err != nil { - glog.Fatal(err) - } else { - select {} - } -} diff --git a/.example/os/gfsnotify/gfsnotify_callback.go b/.example/os/gfsnotify/gfsnotify_callback.go deleted file mode 100644 index f6e864d9e..000000000 --- a/.example/os/gfsnotify/gfsnotify_callback.go +++ /dev/null @@ -1,37 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/os/gfsnotify" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - c1, err := gfsnotify.Add("/home/john/temp/log", func(event *gfsnotify.Event) { - glog.Print("callback1") - }) - if err != nil { - panic(err) - } - c2, err := gfsnotify.Add("/home/john/temp/log", func(event *gfsnotify.Event) { - glog.Print("callback2") - }) - if err != nil { - panic(err) - } - // 5秒后移除c1的回调函数注册,仅剩c2 - gtimer.SetTimeout(5*time.Second, func() { - gfsnotify.RemoveCallback(c1.Id) - glog.Print("remove callback c1") - }) - // 10秒后移除c2的回调函数注册,所有的回调都移除,不再有任何打印信息输出 - gtimer.SetTimeout(10*time.Second, func() { - gfsnotify.RemoveCallback(c2.Id) - glog.Print("remove callback c2") - }) - - select {} - -} diff --git a/.example/os/gfsnotify/gfsnotify_callback_folder.go b/.example/os/gfsnotify/gfsnotify_callback_folder.go deleted file mode 100644 index a12d70f89..000000000 --- a/.example/os/gfsnotify/gfsnotify_callback_folder.go +++ /dev/null @@ -1,32 +0,0 @@ -package main - -import ( - "context" - "time" - - "github.com/gogf/gf/v2/os/gfsnotify" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - var ( - ctx = context.Background() - ) - callback, err := gfsnotify.Add("/home/john/temp", func(event *gfsnotify.Event) { - glog.Print(ctx, "callback") - }) - if err != nil { - panic(err) - } - - // 在此期间创建文件、目录、修改文件、删除文件 - - // 20秒后移除回调函数注册,所有的回调都移除,不再有任何打印信息输出 - gtimer.SetTimeout(ctx, 20*time.Second, func(ctx context.Context) { - gfsnotify.RemoveCallback(callback.Id) - glog.Print(ctx, "remove callback") - }) - - select {} -} diff --git a/.example/os/gfsnotify/gfsnotify_limit.go b/.example/os/gfsnotify/gfsnotify_limit.go deleted file mode 100644 index 33522de5c..000000000 --- a/.example/os/gfsnotify/gfsnotify_limit.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/os/gfsnotify" - "github.com/gogf/gf/v2/os/glog" -) - -// 对同一个文件多次Add是否超过系统inotify限制 -func main() { - path := "/Users/john/temp/log" - for i := 0; i < 9999999; i++ { - _, err := gfsnotify.Add(path, func(event *gfsnotify.Event) { - glog.Print(event) - }) - if err != nil { - glog.Fatal(err) - } - } -} diff --git a/.example/os/glog/glog_CtxKeys.go b/.example/os/glog/glog_CtxKeys.go deleted file mode 100644 index dff0efc78..000000000 --- a/.example/os/glog/glog_CtxKeys.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - g.Log().SetCtxKeys("TraceId", "SpanId", "Test") - ctx := context.WithValue(context.Background(), "TraceId", "1234567890") - ctx = context.WithValue(ctx, "SpanId", "abcdefg") - - g.Log().Ctx(ctx).Print(1, 2, 3) -} diff --git a/.example/os/glog/glog_SetConfigWithMap.go b/.example/os/glog/glog_SetConfigWithMap.go deleted file mode 100644 index d20e70882..000000000 --- a/.example/os/glog/glog_SetConfigWithMap.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - err := g.Log().SetConfigWithMap(g.Map{ - "prefix": "[TEST]", - }) - if err != nil { - panic(err) - } - glog.Info(1) -} diff --git a/.example/os/glog/glog_async_chaining.go b/.example/os/glog/glog_async_chaining.go deleted file mode 100644 index e5bd8088a..000000000 --- a/.example/os/glog/glog_async_chaining.go +++ /dev/null @@ -1,13 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "time" -) - -func main() { - for i := 0; i < 10; i++ { - g.Log().Async().Print("async log", i) - } - time.Sleep(time.Second) -} diff --git a/.example/os/glog/glog_async_configure.go b/.example/os/glog/glog_async_configure.go deleted file mode 100644 index ed4071e92..000000000 --- a/.example/os/glog/glog_async_configure.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "time" -) - -func main() { - g.Log().SetAsync(true) - for i := 0; i < 10; i++ { - g.Log().Print("async log", i) - } - time.Sleep(time.Second) -} diff --git a/.example/os/glog/glog_category.go b/.example/os/glog/glog_category.go deleted file mode 100644 index 1aa9a7e8f..000000000 --- a/.example/os/glog/glog_category.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gfile" -) - -func main() { - path := "/tmp/glog-cat" - g.Log().SetPath(path) - g.Log().Stdout(false).Cat("cat1").Cat("cat2").Print("test") - list, err := gfile.ScanDir(path, "*", true) - g.Dump(err) - g.Dump(list) -} diff --git a/.example/os/glog/glog_color.go b/.example/os/glog/glog_color.go deleted file mode 100644 index aa64f1e89..000000000 --- a/.example/os/glog/glog_color.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - g.Log().Print("Print") - g.Log().Debug("Debug") - g.Log().Info("Info") - g.Log().Notice("Notice") - g.Log().Warning("Warning") - g.Log().Error("Error") - g.Log().Critical("Critical") -} diff --git a/.example/os/glog/glog_debug.go b/.example/os/glog/glog_debug.go deleted file mode 100644 index 1129b0f3d..000000000 --- a/.example/os/glog/glog_debug.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "time" - - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - gtimer.SetTimeout(3*time.Second, func() { - g.Log().SetDebug(false) - }) - for { - g.Log().Debug(gtime.Datetime()) - time.Sleep(time.Second) - } -} diff --git a/.example/os/glog/glog_error.go b/.example/os/glog/glog_error.go deleted file mode 100644 index 15e811fb7..000000000 --- a/.example/os/glog/glog_error.go +++ /dev/null @@ -1,11 +0,0 @@ -package main - -import "github.com/gogf/gf/v2/os/glog" - -func Test() { - glog.Error("This is error!") -} - -func main() { - Test() -} diff --git a/.example/os/glog/glog_file.go b/.example/os/glog/glog_file.go deleted file mode 100644 index 6aa1cb7f6..000000000 --- a/.example/os/glog/glog_file.go +++ /dev/null @@ -1,34 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gfile" -) - -// 设置日志等级 -func main() { - var ( - ctx = context.TODO() - path = "/tmp/glog" - ) - - g.Log().SetPath(path) - g.Log().SetStdoutPrint(false) - - // 使用默认文件名称格式 - g.Log().Print(ctx, "标准文件名称格式,使用当前时间时期") - - // 通过SetFile设置文件名称格式 - g.Log().SetFile("stdout.log") - g.Log().Print(ctx, "设置日志输出文件名称格式为同一个文件") - - // 链式操作设置文件名称格式 - g.Log().File("stderr.log").Print(ctx, "支持链式操作") - g.Log().File("error-{Ymd}.log").Print(ctx, "文件名称支持带gtime日期格式") - g.Log().File("access-{Ymd}.log").Print(ctx, "文件名称支持带gtime日期格式") - - list, err := gfile.ScanDir(path, "*") - g.Dump(err) - g.Dump(list) -} diff --git a/.example/os/glog/glog_flags.go b/.example/os/glog/glog_flags.go deleted file mode 100644 index 3ab7ea82e..000000000 --- a/.example/os/glog/glog_flags.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - g.Log().SetFlags(glog.F_TIME_TIME | glog.F_FILE_SHORT) - g.Log().Print("time and short line number") - g.Log().SetFlags(glog.F_TIME_MILLI | glog.F_FILE_LONG) - g.Log().Print("time with millisecond and long line number") - g.Log().SetFlags(glog.F_TIME_STD | glog.F_FILE_LONG) - g.Log().Print("standard time format and long line number") -} diff --git a/.example/os/glog/glog_gerror.go b/.example/os/glog/glog_gerror.go deleted file mode 100644 index 018a31b08..000000000 --- a/.example/os/glog/glog_gerror.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "errors" - "github.com/gogf/gf/v2/frame/g" - - "github.com/gogf/gf/v2/errors/gerror" -) - -func MakeError() error { - return errors.New("connection closed with normal error") -} - -func MakeGError() error { - return gerror.New("connection closed with gerror") -} - -func TestGError() { - err1 := MakeError() - err2 := MakeGError() - g.Log().Error(err1) - g.Log().Error(err2) -} - -func main() { - TestGError() -} diff --git a/.example/os/glog/glog_json.go b/.example/os/glog/glog_json.go deleted file mode 100644 index e9285d8fe..000000000 --- a/.example/os/glog/glog_json.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - g.Log().Debug(g.Map{"uid": 100, "name": "john"}) - - type User struct { - Uid int `json:"uid"` - Name string `json:"name"` - } - g.Log().Debug(User{100, "john"}) -} diff --git a/.example/os/glog/glog_level.go b/.example/os/glog/glog_level.go deleted file mode 100644 index 701f1132a..000000000 --- a/.example/os/glog/glog_level.go +++ /dev/null @@ -1,13 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/glog" -) - -// 设置日志等级,过滤掉Info日志信息 -func main() { - g.Log().Info("info1") - g.Log().SetLevel(glog.LEVEL_ALL ^ glog.LEVEL_INFO) - g.Log().Info("info2") -} diff --git a/.example/os/glog/glog_level_prefix.go b/.example/os/glog/glog_level_prefix.go deleted file mode 100644 index c15687866..000000000 --- a/.example/os/glog/glog_level_prefix.go +++ /dev/null @@ -1,11 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - g.Log().SetLevelPrefix(glog.LEVEL_DEBU, "debug") - g.Log().Debug("test") -} diff --git a/.example/os/glog/glog_line.go b/.example/os/glog/glog_line.go deleted file mode 100644 index 2d7648343..000000000 --- a/.example/os/glog/glog_line.go +++ /dev/null @@ -1,10 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - g.Log().Line().Debug("this is the short file name with its line number") - g.Log().Line(true).Debug("lone file name with line number") -} diff --git a/.example/os/glog/glog_line2.go b/.example/os/glog/glog_line2.go deleted file mode 100644 index ea0011462..000000000 --- a/.example/os/glog/glog_line2.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" -) - -func PrintLog(content string) { - g.Log().Skip(0).Line().Print("line number with skip:", content) - g.Log().Line(true).Print("line number without skip:", content) -} - -func main() { - PrintLog("just test") -} diff --git a/.example/os/glog/glog_path.go b/.example/os/glog/glog_path.go deleted file mode 100644 index 64b40be32..000000000 --- a/.example/os/glog/glog_path.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gfile" -) - -// 设置日志输出路径 -func main() { - path := "/tmp/glog" - g.Log().SetPath(path) - g.Log().Print("日志内容") - list, err := gfile.ScanDir(path, "*") - g.Dump(err) - g.Dump(list) -} diff --git a/.example/os/glog/glog_pool.go b/.example/os/glog/glog_pool.go deleted file mode 100644 index 565848e93..000000000 --- a/.example/os/glog/glog_pool.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "time" - - "github.com/gogf/gf/v2/os/gtime" -) - -// 测试删除日志文件是否会重建日志文件 -func main() { - path := "/Users/john/Temp/test" - g.Log().SetPath(path) - for { - g.Log().Print(gtime.Now().String()) - time.Sleep(time.Second) - } -} diff --git a/.example/os/glog/glog_prefix.go b/.example/os/glog/glog_prefix.go deleted file mode 100644 index 90c114354..000000000 --- a/.example/os/glog/glog_prefix.go +++ /dev/null @@ -1,11 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - g.Log().SetPrefix("[API]") - g.Log().Print("hello world") - g.Log().Error("error occurred") -} diff --git a/.example/os/glog/glog_stack.go b/.example/os/glog/glog_stack.go deleted file mode 100644 index 854793408..000000000 --- a/.example/os/glog/glog_stack.go +++ /dev/null @@ -1,12 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - g.Log().PrintStack() - - fmt.Println(g.Log().GetStack()) -} diff --git a/.example/os/glog/glog_stdout.go b/.example/os/glog/glog_stdout.go deleted file mode 100644 index 801d65732..000000000 --- a/.example/os/glog/glog_stdout.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "sync" -) - -func main() { - var ( - wg = sync.WaitGroup{} - ch = make(chan struct{}) - ) - wg.Add(3000) - for i := 0; i < 3000; i++ { - go func() { - <-ch - g.Log().Print("abcdefghijklmnopqrstuvwxyz1234567890") - wg.Done() - }() - } - close(ch) - wg.Wait() -} diff --git a/.example/os/glog/glog_writer_greylog.go b/.example/os/glog/glog_writer_greylog.go deleted file mode 100644 index 4f0824a47..000000000 --- a/.example/os/glog/glog_writer_greylog.go +++ /dev/null @@ -1,30 +0,0 @@ -package main - -//import ( -// "github.com/gogf/gf/v2/os/glog" -// "github.com/robertkowalski/graylog-golang" -//) -// -//type MyGrayLogWriter struct { -// gelf *gelf.Gelf -// logger *glog.Logger -//} -// -//func (w *MyGrayLogWriter) Write(p []byte) (n int, err error) { -// w.gelf.Send(p) -// return w.logger.Write(p) -//} -// -//func main() { -// glog.SetWriter(&MyGrayLogWriter{ -// logger : glog.New(), -// gelf : gelf.New(gelf.Config{ -// GraylogPort : 80, -// GraylogHostname : "graylog-host.com", -// Connection : "wan", -// MaxChunkSizeWan : 42, -// MaxChunkSizeLan : 1337, -// }), -// }) -// glog.Print("test log") -//} diff --git a/.example/os/glog/glog_writer_hook.go b/.example/os/glog/glog_writer_hook.go deleted file mode 100644 index e3a6e4526..000000000 --- a/.example/os/glog/glog_writer_hook.go +++ /dev/null @@ -1,31 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/frame/g" - - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/text/gregex" -) - -type MyWriter struct { - logger *glog.Logger -} - -func (w *MyWriter) Write(p []byte) (n int, err error) { - s := string(p) - if gregex.IsMatchString(`\[(PANI|FATA)\]`, s) { - fmt.Println("SERIOUS ISSUE OCCURRED!! I'd better tell monitor in first time!") - g.Client().PostContent("http://monitor.mydomain.com", s) - } - return w.logger.Write(p) -} - -func main() { - glog.SetWriter(&MyWriter{ - logger: glog.New(), - }) - glog.Debug("DEBUG") - glog.Fatal("FATAL ERROR") - -} diff --git a/.example/os/glog/handler/glog_handler_greylog.go b/.example/os/glog/handler/glog_handler_greylog.go deleted file mode 100644 index 295ea11f9..000000000 --- a/.example/os/glog/handler/glog_handler_greylog.go +++ /dev/null @@ -1,31 +0,0 @@ -package main - -//import ( -// "context" -// "github.com/gogf/gf/v2/frame/g" -// "github.com/gogf/gf/v2/os/glog" -// "github.com/robertkowalski/graylog-golang" -//) -// -//var greyLogClient = gelf.New(gelf.Config{ -// GraylogPort: 80, -// GraylogHostname: "graylog-host.com", -// Connection: "wan", -// MaxChunkSizeWan: 42, -// MaxChunkSizeLan: 1337, -//}) -// -//// LoggingGreyLogHandler is an example handler for logging content to remote GreyLog service. -//var LoggingGreyLogHandler glog.Handler = func(ctx context.Context, in *glog.HandlerInput) { -// in.Next() -// greyLogClient.Log(in.Buffer.String()) -//} -// -//func main() { -// g.Log().SetHandlers(LoggingGreyLogHandler) -// -// g.Log().Debug("Debugging...") -// g.Log().Warning("It is warning info") -// g.Log().Error("Error occurs, please have a check") -// glog.Print("test log") -//} diff --git a/.example/os/glog/handler/glog_handler_json.go b/.example/os/glog/handler/glog_handler_json.go deleted file mode 100644 index 2e53212a8..000000000 --- a/.example/os/glog/handler/glog_handler_json.go +++ /dev/null @@ -1,42 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/text/gstr" - "os" -) - -// JsonOutputsForLogger is for JSON marshaling in sequence. -type JsonOutputsForLogger struct { - Time string `json:"time"` - Level string `json:"level"` - Content string `json:"content"` -} - -// LoggingJsonHandler is an example handler for logging JSON format content. -var LoggingJsonHandler glog.Handler = func(ctx context.Context, in *glog.HandlerInput) { - jsonForLogger := JsonOutputsForLogger{ - Time: in.TimeFormat, - Level: in.LevelFormat, - Content: gstr.Trim(in.String()), - } - jsonBytes, err := json.Marshal(jsonForLogger) - if err != nil { - _, _ = os.Stderr.WriteString(err.Error()) - return - } - in.Buffer.Write(jsonBytes) - in.Buffer.WriteString("\n") - in.Next() -} - -func main() { - g.Log().SetHandlers(LoggingJsonHandler) - - g.Log().Debug("Debugging...") - g.Log().Warning("It is warning info") - g.Log().Error("Error occurs, please have a check") -} diff --git a/.example/os/gmlock/1.lock&unlock.go b/.example/os/gmlock/1.lock&unlock.go deleted file mode 100644 index caaba0916..000000000 --- a/.example/os/gmlock/1.lock&unlock.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "sync" - "time" - - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gmlock" -) - -// 内存锁基本使用 -func main() { - var ( - key = "lock" - wg = sync.WaitGroup{} - ) - for i := 0; i < 10; i++ { - wg.Add(1) - go func(i int) { - gmlock.Lock(key) - glog.Print(i) - time.Sleep(time.Second) - gmlock.Unlock(key) - wg.Done() - }(i) - } - wg.Wait() -} diff --git a/.example/os/gmlock/2.trylock.go b/.example/os/gmlock/2.trylock.go deleted file mode 100644 index 7fe2c421c..000000000 --- a/.example/os/gmlock/2.trylock.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "sync" - "time" - - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gmlock" -) - -// 内存锁 - TryLock -func main() { - key := "lock" - wg := sync.WaitGroup{} - for i := 0; i < 10; i++ { - wg.Add(1) - go func(i int) { - if gmlock.TryLock(key) { - glog.Print(i) - time.Sleep(time.Second) - gmlock.Unlock(key) - } else { - glog.Print(false) - } - wg.Done() - }(i) - } - wg.Wait() -} diff --git a/.example/os/gmlock/3.lock_conflicts.go b/.example/os/gmlock/3.lock_conflicts.go deleted file mode 100644 index 712080a4a..000000000 --- a/.example/os/gmlock/3.lock_conflicts.go +++ /dev/null @@ -1,39 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gmlock" -) - -// 内存锁 - 手动Unlock与计时Unlock冲突校验 -func main() { - key := "key" - - // 第一次锁带时间 - gmlock.Lock(key) - glog.Print("lock1") - // 这个时候上一次的计时解锁已失效 - gmlock.Unlock(key) - glog.Print("unlock1") - - fmt.Println() - - // 第二次锁,不带时间,且在执行过程中钱一个Lock的定时解锁生效 - gmlock.Lock(key) - glog.Print("lock2") - go func() { - // 正常情况下3秒后才能执行这句 - gmlock.Lock(key) - glog.Print("lock by goroutine") - }() - time.Sleep(3 * time.Second) - // 这时再解锁 - gmlock.Unlock(key) - // 注意3秒之后才会执行这一句 - glog.Print("unlock2") - - select {} -} diff --git a/.example/os/gmlock/4.test_deadlock.go b/.example/os/gmlock/4.test_deadlock.go deleted file mode 100644 index 9bc74976f..000000000 --- a/.example/os/gmlock/4.test_deadlock.go +++ /dev/null @@ -1,97 +0,0 @@ -package main - -import ( - "fmt" - "math/rand" - "sync" - "time" - - "github.com/gogf/gf/v2/os/gmlock" -) - -// 测试Locker是否会产生死锁 -func main() { - var ( - l = gmlock.New() - wg = sync.WaitGroup{} - key = "test" - event = make(chan int) - number = 100000 - ) - for i := 0; i < number; i++ { - wg.Add(1) - go func() { - <-event - l.Lock(key) - //fmt.Println("get lock") - l.Unlock(key) - wg.Done() - }() - } - - for i := 0; i < number; i++ { - wg.Add(1) - go func() { - <-event - l.RLock(key) - //fmt.Println("get rlock") - l.RUnlock(key) - wg.Done() - }() - } - - for i := 0; i < number; i++ { - wg.Add(1) - go func() { - <-event - if l.TryLock(key) { - //fmt.Println("get lock") - l.Unlock(key) - } - wg.Done() - }() - } - - for i := 0; i < number; i++ { - wg.Add(1) - go func() { - <-event - if l.TryRLock(key) { - //fmt.Println("get rlock") - l.RUnlock(key) - } - wg.Done() - }() - } - - for i := 0; i < number; i++ { - wg.Add(1) - go func() { - <-event - if l.TryLock(key) { - // 模拟业务逻辑的随机处理间隔 - time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond) - l.Unlock(key) - } - wg.Done() - }() - } - - for i := 0; i < number; i++ { - wg.Add(1) - go func() { - <-event - if l.TryRLock(key) { - // 模拟业务逻辑的随机处理间隔 - time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond) - l.RUnlock(key) - } - wg.Done() - }() - } - // 使用chan作为事件发送测试指令,让所有的goroutine同时执行 - close(event) - wg.Wait() - - fmt.Println("done!") -} diff --git a/.example/os/gmutex/gmutex_basic.go b/.example/os/gmutex/gmutex_basic.go deleted file mode 100644 index 5ca0944fa..000000000 --- a/.example/os/gmutex/gmutex_basic.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gmutex" -) - -func main() { - mu := gmutex.New() - for i := 0; i < 10; i++ { - go func(n int) { - mu.Lock() - defer mu.Unlock() - glog.Print("Lock:", n) - time.Sleep(time.Second) - }(i) - } - for i := 0; i < 10; i++ { - go func(n int) { - mu.RLock() - defer mu.RUnlock() - glog.Print("RLock:", n) - time.Sleep(time.Second) - }(i) - } - time.Sleep(11 * time.Second) -} diff --git a/.example/os/gmutex/gmutex_func.go b/.example/os/gmutex/gmutex_func.go deleted file mode 100644 index cc2515883..000000000 --- a/.example/os/gmutex/gmutex_func.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/os/glog" - - "github.com/gogf/gf/v2/os/gmutex" -) - -func main() { - mu := gmutex.New() - go mu.LockFunc(func() { - glog.Print("lock func1") - time.Sleep(1 * time.Second) - }) - time.Sleep(time.Millisecond) - go mu.LockFunc(func() { - glog.Print("lock func2") - }) - time.Sleep(2 * time.Second) -} diff --git a/.example/os/gproc/gproc.go b/.example/os/gproc/gproc.go deleted file mode 100644 index 743f45979..000000000 --- a/.example/os/gproc/gproc.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "os" - "time" - - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gproc" -) - -// 父子进程基本演示 -func main() { - if gproc.IsChild() { - glog.Printf("%d: Hi, I am child, waiting 3 seconds to die", gproc.Pid()) - time.Sleep(time.Second) - glog.Printf("%d: 1", gproc.Pid()) - time.Sleep(time.Second) - glog.Printf("%d: 2", gproc.Pid()) - time.Sleep(time.Second) - glog.Printf("%d: 3", gproc.Pid()) - } else { - m := gproc.NewManager() - p := m.NewProcess(os.Args[0], os.Args, os.Environ()) - p.Start() - p.Wait() - glog.Printf("%d: child died", gproc.Pid()) - } -} diff --git a/.example/os/gproc/gproc3.go b/.example/os/gproc/gproc3.go deleted file mode 100644 index 49acaa0e0..000000000 --- a/.example/os/gproc/gproc3.go +++ /dev/null @@ -1,36 +0,0 @@ -package main - -import ( - "os" - "time" - - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gproc" -) - -// 父进程销毁后,使用进程管理器查看存活的子进程。 -// 请使用go build编译后运行,不要使用IDE运行,因为IDE大多采用的是子进程方式执行。 -func main() { - if gproc.IsChild() { - glog.Printf("%d: I am child, waiting 10 seconds to die", gproc.Pid()) - //p, err := os.FindProcess(os.Getppid()) - //fmt.Println(err) - //p.Kill() - time.Sleep(2 * time.Second) - glog.Printf("%d: 2", gproc.Pid()) - time.Sleep(2 * time.Second) - glog.Printf("%d: 4", gproc.Pid()) - time.Sleep(2 * time.Second) - glog.Printf("%d: 6", gproc.Pid()) - time.Sleep(2 * time.Second) - glog.Printf("%d: 8", gproc.Pid()) - time.Sleep(2 * time.Second) - glog.Printf("%d: died", gproc.Pid()) - } else { - p := gproc.NewProcess(os.Args[0], os.Args, os.Environ()) - p.Start() - glog.Printf("%d: I am main, waiting 3 seconds to die", gproc.Pid()) - time.Sleep(3 * time.Second) - glog.Printf("%d: died", gproc.Pid()) - } -} diff --git a/.example/os/gproc/gproc4.go b/.example/os/gproc/gproc4.go deleted file mode 100644 index 2fd2855fd..000000000 --- a/.example/os/gproc/gproc4.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "os" - "time" - - "github.com/gogf/gf/v2/os/genv" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gproc" -) - -// 查看父子进程的环境变量 -func main() { - time.Sleep(5 * time.Second) - glog.Printf("%d: %v", gproc.Pid(), genv.All()) - p := gproc.NewProcess(os.Args[0], os.Args, os.Environ()) - p.Start() -} diff --git a/.example/os/gproc/gproc_comm.go b/.example/os/gproc/gproc_comm.go deleted file mode 100644 index ca95ee290..000000000 --- a/.example/os/gproc/gproc_comm.go +++ /dev/null @@ -1,32 +0,0 @@ -package main - -import ( - "fmt" - "os" - "time" - - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gproc" - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - fmt.Printf("%d: I am child? %v\n", gproc.Pid(), gproc.IsChild()) - if gproc.IsChild() { - gtimer.SetInterval(time.Second, func() { - if err := gproc.Send(gproc.PPid(), []byte(gtime.Datetime())); err != nil { - glog.Error(err) - } - }) - select {} - } else { - m := gproc.NewManager() - p := m.NewProcess(os.Args[0], os.Args, os.Environ()) - p.Start() - for { - msg := gproc.Receive() - fmt.Printf("%d: receive from %d, data: %s\n", gproc.Pid(), msg.SendPid, string(msg.Data)) - } - } -} diff --git a/.example/os/gproc/gproc_comm_group.go b/.example/os/gproc/gproc_comm_group.go deleted file mode 100644 index 90e216944..000000000 --- a/.example/os/gproc/gproc_comm_group.go +++ /dev/null @@ -1,58 +0,0 @@ -// 该示例是gproc_comm.go的改进,增加了分组消息的演示。 -package main - -import ( - "fmt" - "os" - "time" - - "github.com/gogf/gf/v2/os/gproc" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - fmt.Printf("%d: I am child? %v\n", gproc.Pid(), gproc.IsChild()) - if gproc.IsChild() { - // sending group: test1 - gtime.SetInterval(time.Second, func() bool { - if err := gproc.Send(gproc.PPid(), []byte(gtime.Datetime()), "test1"); err != nil { - fmt.Printf("test1: error - %s\n", err.Error()) - } - return true - }) - // sending group: test2 - gtime.SetInterval(time.Second, func() bool { - if err := gproc.Send(gproc.PPid(), []byte(gtime.Datetime()), "test2"); err != nil { - fmt.Printf("test2: error - %s\n", err.Error()) - } - return true - }) - // sending group: test3, will cause error - gtime.SetInterval(time.Second, func() bool { - if err := gproc.Send(gproc.PPid(), []byte(gtime.Datetime()), "test3"); err != nil { - fmt.Printf("test3: error - %s\n", err.Error()) - } - return true - }) - select {} - } else { - m := gproc.NewManager() - p := m.NewProcess(os.Args[0], os.Args, os.Environ()) - p.Start() - // receiving group: test1 - go func() { - for { - msg := gproc.Receive("test1") - fmt.Printf("test1: receive from %d, data: %s\n", msg.Pid, string(msg.Data)) - } - }() - // receiving group: test2 - go func() { - for { - msg := gproc.Receive("test2") - fmt.Printf("test1: receive from %d, data: %s\n", msg.Pid, string(msg.Data)) - } - }() - select {} - } -} diff --git a/.example/os/gproc/gproc_comm_send.go b/.example/os/gproc/gproc_comm_send.go deleted file mode 100644 index a3f6c92b5..000000000 --- a/.example/os/gproc/gproc_comm_send.go +++ /dev/null @@ -1,13 +0,0 @@ -// 向指定进程发送进程消息。 -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/os/gproc" -) - -func main() { - err := gproc.Send(22988, []byte{30}) - fmt.Println(err) -} diff --git a/.example/os/gproc/gproc_kill.go b/.example/os/gproc/gproc_kill.go deleted file mode 100644 index cb438e0f3..000000000 --- a/.example/os/gproc/gproc_kill.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/os/gproc" -) - -func main() { - pid := 32556 - m := gproc.NewManager() - m.AddProcess(pid) - err := m.KillAll() - fmt.Println(err) - m.WaitAll() - fmt.Printf("%d was killed\n", pid) -} diff --git a/.example/os/gproc/gproc_shellexec.go b/.example/os/gproc/gproc_shellexec.go deleted file mode 100644 index ed6600839..000000000 --- a/.example/os/gproc/gproc_shellexec.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/os/gproc" -) - -// 执行shell指令 -func main() { - r, err := gproc.ShellExec(`sleep 3s; echo "hello gf!";`) - fmt.Println("result:", r) - fmt.Println(err) -} diff --git a/.example/os/gproc/gproc_sleep.go b/.example/os/gproc/gproc_sleep.go deleted file mode 100644 index 66aaadea2..000000000 --- a/.example/os/gproc/gproc_sleep.go +++ /dev/null @@ -1,12 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/os/gproc" -) - -func main() { - fmt.Println(gproc.Pid()) - err := gproc.ShellRun("sleep 99999s") - fmt.Println(err) -} diff --git a/.example/os/gproc/signal/signal_handler.go b/.example/os/gproc/signal/signal_handler.go deleted file mode 100644 index a1d495347..000000000 --- a/.example/os/gproc/signal/signal_handler.go +++ /dev/null @@ -1,54 +0,0 @@ -package main - -import ( - "fmt" - "os" - "os/signal" - "syscall" - "time" -) - -func signalHandlerForMQ() { - var ( - sig os.Signal - receivedChan = make(chan os.Signal) - ) - signal.Notify( - receivedChan, - syscall.SIGINT, - syscall.SIGQUIT, - syscall.SIGKILL, - syscall.SIGTERM, - syscall.SIGABRT, - ) - for { - sig = <-receivedChan - fmt.Println("MQ is shutting down due to signal:", sig.String()) - time.Sleep(time.Second) - fmt.Println("MQ is shut down smoothly") - return - } -} - -func main() { - fmt.Println("Process start, pid:", os.Getpid()) - go signalHandlerForMQ() - - var ( - sig os.Signal - receivedChan = make(chan os.Signal) - ) - signal.Notify( - receivedChan, - syscall.SIGINT, - syscall.SIGQUIT, - syscall.SIGKILL, - syscall.SIGTERM, - syscall.SIGABRT, - ) - for { - sig = <-receivedChan - fmt.Println("MainProcess is shutting down due to signal:", sig.String()) - return - } -} diff --git a/.example/os/gproc/signal/signal_handler_gproc.go b/.example/os/gproc/signal/signal_handler_gproc.go deleted file mode 100644 index 06cde3386..000000000 --- a/.example/os/gproc/signal/signal_handler_gproc.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/os/gproc" - "os" - "time" -) - -func signalHandlerForMQ(sig os.Signal) { - fmt.Println("MQ is shutting down due to signal:", sig.String()) - time.Sleep(time.Second) - fmt.Println("MQ is shut down smoothly") -} - -func signalHandlerForMain(sig os.Signal) { - fmt.Println("MainProcess is shutting down due to signal:", sig.String()) -} - -func main() { - fmt.Println("Process start, pid:", os.Getpid()) - gproc.AddSigHandlerShutdown( - signalHandlerForMQ, - signalHandlerForMain, - ) - gproc.Listen() -} diff --git a/.example/os/gres/gres_example.go b/.example/os/gres/gres_example.go deleted file mode 100644 index cf2084107..000000000 --- a/.example/os/gres/gres_example.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - _ "github.com/gogf/gf/v2/os/gres/testdata/example/boot" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.Group("/", func(group *ghttp.RouterGroup) { - group.GET("/template", func(r *ghttp.Request) { - r.Response.WriteTplDefault(g.Map{ - "name": "GoFrame", - }) - }) - }) - s.Run() -} diff --git a/.example/os/gres/gres_pack.go b/.example/os/gres/gres_pack.go deleted file mode 100644 index 28c6e237e..000000000 --- a/.example/os/gres/gres_pack.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/crypto/gaes" - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/os/gres" -) - -var ( - CryptoKey = []byte("x76cgqt36i9c863bzmotuf8626dxiwu0") -) - -func main() { - binContent, err := gres.Pack("public,config") - if err != nil { - panic(err) - } - binContent, err = gaes.Encrypt(binContent, CryptoKey) - if err != nil { - panic(err) - } - if err := gfile.PutBytes("data.bin", binContent); err != nil { - panic(err) - } -} diff --git a/.example/os/gres/gres_unpack.go b/.example/os/gres/gres_unpack.go deleted file mode 100644 index cec200e3b..000000000 --- a/.example/os/gres/gres_unpack.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/crypto/gaes" - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/os/gres" -) - -var ( - CryptoKey = []byte("x76cgqt36i9c863bzmotuf8626dxiwu0") -) - -func main() { - binContent := gfile.GetBytes("data.bin") - binContent, err := gaes.Decrypt(binContent, CryptoKey) - if err != nil { - panic(err) - } - if err := gres.Add(binContent); err != nil { - panic(err) - } - gres.Dump() -} diff --git a/.example/os/grpool/goroutine.go b/.example/os/grpool/goroutine.go deleted file mode 100644 index 2bbcc1468..000000000 --- a/.example/os/grpool/goroutine.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - "sync" - "time" - - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - start := gtime.TimestampMilli() - wg := sync.WaitGroup{} - for i := 0; i < 100000; i++ { - wg.Add(1) - go func() { - time.Sleep(time.Second) - wg.Done() - }() - } - wg.Wait() - fmt.Println("time spent:", gtime.TimestampMilli()-start) -} diff --git a/.example/os/grpool/grpool.go b/.example/os/grpool/grpool.go deleted file mode 100644 index 9e02a0952..000000000 --- a/.example/os/grpool/grpool.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import ( - "fmt" - "sync" - "time" - - "github.com/gogf/gf/v2/os/grpool" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - start := gtime.TimestampMilli() - wg := sync.WaitGroup{} - for i := 0; i < 100000; i++ { - wg.Add(1) - grpool.Add(func() { - time.Sleep(time.Second) - wg.Done() - }) - } - wg.Wait() - fmt.Println(grpool.Size()) - fmt.Println("time spent:", gtime.TimestampMilli()-start) -} diff --git a/.example/os/grpool/grpool1.go b/.example/os/grpool/grpool1.go deleted file mode 100644 index a71a1d0b2..000000000 --- a/.example/os/grpool/grpool1.go +++ /dev/null @@ -1,30 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/os/grpool" - "github.com/gogf/gf/v2/os/gtimer" -) - -func job() { - time.Sleep(1 * time.Second) -} - -func main() { - pool := grpool.New(100) - for i := 0; i < 1000; i++ { - pool.Add(job) - } - fmt.Println("worker:", pool.Size()) - fmt.Println(" jobs:", pool.Jobs()) - gtimer.SetInterval(time.Second, func() { - fmt.Println("worker:", pool.Size()) - fmt.Println(" jobs:", pool.Jobs()) - fmt.Println() - gtimer.Exit() - }) - - select {} -} diff --git a/.example/os/grpool/grpool2.go b/.example/os/grpool/grpool2.go deleted file mode 100644 index 4cb3933dc..000000000 --- a/.example/os/grpool/grpool2.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - "sync" - - "github.com/gogf/gf/v2/os/grpool" -) - -func main() { - wg := sync.WaitGroup{} - for i := 0; i < 10; i++ { - wg.Add(1) - v := i - grpool.Add(func() { - fmt.Println(v) - wg.Done() - }) - } - wg.Wait() -} diff --git a/.example/os/grpool/grpool3.go b/.example/os/grpool/grpool3.go deleted file mode 100644 index a91e14641..000000000 --- a/.example/os/grpool/grpool3.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "fmt" - "sync" - - "github.com/gogf/gf/v2/os/grpool" -) - -func main() { - p := grpool.New(1) - wg := sync.WaitGroup{} - for i := 0; i < 10; i++ { - wg.Add(1) - v := i - p.Add(func() { - fmt.Println(v) - wg.Done() - }) - } - wg.Wait() -} diff --git a/.example/os/grpool/grpool4.go b/.example/os/grpool/grpool4.go deleted file mode 100644 index 4a2fd6773..000000000 --- a/.example/os/grpool/grpool4.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "fmt" - "sync" -) - -func main() { - wg := sync.WaitGroup{} - for i := 0; i < 10; i++ { - wg.Add(1) - go func(v int) { - fmt.Println(v) - wg.Done() - }(i) - } - wg.Wait() -} diff --git a/.example/os/grpool/grpool5.go b/.example/os/grpool/grpool5.go deleted file mode 100644 index 0b9c1aeff..000000000 --- a/.example/os/grpool/grpool5.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/os/grpool" -) - -func main() { - p := grpool.New(1) - for i := 0; i < 10; i++ { - v := i - p.Add(func() { - fmt.Println(v) - time.Sleep(3 * time.Second) - }) - } - time.Sleep(time.Minute) -} diff --git a/.example/os/gsession/storage-file/file.go b/.example/os/gsession/storage-file/file.go deleted file mode 100644 index 513ddf0d3..000000000 --- a/.example/os/gsession/storage-file/file.go +++ /dev/null @@ -1,30 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gtime" - "time" -) - -func main() { - s := g.Server() - s.SetConfigWithMap(g.Map{ - "SessionMaxAge": time.Minute, - }) - s.Group("/", func(group *ghttp.RouterGroup) { - group.ALL("/set", func(r *ghttp.Request) { - r.Session.Set("time", gtime.Timestamp()) - r.Response.Write("ok") - }) - group.ALL("/get", func(r *ghttp.Request) { - r.Response.Write(r.Session.Map()) - }) - group.ALL("/del", func(r *ghttp.Request) { - r.Session.Clear() - r.Response.Write("ok") - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/os/gsession/storage-memory/memory.go b/.example/os/gsession/storage-memory/memory.go deleted file mode 100644 index 13821122f..000000000 --- a/.example/os/gsession/storage-memory/memory.go +++ /dev/null @@ -1,32 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gsession" - "github.com/gogf/gf/v2/os/gtime" - "time" -) - -func main() { - s := g.Server() - s.SetConfigWithMap(g.Map{ - "SessionMaxAge": time.Minute, - "SessionStorage": gsession.NewStorageMemory(), - }) - s.Group("/", func(group *ghttp.RouterGroup) { - group.ALL("/set", func(r *ghttp.Request) { - r.Session.Set("time", gtime.Timestamp()) - r.Response.Write("ok") - }) - group.ALL("/get", func(r *ghttp.Request) { - r.Response.Write(r.Session.Map()) - }) - group.ALL("/del", func(r *ghttp.Request) { - r.Session.Clear() - r.Response.Write("ok") - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/os/gsession/storage-redis-hashtable/config.toml b/.example/os/gsession/storage-redis-hashtable/config.toml deleted file mode 100644 index 5632e6444..000000000 --- a/.example/os/gsession/storage-redis-hashtable/config.toml +++ /dev/null @@ -1,4 +0,0 @@ -# Redis数据库配置 -[redis] - default = "127.0.0.1:6379,0" - cache = "127.0.0.1:6379,1" \ No newline at end of file diff --git a/.example/os/gsession/storage-redis-hashtable/redis-hashtable.go b/.example/os/gsession/storage-redis-hashtable/redis-hashtable.go deleted file mode 100644 index 4a83c8793..000000000 --- a/.example/os/gsession/storage-redis-hashtable/redis-hashtable.go +++ /dev/null @@ -1,32 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gsession" - "github.com/gogf/gf/v2/os/gtime" - "time" -) - -func main() { - s := g.Server() - s.SetConfigWithMap(g.Map{ - "SessionMaxAge": time.Minute, - "SessionStorage": gsession.NewStorageRedisHashTable(g.Redis()), - }) - s.Group("/", func(group *ghttp.RouterGroup) { - group.ALL("/set", func(r *ghttp.Request) { - r.Session.Set("time", gtime.Timestamp()) - r.Response.Write("ok") - }) - group.ALL("/get", func(r *ghttp.Request) { - r.Response.Write(r.Session.Map()) - }) - group.ALL("/del", func(r *ghttp.Request) { - r.Session.Clear() - r.Response.Write("ok") - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/os/gsession/storage-redis/config.toml b/.example/os/gsession/storage-redis/config.toml deleted file mode 100644 index 5632e6444..000000000 --- a/.example/os/gsession/storage-redis/config.toml +++ /dev/null @@ -1,4 +0,0 @@ -# Redis数据库配置 -[redis] - default = "127.0.0.1:6379,0" - cache = "127.0.0.1:6379,1" \ No newline at end of file diff --git a/.example/os/gsession/storage-redis/redis.go b/.example/os/gsession/storage-redis/redis.go deleted file mode 100644 index 5b7068c3e..000000000 --- a/.example/os/gsession/storage-redis/redis.go +++ /dev/null @@ -1,32 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gsession" - "github.com/gogf/gf/v2/os/gtime" - "time" -) - -func main() { - s := g.Server() - s.SetConfigWithMap(g.Map{ - "SessionMaxAge": time.Minute, - "SessionStorage": gsession.NewStorageRedis(g.Redis()), - }) - s.Group("/", func(group *ghttp.RouterGroup) { - group.ALL("/set", func(r *ghttp.Request) { - r.Session.Set("time", gtime.Timestamp()) - r.Response.Write("ok") - }) - group.ALL("/get", func(r *ghttp.Request) { - r.Response.Write(r.Session.Map()) - }) - group.ALL("/del", func(r *ghttp.Request) { - r.Session.Clear() - r.Response.Write("ok") - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/os/gspath/gspath.go b/.example/os/gspath/gspath.go deleted file mode 100644 index 8e3eccc5d..000000000 --- a/.example/os/gspath/gspath.go +++ /dev/null @@ -1,26 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gspath" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - sp := gspath.New() - path := "/Users/john/Temp" - rp, err := sp.Add(path) - fmt.Println(err) - fmt.Println(rp) - fmt.Println(sp) - - gtime.SetInterval(5*time.Second, func() bool { - g.Dump(sp.AllPaths()) - return true - }) - - select {} -} diff --git a/.example/os/gtime/gtime_format.go b/.example/os/gtime/gtime_format.go deleted file mode 100644 index b0bdc9322..000000000 --- a/.example/os/gtime/gtime_format.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - formats := []string{ - "Y-m-d H:i:s.u", - "D M d H:i:s T O Y", - "\\T\\i\\m\\e \\i\\s: h:i:s a", - "2006-01-02T15:04:05.000000000Z07:00", - } - t := gtime.Now() - for _, f := range formats { - fmt.Println(t.Format(f)) - } -} diff --git a/.example/os/gtime/gtime_func.go b/.example/os/gtime/gtime_func.go deleted file mode 100644 index d362ac25e..000000000 --- a/.example/os/gtime/gtime_func.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - fmt.Println("Date :", gtime.Date()) - fmt.Println("Datetime :", gtime.Datetime()) - fmt.Println("Second :", gtime.Timestamp()) - fmt.Println("Millisecond:", gtime.TimestampMilli()) - fmt.Println("Microsecond:", gtime.TimestampMicro()) - fmt.Println("Nanosecond :", gtime.TimestampNano()) -} diff --git a/.example/os/gtime/gtime_json.go b/.example/os/gtime/gtime_json.go deleted file mode 100644 index 66209af74..000000000 --- a/.example/os/gtime/gtime_json.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - t := gtime.Now() - b, err := json.Marshal(t) - fmt.Println(err) - fmt.Println(string(b)) -} diff --git a/.example/os/gtime/gtime_layout.go b/.example/os/gtime/gtime_layout.go deleted file mode 100644 index a75f0b90d..000000000 --- a/.example/os/gtime/gtime_layout.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - formats := []string{ - "2006-01-02 15:04:05.000", - "Mon Jan _2 15:04:05 MST 2006", - "Time is: 03:04:05 PM", - "2006-01-02T15:04:05.000000000Z07:00 MST", - } - t := gtime.Now() - for _, f := range formats { - fmt.Println(t.Layout(f)) - } -} diff --git a/.example/os/gtime/gtime_linkop.go b/.example/os/gtime/gtime_linkop.go deleted file mode 100644 index d708bffc9..000000000 --- a/.example/os/gtime/gtime_linkop.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - // 去年今日 - fmt.Println(gtime.Now().AddDate(-1, 0, 0).Format("Y-m-d")) - - // 去年今日,UTC时间 - fmt.Println(gtime.Now().AddDate(-1, 0, 0).Format("Y-m-d H:i:s T")) - fmt.Println(gtime.Now().AddDate(-1, 0, 0).UTC().Format("Y-m-d H:i:s T")) - - // 下个月1号凌晨0点整 - fmt.Println(gtime.Now().AddDate(0, 1, 0).Format("Y-m-d 00:00:00")) - - // 2个小时前 - fmt.Println(gtime.Now().Add(-time.Hour).Format("Y-m-d H:i:s")) -} diff --git a/.example/os/gtime/gtime_parsertime.go b/.example/os/gtime/gtime_parsertime.go deleted file mode 100644 index 740df565b..000000000 --- a/.example/os/gtime/gtime_parsertime.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - content := ` - -2018-11-01 14:30:39 -- 67 -- assignDoctor:request -- {"问诊ID":"1017467","操作类型":2,"操作ID":52339491,"医生ID":52339491,"是否主动接单":"是"} -2018-11-01 14:35:55 -- 73 -- throwIntoPool:request -- {"问诊Id":1017474,"当前Id":null,"当前角色":null} -` - if t := gtime.ParseTimeFromContent(content); t != nil { - fmt.Println(t.String()) - fmt.Println(t.UTC()) - fmt.Println(gtime.Now().UTC()) - } else { - panic("cannot parse time from content") - } - - //if t := gtime.ParseTimeFromContent(content, "d/M/Y:H:i:s +0800"); t != nil { - // fmt.Println(t.String()) - //} else { - // panic("cannot parse time from content") - //} -} diff --git a/.example/os/gtime/gtime_regex1.go b/.example/os/gtime/gtime_regex1.go deleted file mode 100644 index 4f0826af9..000000000 --- a/.example/os/gtime/gtime_regex1.go +++ /dev/null @@ -1,39 +0,0 @@ -package main - -import ( - "fmt" - "regexp" - - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - timeRegex, err := regexp.Compile(gtime.TIME_REAGEX_PATTERN1) - if err != nil { - panic(err) - } - array := []string{ - "2017-12-14 04:51:34 +0805 LMT", - "2006-01-02T15:04:05Z07:00", - "2014-01-17T01:19:15+08:00", - "2018-02-09T20:46:17.897Z", - "2018-02-09 20:46:17.897", - "2018-02-09T20:46:17Z", - "2018-02-09 20:46:17", - "2018/10/31 - 16:38:46", - "2018-02-09", - "2017/12/14 04:51:34 +0805 LMT", - "2018/02/09 12:00:15", - "18/02/09 12:16", - "18/02/09 12", - "18/02/09 +0805 LMT", - } - for _, s := range array { - fmt.Println(s) - match := timeRegex.FindStringSubmatch(s) - for k, v := range match { - fmt.Println(k, v) - } - fmt.Println() - } -} diff --git a/.example/os/gtime/gtime_regex2.go b/.example/os/gtime/gtime_regex2.go deleted file mode 100644 index 99c07859e..000000000 --- a/.example/os/gtime/gtime_regex2.go +++ /dev/null @@ -1,33 +0,0 @@ -package main - -import ( - "fmt" - "regexp" - - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - timeRegex, err := regexp.Compile(gtime.TIME_REAGEX_PATTERN2) - if err != nil { - panic(err) - } - array := []string{ - "01-Nov-2018 11:50:28 +0805 LMT", - "01-Nov-2018T15:04:05Z07:00", - "01-Nov-2018T01:19:15+08:00", - "01-Nov-2018 11:50:28 +0805 LMT", - "01/Nov/18 11:50:28", - "01/Nov/2018 11:50:28", - "01/Nov/2018:11:50:28", - "01/Nov/2018", - } - for _, s := range array { - fmt.Println(s) - match := timeRegex.FindStringSubmatch(s) - for k, v := range match { - fmt.Println(k, v) - } - fmt.Println() - } -} diff --git a/.example/os/gtime/gtime_strtotime.go b/.example/os/gtime/gtime_strtotime.go deleted file mode 100644 index 4169e66f2..000000000 --- a/.example/os/gtime/gtime_strtotime.go +++ /dev/null @@ -1,46 +0,0 @@ -package main - -import ( - "context" - "fmt" - "time" - - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - array := []string{ - "2017-12-14 04:51:34 +0805 LMT", - "2006-01-02T15:04:05Z07:00", - "2014-01-17T01:19:15+08:00", - "2018-02-09T20:46:17.897Z", - "2018-02-09 20:46:17.897", - "2018-02-09T20:46:17Z", - "2018-02-09 20:46:17", - "2018.02.09 20:46:17", - "2018-02-09", - "2017/12/14 04:51:34 +0805 LMT", - "2018/02/09 12:00:15", - "01/Nov/2018:13:28:13 +0800", - "01-Nov-2018 11:50:28 +0805 LMT", - "01-Nov-2018T15:04:05Z07:00", - "01-Nov-2018T01:19:15+08:00", - "01-Nov-2018 11:50:28 +0805 LMT", - "01/Nov/2018 11:50:28", - "01/Nov/2018:11:50:28", - "01.Nov.2018:11:50:28", - "01/Nov/2018", - } - cstLocal, _ := time.LoadLocation("Asia/Shanghai") - for _, s := range array { - if t, err := gtime.StrToTime(s); err == nil { - fmt.Println(s) - fmt.Println(t.UTC().String()) - fmt.Println(t.In(cstLocal).String()) - } else { - glog.Error(context.Background(), s, err) - } - fmt.Println() - } -} diff --git a/.example/os/gtime/gtime_strtotime2.go b/.example/os/gtime/gtime_strtotime2.go deleted file mode 100644 index 7b3e0e86f..000000000 --- a/.example/os/gtime/gtime_strtotime2.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - if t, err := gtime.StrToTimeFormat("Tue Oct 16 15:55:59 CST 2018", "D M d H:i:s T Y"); err == nil { - fmt.Println(t.String()) - } else { - panic(err) - } -} diff --git a/.example/os/gtime/gtime_zone.go b/.example/os/gtime/gtime_zone.go deleted file mode 100644 index e34c5f988..000000000 --- a/.example/os/gtime/gtime_zone.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - // 先使用标准库打印当前时间 - fmt.Println(time.Now().String()) - // 设置进程时区,全局有效 - err := gtime.SetTimeZone("Asia/Tokyo") - if err != nil { - panic(err) - } - // 使用gtime获取当前时间 - fmt.Println(gtime.Now().String()) - // 使用标准库获取当前时间 - fmt.Println(time.Now().String()) -} diff --git a/.example/os/gtimer/gtimer-batch.go b/.example/os/gtimer/gtimer-batch.go deleted file mode 100644 index cbc902ef8..000000000 --- a/.example/os/gtimer/gtimer-batch.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - for i := 0; i < 100000; i++ { - gtimer.Add(time.Second, func() { - - }) - } - fmt.Println("start") - time.Sleep(48 * time.Hour) -} diff --git a/.example/os/gtimer/gtimer1.go b/.example/os/gtimer/gtimer1.go deleted file mode 100644 index 1f965f6ea..000000000 --- a/.example/os/gtimer/gtimer1.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - now := time.Now() - interval := 510 * time.Millisecond - gtimer.Add(interval, func() { - fmt.Println(time.Now(), time.Duration(time.Now().UnixNano()-now.UnixNano())) - now = time.Now() - }) - time.Sleep(time.Hour) - select {} -} diff --git a/.example/os/gtimer/gtimer2.go b/.example/os/gtimer/gtimer2.go deleted file mode 100644 index 3844e6bd5..000000000 --- a/.example/os/gtimer/gtimer2.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/container/gtype" - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - v := gtype.NewInt() - //w := gtimer.New(10, 10*time.Millisecond) - fmt.Println("start:", time.Now()) - for i := 0; i < 1000000; i++ { - gtimer.AddTimes(time.Second, 1, func() { - v.Add(1) - }) - } - fmt.Println("end :", time.Now()) - time.Sleep(1000 * time.Millisecond) - fmt.Println(v.Val(), time.Now()) - - //gtimer.AddSingleton(time.Second, func() { - // fmt.Println(time.Now().String()) - //}) - //select { } -} diff --git a/.example/os/gtimer/gtimer3.go b/.example/os/gtimer/gtimer3.go deleted file mode 100644 index aa726c704..000000000 --- a/.example/os/gtimer/gtimer3.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - interval := time.Second - gtimer.AddSingleton(interval, func() { - glog.Print("doing") - time.Sleep(5 * time.Second) - }) - - select {} -} diff --git a/.example/os/gtimer/gtimer4.go b/.example/os/gtimer/gtimer4.go deleted file mode 100644 index 88dea15bf..000000000 --- a/.example/os/gtimer/gtimer4.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - interval := time.Second - gtimer.AddTimes(interval, 2, func() { - glog.Print("doing1") - }) - gtimer.AddTimes(interval, 2, func() { - glog.Print("doing2") - }) - - select {} -} diff --git a/.example/os/gtimer/sleep1.go b/.example/os/gtimer/sleep1.go deleted file mode 100644 index e7dffddba..000000000 --- a/.example/os/gtimer/sleep1.go +++ /dev/null @@ -1,33 +0,0 @@ -package main - -import ( - "fmt" - "runtime" - "time" -) - -func main() { - go func() { - for { - time.Sleep(time.Microsecond) - go func() { - n := 0 - for i := 0; i < 100000000; i++ { - n += i - } - }() - } - }() - i := 0 - t := time.Now() - for { - time.Sleep(100 * time.Millisecond) - i++ - n := time.Now() - fmt.Println(i, runtime.NumGoroutine(), n, (n.UnixNano()-t.UnixNano())/1000000) - t = n - if i == 100 { - break - } - } -} diff --git a/.example/os/gtimer/sleep2.go b/.example/os/gtimer/sleep2.go deleted file mode 100644 index 429ca72f0..000000000 --- a/.example/os/gtimer/sleep2.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "fmt" - "time" -) - -func main() { - i := 0 - for { - time.Sleep(10 * time.Millisecond) - fmt.Println(time.Now()) - i++ - if i == 100 { - break - } - } -} diff --git a/.example/os/gtimer/ticker1.go b/.example/os/gtimer/ticker1.go deleted file mode 100644 index 8db944a17..000000000 --- a/.example/os/gtimer/ticker1.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - "time" -) - -func main() { - fmt.Println("start:", time.Now()) - index := 0 - ticker := time.NewTicker(10 * time.Millisecond) - for { - <-ticker.C - index++ - fmt.Println(index) - if index == 100 { - break - } - } - fmt.Println(" end:", time.Now()) -} diff --git a/.example/os/gtimer/ticker2.go b/.example/os/gtimer/ticker2.go deleted file mode 100644 index 8db944a17..000000000 --- a/.example/os/gtimer/ticker2.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - "time" -) - -func main() { - fmt.Println("start:", time.Now()) - index := 0 - ticker := time.NewTicker(10 * time.Millisecond) - for { - <-ticker.C - index++ - fmt.Println(index) - if index == 100 { - break - } - } - fmt.Println(" end:", time.Now()) -} diff --git a/.example/os/gview/assign/assign.go b/.example/os/gview/assign/assign.go deleted file mode 100644 index af0389af6..000000000 --- a/.example/os/gview/assign/assign.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gview" -) - -func main() { - g.View().Assigns(gview.Params{ - "k1": "v1", - "k2": "v2", - }) - b, err := g.View().ParseContent(`{{.k1}} - {{.k2}}`, nil) - fmt.Println(err) - fmt.Println(string(b)) -} diff --git a/.example/os/gview/basic/gview.go b/.example/os/gview/basic/gview.go deleted file mode 100644 index 53b31222c..000000000 --- a/.example/os/gview/basic/gview.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - v := g.View() - b, err := v.Parse("gview.tpl", map[string]interface{}{ - "k": "v", - }) - if err != nil { - panic(err) - } - fmt.Println(string(b)) -} diff --git a/.example/os/gview/basic/gview.tpl b/.example/os/gview/basic/gview.tpl deleted file mode 100644 index 26d34e666..000000000 --- a/.example/os/gview/basic/gview.tpl +++ /dev/null @@ -1 +0,0 @@ -test.tpl content, vars: {{.}} \ No newline at end of file diff --git a/.example/os/gview/bind_func/gview_func1.go b/.example/os/gview/bind_func/gview_func1.go deleted file mode 100644 index bbbe8cb33..000000000 --- a/.example/os/gview/bind_func/gview_func1.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gview" -) - -// 用于测试的内置函数 -func funcTest() string { - return "test content" -} - -func main() { - // 解析模板的时候传递模板函数映射Map,仅会在当前模板解析生效 - parsed, err := g.View().ParseContent(`call build-in function test: {{test}}`, nil, gview.FuncMap{ - "test": funcTest, - }) - if err != nil { - panic(err) - } - fmt.Println(string(parsed)) -} diff --git a/.example/os/gview/bind_func/gview_func2.go b/.example/os/gview/bind_func/gview_func2.go deleted file mode 100644 index ca711b6a3..000000000 --- a/.example/os/gview/bind_func/gview_func2.go +++ /dev/null @@ -1,31 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -// 用于测试的带参数的内置函数 -func funcHello(name string) string { - return fmt.Sprintf(`Hello %s`, name) -} - -func main() { - // 绑定全局的模板函数 - g.View().BindFunc("hello", funcHello) - - // 普通方式传参 - parsed1, err := g.View().ParseContent(`{{hello "GoFrame"}}`, nil) - if err != nil { - panic(err) - } - fmt.Println(string(parsed1)) - - // 通过管道传参 - parsed2, err := g.View().ParseContent(`{{"GoFrame" | hello}}`, nil) - if err != nil { - panic(err) - } - fmt.Println(string(parsed2)) -} diff --git a/.example/os/gview/bind_func/index.html b/.example/os/gview/bind_func/index.html deleted file mode 100644 index c905f153c..000000000 --- a/.example/os/gview/bind_func/index.html +++ /dev/null @@ -1 +0,0 @@ -{{test}} \ No newline at end of file diff --git a/.example/os/gview/build_in_funcs/build_in_funcs1.go b/.example/os/gview/build_in_funcs/build_in_funcs1.go deleted file mode 100644 index 3f365ec83..000000000 --- a/.example/os/gview/build_in_funcs/build_in_funcs1.go +++ /dev/null @@ -1,36 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - tplContent := ` -{{"
测试
"|text}} -{{"
测试
"|html}} -{{"<div>测试</div>"|htmldecode}} -{{"https://goframe.org"|url}} -{{"https%3A%2F%2Fgoframe.org"|urldecode}} -{{1540822968 | date "Y-m-d"}} -{{"1540822968" | date "Y-m-d H:i:s"}} -{{date "Y-m-d H:i:s"}} -{{compare "A" "B"}} -{{compare "1" "2"}} -{{compare 2 1}} -{{compare 1 1}} -{{"我是中国人" | substr 2 -1}} -{{"我是中国人" | substr 2 2}} -{{"我是中国人" | strlimit 2 "..."}} -{{"热爱GF热爱生活" | hidestr 20 "*"}} -{{"热爱GF热爱生活" | hidestr 50 "*"}} -{{"热爱GF热爱生活" | highlight "GF" "red"}} -{{"gf" | toupper}} -{{"GF" | tolower}} -{{"Go\nFrame" | nl2br}} -` - content, err := g.View().ParseContent(tplContent, nil) - fmt.Println(err) - fmt.Println(string(content)) -} diff --git a/.example/os/gview/build_in_funcs/build_in_funcs2.go b/.example/os/gview/build_in_funcs/build_in_funcs2.go deleted file mode 100644 index 9fc8c34ee..000000000 --- a/.example/os/gview/build_in_funcs/build_in_funcs2.go +++ /dev/null @@ -1,46 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - tplContent := ` -eq: -eq "a" "a": {{eq "a" "a"}} -eq "1" "1": {{eq "1" "1"}} -eq 1 "1": {{eq 1 "1"}} - -ne: -ne 1 "1": {{ne 1 "1"}} -ne "a" "a": {{ne "a" "a"}} -ne "a" "b": {{ne "a" "b"}} - -lt: -lt 1 "2": {{lt 1 "2"}} -lt 2 2 : {{lt 2 2 }} -lt "a" "b": {{lt "a" "b"}} - -le: -le 1 "2": {{le 1 "2"}} -le 2 1 : {{le 2 1 }} -le "a" "a": {{le "a" "a"}} - -gt: -gt 1 "2": {{gt 1 "2"}} -gt 2 1 : {{gt 2 1 }} -gt "a" "a": {{gt "a" "a"}} - -ge: -ge 1 "2": {{ge 1 "2"}} -ge 2 1 : {{ge 2 1 }} -ge "a" "a": {{ge "a" "a"}} -` - content, err := g.View().ParseContent(tplContent, nil) - if err != nil { - panic(err) - } - fmt.Println(content) -} diff --git a/.example/os/gview/build_in_funcs/issue359-1.go b/.example/os/gview/build_in_funcs/issue359-1.go deleted file mode 100644 index 842910e4d..000000000 --- a/.example/os/gview/build_in_funcs/issue359-1.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - tplContent := ` -{{"我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人"| strlimit 10 "..."}} -` - content, err := g.View().ParseContent(tplContent, nil) - fmt.Println(err) - fmt.Println(content) -} diff --git a/.example/os/gview/build_in_funcs/issue359-2.go b/.example/os/gview/build_in_funcs/issue359-2.go deleted file mode 100644 index f05041bee..000000000 --- a/.example/os/gview/build_in_funcs/issue359-2.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - s := "我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人" - tplContent := ` -{{.str | strlimit 10 "..."}} -` - content, err := g.View().ParseContent(tplContent, g.Map{ - "str": s, - }) - fmt.Println(err) - fmt.Println(content) -} diff --git a/.example/os/gview/define/main.go b/.example/os/gview/define/main.go deleted file mode 100644 index 95a9c87b7..000000000 --- a/.example/os/gview/define/main.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gfile" -) - -func main() { - v := g.View() - v.AddPath(gfile.MainPkgPath() + gfile.Separator + "template") - b, err := v.Parse("index.html", map[string]interface{}{ - "k": "v", - }) - if err != nil { - panic(err) - } - fmt.Println(string(b)) - -} diff --git a/.example/os/gview/define/template/index.html b/.example/os/gview/define/template/index.html deleted file mode 100644 index 88d49c89d..000000000 --- a/.example/os/gview/define/template/index.html +++ /dev/null @@ -1,8 +0,0 @@ -{{define "test"}} - test content {{.}} -{{end}} - - -1{{.var}}2 -{{include "subs/sub.html" .}} - diff --git a/.example/os/gview/define/template/subs/sub.html b/.example/os/gview/define/template/subs/sub.html deleted file mode 100644 index 0be3088c3..000000000 --- a/.example/os/gview/define/template/subs/sub.html +++ /dev/null @@ -1,4 +0,0 @@ -3 -{{template "test" .}} -4 -{{.var2}} \ No newline at end of file diff --git a/.example/os/gview/delimiters/gview_delimiters.go b/.example/os/gview/delimiters/gview_delimiters.go deleted file mode 100644 index 139c198d6..000000000 --- a/.example/os/gview/delimiters/gview_delimiters.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - v := g.View() - v.SetDelimiters("${", "}") - b, err := v.Parse("gview_delimiters.tpl", map[string]interface{}{ - "k": "v", - }) - fmt.Println(err) - fmt.Println(string(b)) -} diff --git a/.example/os/gview/delimiters/gview_delimiters.tpl b/.example/os/gview/delimiters/gview_delimiters.tpl deleted file mode 100644 index d5e4b51e6..000000000 --- a/.example/os/gview/delimiters/gview_delimiters.tpl +++ /dev/null @@ -1 +0,0 @@ -test.tpl content, vars: ${.} \ No newline at end of file diff --git a/.example/os/gview/func_html/func_html.go b/.example/os/gview/func_html/func_html.go deleted file mode 100644 index 0f75aa607..000000000 --- a/.example/os/gview/func_html/func_html.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gview" -) - -func main() { - if c, err := gview.ParseContent(`{{"
测试
模板引擎默认处理HTML标签\n"}}`, nil); err == nil { - g.Dump(c) - } else { - g.Dump(c) - } - if c, err := gview.ParseContent(`{{"
测试
去掉HTML标签\n"|text}}`, nil); err == nil { - g.Dump(c) - } else { - g.Dump(c) - } - if c, err := gview.ParseContent(`{{"
测试
保留HTML标签\n"|html}}`, nil); err == nil { - g.Dump(c) - } else { - g.Dump(c) - } -} diff --git a/.example/os/gview/func_text/func_text.go b/.example/os/gview/func_text/func_text.go deleted file mode 100644 index 390df9cbc..000000000 --- a/.example/os/gview/func_text/func_text.go +++ /dev/null @@ -1,10 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/os/gview" - "github.com/gogf/gf/v2/util/gutil" -) - -func main() { - gutil.Dump(gview.ParseContent(`{{"
测试
去掉HTML标签"|text}}`, nil)) -} diff --git a/.example/os/gview/hot_update/controller_hot_update.go b/.example/os/gview/hot_update/controller_hot_update.go deleted file mode 100644 index e3734482c..000000000 --- a/.example/os/gview/hot_update/controller_hot_update.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/frame/gmvc" -) - -func init() { - g.View().SetPath(`D:\Workspace\Go\GOPATH\src\gitee.com\johng\gf\geg\os\gview`) -} - -// 测试控制器注册模板热更新机制 -type Controller struct { - gmvc.Controller -} - -// 测试模板热更新机制 -func (c *Controller) Test() { - b, _ := c.View.Parse("gview.tpl") - c.Response.Write(b) -} - -func main() { - s := g.Server() - s.BindController("/", &Controller{}) - s.Run() -} diff --git a/.example/os/gview/hot_update/gview_hot_update.go b/.example/os/gview/hot_update/gview_hot_update.go deleted file mode 100644 index 70b7f1415..000000000 --- a/.example/os/gview/hot_update/gview_hot_update.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - v := g.View() - v.SetPath(`D:\Workspace\Go\GOPATH\src\gitee.com\johng\gf\geg\os\gview`) - gtime.SetInterval(time.Second, func() bool { - b, _ := v.Parse("gview.tpl", nil) - fmt.Println(string(b)) - return true - }) - select {} -} diff --git a/.example/os/gview/hot_update/web_hot_update.go b/.example/os/gview/hot_update/web_hot_update.go deleted file mode 100644 index 31aab9192..000000000 --- a/.example/os/gview/hot_update/web_hot_update.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - g.View().SetPath(`D:\Workspace\Go\GOPATH\src\gitee.com\johng\gf\geg\os\gview`) - b, _ := g.View().Parse("gview.tpl", nil) - r.Response.Write(b) - }) - s.Run() -} diff --git a/.example/os/gview/i18n/i18n.go b/.example/os/gview/i18n/i18n.go deleted file mode 100644 index c6fa628db..000000000 --- a/.example/os/gview/i18n/i18n.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - content := `{{.name}} says "a{#hello}{#world}!"` - result1, _ := g.View().ParseContent(content, g.Map{ - "name": "john", - "I18nLanguage": "zh-CN", - }) - fmt.Println(result1) - - result2, _ := g.View().ParseContent(content, g.Map{ - "name": "john", - "I18nLanguage": "ja", - }) - fmt.Println(result2) -} diff --git a/.example/os/gview/include/main.go b/.example/os/gview/include/main.go deleted file mode 100644 index 0fdd1d642..000000000 --- a/.example/os/gview/include/main.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gfile" -) - -func main() { - v := g.View() - // 设置模板目录为当前main.go所在目录下的template目录 - v.AddPath(gfile.MainPkgPath() + gfile.Separator + "template2") - b, err := v.Parse("index.html", map[string]interface{}{ - "k": "v", - }) - if err != nil { - panic(err) - } - fmt.Println(string(b)) -} diff --git a/.example/os/gview/include/template/index.html b/.example/os/gview/include/template/index.html deleted file mode 100644 index f534c4417..000000000 --- a/.example/os/gview/include/template/index.html +++ /dev/null @@ -1,2 +0,0 @@ -{{include "subs/sub.html" .}} - diff --git a/.example/os/gview/include/template/subs/sub.html b/.example/os/gview/include/template/subs/sub.html deleted file mode 100644 index 91012a681..000000000 --- a/.example/os/gview/include/template/subs/sub.html +++ /dev/null @@ -1 +0,0 @@ -{{.}} \ No newline at end of file diff --git a/.example/os/gview/layout/layout1/main.go b/.example/os/gview/layout/layout1/main.go deleted file mode 100644 index 644e59568..000000000 --- a/.example/os/gview/layout/layout1/main.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.WriteTpl("layout.html", g.Map{ - "header": "This is header", - "container": "This is container", - "footer": "This is footer", - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/os/gview/layout/layout1/template/container.html b/.example/os/gview/layout/layout1/template/container.html deleted file mode 100644 index 4f6af6313..000000000 --- a/.example/os/gview/layout/layout1/template/container.html +++ /dev/null @@ -1,3 +0,0 @@ -{{define "container"}} -

{{.container}}

-{{end}} \ No newline at end of file diff --git a/.example/os/gview/layout/layout1/template/footer.html b/.example/os/gview/layout/layout1/template/footer.html deleted file mode 100644 index 8a5f09a53..000000000 --- a/.example/os/gview/layout/layout1/template/footer.html +++ /dev/null @@ -1,3 +0,0 @@ -{{define "footer"}} -

{{.footer}}

-{{end}} \ No newline at end of file diff --git a/.example/os/gview/layout/layout1/template/header.html b/.example/os/gview/layout/layout1/template/header.html deleted file mode 100644 index bc500316a..000000000 --- a/.example/os/gview/layout/layout1/template/header.html +++ /dev/null @@ -1,3 +0,0 @@ -{{define "header"}} -

{{.header}}

-{{end}} \ No newline at end of file diff --git a/.example/os/gview/layout/layout1/template/layout.html b/.example/os/gview/layout/layout1/template/layout.html deleted file mode 100644 index 223fce6b8..000000000 --- a/.example/os/gview/layout/layout1/template/layout.html +++ /dev/null @@ -1,15 +0,0 @@ - - - - GoFrame Layout - {{template "header" .}} - - -
- {{template "container" .}} -
- - - \ No newline at end of file diff --git a/.example/os/gview/layout/layout2/main.go b/.example/os/gview/layout/layout2/main.go deleted file mode 100644 index 5f7d8779f..000000000 --- a/.example/os/gview/layout/layout2/main.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/main1", func(r *ghttp.Request) { - r.Response.WriteTpl("layout.html", g.Map{ - "name": "smith", - "mainTpl": "main/main1.html", - }) - }) - s.BindHandler("/main2", func(r *ghttp.Request) { - r.Response.WriteTpl("layout.html", g.Map{ - "name": "john", - "mainTpl": "main/main2.html", - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/os/gview/layout/layout2/template/footer.html b/.example/os/gview/layout/layout2/template/footer.html deleted file mode 100644 index 83ae25b65..000000000 --- a/.example/os/gview/layout/layout2/template/footer.html +++ /dev/null @@ -1 +0,0 @@ -

FOOTER

\ No newline at end of file diff --git a/.example/os/gview/layout/layout2/template/header.html b/.example/os/gview/layout/layout2/template/header.html deleted file mode 100644 index b9cb0a77c..000000000 --- a/.example/os/gview/layout/layout2/template/header.html +++ /dev/null @@ -1 +0,0 @@ -

HEADER

\ No newline at end of file diff --git a/.example/os/gview/layout/layout2/template/layout.html b/.example/os/gview/layout/layout2/template/layout.html deleted file mode 100644 index 9f58c21a0..000000000 --- a/.example/os/gview/layout/layout2/template/layout.html +++ /dev/null @@ -1,3 +0,0 @@ -{{include "header.html" .}} -{{include .mainTpl .}} -{{include "footer.html" .}} \ No newline at end of file diff --git a/.example/os/gview/layout/layout2/template/main/main1.html b/.example/os/gview/layout/layout2/template/main/main1.html deleted file mode 100644 index fdb0016f3..000000000 --- a/.example/os/gview/layout/layout2/template/main/main1.html +++ /dev/null @@ -1 +0,0 @@ -

MAIN1

\ No newline at end of file diff --git a/.example/os/gview/layout/layout2/template/main/main2.html b/.example/os/gview/layout/layout2/template/main/main2.html deleted file mode 100644 index 608512269..000000000 --- a/.example/os/gview/layout/layout2/template/main/main2.html +++ /dev/null @@ -1 +0,0 @@ -

MAIN2

\ No newline at end of file diff --git a/.example/os/gview/object/object.go b/.example/os/gview/object/object.go deleted file mode 100644 index 594a41ab2..000000000 --- a/.example/os/gview/object/object.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" -) - -type T struct { - Name string -} - -func (t *T) Hello(name string) string { - return "Hello " + name -} - -func (t *T) Test() string { - return "This is test" -} - -func main() { - t := &T{"John"} - v := g.View() - content := `{{.t.Hello "there"}}, my name's {{.t.Name}}. {{.t.Test}}.` - if r, err := v.ParseContent(content, g.Map{"t": t}); err != nil { - g.Dump(err) - } else { - g.Dump(r) - } -} diff --git a/.example/os/gview/resource/main1.go b/.example/os/gview/resource/main1.go deleted file mode 100644 index 88b96590e..000000000 --- a/.example/os/gview/resource/main1.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gres" - _ "github.com/gogf/gf/v2/os/gres/testdata" -) - -func main() { - gres.Dump() - - v := g.View() - v.SetPath("files/template/layout1") - s, err := v.Parse("layout.html") - fmt.Println(err) - fmt.Println(s) -} diff --git a/.example/os/gview/resource/main2.go b/.example/os/gview/resource/main2.go deleted file mode 100644 index 9892c4fc8..000000000 --- a/.example/os/gview/resource/main2.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gres" - _ "github.com/gogf/gf/v2/os/gres/testdata" -) - -func main() { - gres.Dump() - - v := g.View() - v.SetPath("files/template/layout2") - s, err := v.Parse("layout.html", g.Map{ - "mainTpl": "main/main1.html", - }) - fmt.Println(err) - fmt.Println(s) -} diff --git a/.example/os/gview/resource/main3.go b/.example/os/gview/resource/main3.go deleted file mode 100644 index db3e029ed..000000000 --- a/.example/os/gview/resource/main3.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gres" - _ "github.com/gogf/gf/v2/os/gres/testdata" -) - -func main() { - gres.Dump() - - v := g.View() - s, err := v.Parse("index.html") - fmt.Println(err) - fmt.Println(s) -} diff --git a/.example/text/gregex/gregex.go b/.example/text/gregex/gregex.go deleted file mode 100644 index 5c807daa8..000000000 --- a/.example/text/gregex/gregex.go +++ /dev/null @@ -1,12 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/text/gregex" -) - -func main() { - match, _ := gregex.MatchString(`(\w+).+\-\-\s*(.+)`, `GF is best! -- John`) - fmt.Printf(`%s says "%s" is the one he loves!`, match[2], match[1]) -} diff --git a/.example/text/gstr/gstr_hidestr.go b/.example/text/gstr/gstr_hidestr.go deleted file mode 100644 index 1b7e9b268..000000000 --- a/.example/text/gstr/gstr_hidestr.go +++ /dev/null @@ -1,12 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/text/gstr" -) - -func main() { - fmt.Println(gstr.HideStr("热爱GF热爱生活", 20, "*")) - fmt.Println(gstr.HideStr("热爱GF热爱生活", 50, "*")) -} diff --git a/.example/text/gstr/gstr_substr.go b/.example/text/gstr/gstr_substr.go deleted file mode 100644 index 75898a51e..000000000 --- a/.example/text/gstr/gstr_substr.go +++ /dev/null @@ -1,12 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/text/gstr" -) - -func main() { - fmt.Println(gstr.SubStr("我是中国人", 2)) - fmt.Println(gstr.SubStr("我是中国人", 2, 2)) -} diff --git a/.example/util/gconv/gconv.go b/.example/util/gconv/gconv.go deleted file mode 100644 index 1f148d906..000000000 --- a/.example/util/gconv/gconv.go +++ /dev/null @@ -1,31 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - i := 123.456 - fmt.Printf("%10s %v\n", "Int:", gconv.Int(i)) - fmt.Printf("%10s %v\n", "Int8:", gconv.Int8(i)) - fmt.Printf("%10s %v\n", "Int16:", gconv.Int16(i)) - fmt.Printf("%10s %v\n", "Int32:", gconv.Int32(i)) - fmt.Printf("%10s %v\n", "Int64:", gconv.Int64(i)) - fmt.Printf("%10s %v\n", "Uint:", gconv.Uint(i)) - fmt.Printf("%10s %v\n", "Uint8:", gconv.Uint8(i)) - fmt.Printf("%10s %v\n", "Uint16:", gconv.Uint16(i)) - fmt.Printf("%10s %v\n", "Uint32:", gconv.Uint32(i)) - fmt.Printf("%10s %v\n", "Uint64:", gconv.Uint64(i)) - fmt.Printf("%10s %v\n", "Float32:", gconv.Float32(i)) - fmt.Printf("%10s %v\n", "Float64:", gconv.Float64(i)) - fmt.Printf("%10s %v\n", "Bool:", gconv.Bool(i)) - fmt.Printf("%10s %v\n", "String:", gconv.String(i)) - - fmt.Printf("%10s %v\n", "Bytes:", gconv.Bytes(i)) - fmt.Printf("%10s %v\n", "Strings:", gconv.Strings(i)) - fmt.Printf("%10s %v\n", "Ints:", gconv.Ints(i)) - fmt.Printf("%10s %v\n", "Floats:", gconv.Floats(i)) - fmt.Printf("%10s %v\n", "Interfaces:", gconv.Interfaces(i)) -} diff --git a/.example/util/gconv/gconv_map1.go b/.example/util/gconv/gconv_map1.go deleted file mode 100644 index e1ca4658a..000000000 --- a/.example/util/gconv/gconv_map1.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - type User struct { - Uid int `json:"uid"` - Name string `json:"name"` - } - // 对象 - fmt.Println(gconv.Map(User{ - Uid: 1, - Name: "john", - })) - // 对象指针 - fmt.Println(gconv.Map(&User{ - Uid: 1, - Name: "john", - })) - - // 任意map类型 - fmt.Println(gconv.Map(map[int]int{ - 100: 10000, - })) -} diff --git a/.example/util/gconv/gconv_map2.go b/.example/util/gconv/gconv_map2.go deleted file mode 100644 index 52a3c4564..000000000 --- a/.example/util/gconv/gconv_map2.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - type User struct { - Uid int - Name string `gconv:"-"` - NickName string `gconv:"nickname, omitempty"` - Pass1 string `gconv:"password1"` - Pass2 string `gconv:"password2"` - } - user := User{ - Uid: 100, - Name: "john", - Pass1: "123", - Pass2: "456", - } - fmt.Println(gconv.Map(user)) -} diff --git a/.example/util/gconv/gconv_map_deep.go b/.example/util/gconv/gconv_map_deep.go deleted file mode 100644 index 80a2a82ce..000000000 --- a/.example/util/gconv/gconv_map_deep.go +++ /dev/null @@ -1,32 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - type Ids struct { - Id int `c:"id"` - Uid int `c:"uid"` - } - type Base struct { - Ids - CreateTime string `c:"create_time"` - } - type User struct { - Base - Passport string `c:"passport"` - Password string `c:"password"` - Nickname string `c:"nickname"` - } - user := new(User) - user.Id = 1 - user.Uid = 100 - user.Nickname = "John" - user.Passport = "johng" - user.Password = "123456" - user.CreateTime = "2019" - g.Dump(gconv.Map(user)) - g.Dump(gconv.MapDeep(user)) -} diff --git a/.example/util/gconv/gconv_map_tag.go b/.example/util/gconv/gconv_map_tag.go deleted file mode 100644 index 727f4bf83..000000000 --- a/.example/util/gconv/gconv_map_tag.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - type User struct { - Id int `json:"uid"` - Name string `my-tag:"nick-name" json:"name"` - } - user := &User{ - Id: 1, - Name: "john", - } - g.Dump(gconv.Map(user, "my-tag")) -} diff --git a/.example/util/gconv/gconv_slice.go b/.example/util/gconv/gconv_slice.go deleted file mode 100644 index c306e2cac..000000000 --- a/.example/util/gconv/gconv_slice.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/util/gconv" -) - -// struct转slice -func main() { - type User struct { - Uid int - Name string - } - // 对象 - fmt.Println(gconv.Interfaces(User{ - Uid: 1, - Name: "john", - })) - // 指针 - fmt.Println(gconv.Interfaces(&User{ - Uid: 1, - Name: "john", - })) -} diff --git a/.example/util/gconv/gconv_struct1.go b/.example/util/gconv/gconv_struct1.go deleted file mode 100644 index 1cd680b5d..000000000 --- a/.example/util/gconv/gconv_struct1.go +++ /dev/null @@ -1,47 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -type User struct { - Uid int - Name string - Site_Url string - NickName string - Pass1 string `gconv:"password1"` - Pass2 string `gconv:"password2"` -} - -func main() { - user := (*User)(nil) - - // 使用默认映射规则绑定属性值到对象 - user = new(User) - params1 := g.Map{ - "uid": 1, - "Name": "john", - "siteurl": "https://goframe.org", - "nick_name": "johng", - "PASS1": "123", - "PASS2": "456", - } - if err := gconv.Struct(params1, user); err == nil { - g.Dump(user) - } - - // 使用struct tag映射绑定属性值到对象 - user = new(User) - params2 := g.Map{ - "uid": 2, - "name": "smith", - "site-url": "https://goframe.org", - "nick name": "johng", - "password1": "111", - "password2": "222", - } - if err := gconv.Struct(params2, user); err == nil { - g.Dump(user) - } -} diff --git a/.example/util/gconv/gconv_struct2.go b/.example/util/gconv/gconv_struct2.go deleted file mode 100644 index 5d09c723b..000000000 --- a/.example/util/gconv/gconv_struct2.go +++ /dev/null @@ -1,30 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -// 使用默认映射规则绑定属性值到对象 -func main() { - type User struct { - Uid int - Name string - SiteUrl string - Pass1 string - Pass2 string - } - user := new(User) - params := g.Map{ - "uid": 1, - "Name": "john", - "site_url": "https://goframe.org", - "PASS1": "123", - "PASS2": "456", - } - if err := gconv.Struct(params, user); err == nil { - fmt.Println(user) - } -} diff --git a/.example/util/gconv/gconv_struct4.go b/.example/util/gconv/gconv_struct4.go deleted file mode 100644 index c9dba3445..000000000 --- a/.example/util/gconv/gconv_struct4.go +++ /dev/null @@ -1,41 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - type Score struct { - Name string - Result int - } - type User1 struct { - Scores Score - } - type User2 struct { - Scores *Score - } - - user1 := new(User1) - user2 := new(User2) - scores := g.Map{ - "Scores": g.Map{ - "Name": "john", - "Result": 100, - }, - } - - if err := gconv.Struct(scores, user1); err != nil { - fmt.Println(err) - } else { - g.Dump(user1) - } - if err := gconv.Struct(scores, user2); err != nil { - fmt.Println(err) - } else { - g.Dump(user2) - } -} diff --git a/.example/util/gconv/gconv_struct5.go b/.example/util/gconv/gconv_struct5.go deleted file mode 100644 index 2351653a7..000000000 --- a/.example/util/gconv/gconv_struct5.go +++ /dev/null @@ -1,33 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - type Score struct { - Name string - Result int - } - type User struct { - Scores []Score - } - - user := new(User) - scores := g.Map{ - "Scores": g.Map{ - "Name": "john", - "Result": 100, - }, - } - - // 嵌套struct转换,属性为slice类型,数值为map类型 - if err := gconv.Struct(scores, user); err != nil { - fmt.Println(err) - } else { - g.Dump(user) - } -} diff --git a/.example/util/gconv/gconv_struct6.go b/.example/util/gconv/gconv_struct6.go deleted file mode 100644 index a7681a0e1..000000000 --- a/.example/util/gconv/gconv_struct6.go +++ /dev/null @@ -1,39 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - type Score struct { - Name string - Result int - } - type User struct { - Scores []*Score - } - - user := new(User) - scores := g.Map{ - "Scores": g.Slice{ - g.Map{ - "Name": "john", - "Result": 100, - }, - g.Map{ - "Name": "smith", - "Result": 60, - }, - }, - } - - // 嵌套struct转换,属性为slice类型,数值为slice map类型 - if err := gconv.Struct(scores, user); err != nil { - fmt.Println(err) - } else { - g.Dump(user) - } -} diff --git a/.example/util/gconv/gconv_struct_create.go b/.example/util/gconv/gconv_struct_create.go deleted file mode 100644 index 211cfea46..000000000 --- a/.example/util/gconv/gconv_struct_create.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - type User struct { - Uid int - Name string - } - user := (*User)(nil) - params := g.Map{ - "uid": 1, - "name": "john", - } - err := gconv.Struct(params, &user) - if err != nil { - panic(err) - } - g.Dump(user) -} diff --git a/.example/util/gconv/gconv_struct_deep.go b/.example/util/gconv/gconv_struct_deep.go deleted file mode 100644 index 565766321..000000000 --- a/.example/util/gconv/gconv_struct_deep.go +++ /dev/null @@ -1,34 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - type Ids struct { - Id int `json:"id"` - Uid int `json:"uid"` - } - type Base struct { - Ids - CreateTime string `json:"create_time"` - } - type User struct { - Base - Passport string `json:"passport"` - Password string `json:"password"` - Nickname string `json:"nickname"` - } - data := g.Map{ - "id": 1, - "uid": 100, - "passport": "johng", - "password": "123456", - "nickname": "John", - "create_time": "2019", - } - user := new(User) - gconv.StructDeep(data, user) - g.Dump(user) -} diff --git a/.example/util/gconv/strings.go b/.example/util/gconv/strings.go deleted file mode 100644 index 258d6d638..000000000 --- a/.example/util/gconv/strings.go +++ /dev/null @@ -1,11 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - fmt.Println(gconv.Strings([]int{1, 2, 3})) -} diff --git a/.example/util/gconv/time1.go b/.example/util/gconv/time1.go deleted file mode 100644 index 825d49f5f..000000000 --- a/.example/util/gconv/time1.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - now := time.Now() - t := gconv.Time(now.UnixNano() / 100) - fmt.Println(now.UnixNano()) - fmt.Println(t.Nanosecond()) - fmt.Println(now.Nanosecond()) -} diff --git a/.example/util/gconv/time2.go b/.example/util/gconv/time2.go deleted file mode 100644 index c7d77a406..000000000 --- a/.example/util/gconv/time2.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - fmt.Println(gconv.Time("2018-06-07").String()) - - fmt.Println(gconv.Time("2018-06-07 13:01:02").String()) - - fmt.Println(gconv.Time("2018-06-07 13:01:02.096").String()) - -} diff --git a/.example/util/gpage/gpage.go b/.example/util/gpage/gpage.go deleted file mode 100644 index cc39411aa..000000000 --- a/.example/util/gpage/gpage.go +++ /dev/null @@ -1,38 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gview" -) - -func main() { - s := g.Server() - s.BindHandler("/page/demo", func(r *ghttp.Request) { - page := r.GetPage(100, 10) - buffer, _ := gview.ParseContent(` - - - - - -
{{.page1}}
-
{{.page2}}
-
{{.page3}}
-
{{.page4}}
- - - `, g.Map{ - "page1": page.GetContent(1), - "page2": page.GetContent(2), - "page3": page.GetContent(3), - "page4": page.GetContent(4), - }) - r.Response.Write(buffer) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/util/gpage/gpage_ajax.go b/.example/util/gpage/gpage_ajax.go deleted file mode 100644 index 5451472a1..000000000 --- a/.example/util/gpage/gpage_ajax.go +++ /dev/null @@ -1,47 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gview" -) - -func main() { - s := g.Server() - s.BindHandler("/page/ajax", func(r *ghttp.Request) { - page := r.GetPage(100, 10) - page.AjaxActionName = "DoAjax" - buffer, _ := gview.ParseContent(r.Context(), ` - - - - - - - -
{{.page1}}
-
{{.page2}}
-
{{.page3}}
-
{{.page4}}
- - - `, g.Map{ - "page1": page.GetContent(1), - "page2": page.GetContent(2), - "page3": page.GetContent(3), - "page4": page.GetContent(4), - }) - r.Response.Write(buffer) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/util/gpage/gpage_custom1.go b/.example/util/gpage/gpage_custom1.go deleted file mode 100644 index a9a0f9a60..000000000 --- a/.example/util/gpage/gpage_custom1.go +++ /dev/null @@ -1,47 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gview" - "github.com/gogf/gf/v2/text/gstr" - "github.com/gogf/gf/v2/util/gpage" -) - -// wrapContent wraps each of the page tag with html li and ul. -func wrapContent(page *gpage.Page) string { - content := page.GetContent(4) - content = gstr.ReplaceByMap(content, map[string]string{ - "": "/span>", - "": "/a>", - }) - return "
    " + content + "
" -} - -func main() { - s := g.Server() - s.BindHandler("/page/custom1/*page", func(r *ghttp.Request) { - page := r.GetPage(100, 10) - content := wrapContent(page) - buffer, _ := gview.ParseContent(` - - - - - -
{{.page}}
- - - `, g.Map{ - "page": content, - }) - r.Response.Write(buffer) - }) - s.SetPort(10000) - s.Run() -} diff --git a/.example/util/gpage/gpage_custom2.go b/.example/util/gpage/gpage_custom2.go deleted file mode 100644 index 44b012456..000000000 --- a/.example/util/gpage/gpage_custom2.go +++ /dev/null @@ -1,47 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gview" - "github.com/gogf/gf/v2/util/gpage" -) - -// pageContent customizes the page tag name. -func pageContent(page *gpage.Page) string { - page.NextPageTag = "NextPage" - page.PrevPageTag = "PrevPage" - page.FirstPageTag = "HomePage" - page.LastPageTag = "LastPage" - pageStr := page.FirstPage() - pageStr += page.PrevPage() - pageStr += page.PageBar() - pageStr += page.NextPage() - pageStr += page.LastPage() - return pageStr -} - -func main() { - s := g.Server() - s.BindHandler("/page/custom2/*page", func(r *ghttp.Request) { - page := r.GetPage(100, 10) - buffer, _ := gview.ParseContent(` - - - - - -
{{.page}}
- - - `, g.Map{ - "page": pageContent(page), - }) - r.Response.Write(buffer) - }) - s.SetPort(10000) - s.Run() -} diff --git a/.example/util/gpage/gpage_static1.go b/.example/util/gpage/gpage_static1.go deleted file mode 100644 index 0d852d31a..000000000 --- a/.example/util/gpage/gpage_static1.go +++ /dev/null @@ -1,38 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gview" -) - -func main() { - s := g.Server() - s.BindHandler("/page/static/*page", func(r *ghttp.Request) { - page := r.GetPage(100, 10) - buffer, _ := gview.ParseContent(` - - - - - -
{{.page1}}
-
{{.page2}}
-
{{.page3}}
-
{{.page4}}
- - - `, g.Map{ - "page1": page.GetContent(1), - "page2": page.GetContent(2), - "page3": page.GetContent(3), - "page4": page.GetContent(4), - }) - r.Response.Write(buffer) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/util/gpage/gpage_static2.go b/.example/util/gpage/gpage_static2.go deleted file mode 100644 index e3a1e4680..000000000 --- a/.example/util/gpage/gpage_static2.go +++ /dev/null @@ -1,38 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gview" -) - -func main() { - s := g.Server() - s.BindHandler("/:obj/*action/{page}.html", func(r *ghttp.Request) { - page := r.GetPage(100, 10) - buffer, _ := gview.ParseContent(` - - - - - -
{{.page1}}
-
{{.page2}}
-
{{.page3}}
-
{{.page4}}
- - - `, g.Map{ - "page1": page.GetContent(1), - "page2": page.GetContent(2), - "page3": page.GetContent(3), - "page4": page.GetContent(4), - }) - r.Response.Write(buffer) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/util/gpage/gpage_template.go b/.example/util/gpage/gpage_template.go deleted file mode 100644 index ba6e1a3a6..000000000 --- a/.example/util/gpage/gpage_template.go +++ /dev/null @@ -1,39 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gview" -) - -func main() { - s := g.Server() - s.BindHandler("/page/template/{page}.html", func(r *ghttp.Request) { - page := r.GetPage(100, 10) - page.UrlTemplate = "/order/list/{.page}.html" - buffer, _ := gview.ParseContent(` - - - - - -
{{.page1}}
-
{{.page2}}
-
{{.page3}}
-
{{.page4}}
- - - `, g.Map{ - "page1": page.GetContent(1), - "page2": page.GetContent(2), - "page3": page.GetContent(3), - "page4": page.GetContent(4), - }) - r.Response.Write(buffer) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/util/grand/grand.go b/.example/util/grand/grand.go deleted file mode 100644 index f36b13bad..000000000 --- a/.example/util/grand/grand.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/util/grand" -) - -func main() { - for i := 0; i < 100; i++ { - fmt.Println(grand.S(16)) - } - for i := 0; i < 100; i++ { - fmt.Println(grand.N(0, 99999999)) - } -} diff --git a/.example/util/grand/rand.go b/.example/util/grand/rand.go deleted file mode 100644 index 9cfc28459..000000000 --- a/.example/util/grand/rand.go +++ /dev/null @@ -1,83 +0,0 @@ -package main - -import ( - crand "crypto/rand" - "encoding/binary" - "fmt" - mrand "math/rand" - "os" - "time" - - "github.com/gogf/gf/v2/os/gtime" -) - -// int 随机 -func a1() { - s1 := mrand.NewSource(time.Now().UnixNano()) - r1 := mrand.New(s1) - for i := 0; i < 10; i++ { - fmt.Printf("%d ", r1.Intn(100)) - } - fmt.Printf("\n") -} - -// 0/1 true/false 随机 -func a2() { - // Go编程这本书上例子. - ch := make(chan int, 1) - for i := 0; i < 10; i++ { - select { - case ch <- 0: - case ch <- 1: - } - r := <-ch - fmt.Printf("%d ", r) - } - fmt.Printf("\n") -} - -//真随机 -- 用标准库封装好的 -func a3() { - b := make([]byte, 16) - // On Unix-like systems, Reader reads from /dev/urandom. - // On Windows systems, Reader uses the CryptGenRandom API. - _, err := crand.Read(b) //返回长度为0 - 32 的值 - if err != nil { - fmt.Println("[a3] ", err) - return - } - fmt.Println("[a3] b:", b) -} - -//真随机 -- 我们直接调真随机文件生成了事。 但注意,它是阻塞式的。 -func a4() { - f, err := os.Open("/dev/random") - if err != nil { - fmt.Println("[a4] ", err) - return - } - defer f.Close() - - b1 := make([]byte, 16) - _, err = f.Read(b1) - if err != nil { - fmt.Println("[a4] ", err) - return - } - fmt.Println("[a4] Read /dev/random:", b1) -} - -// a3 的另一种实现方式 -func a5() { - var ret int32 - binary.Read(crand.Reader, binary.LittleEndian, &ret) - fmt.Println("[a5] ret:", ret) -} - -func main() { - fmt.Println("a1:", gtime.FuncCost(a1)) - fmt.Println("a2:", gtime.FuncCost(a2)) - fmt.Println("a3:", gtime.FuncCost(a3)) - fmt.Println("a4:", gtime.FuncCost(a4)) - fmt.Println("a5:", gtime.FuncCost(a5)) -} diff --git a/.example/util/guid/guid.go b/.example/util/guid/guid.go deleted file mode 100644 index f88c37985..000000000 --- a/.example/util/guid/guid.go +++ /dev/null @@ -1,13 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/util/guid" -) - -func main() { - for i := 0; i < 100; i++ { - s := guid.S() - fmt.Println(s, len(s)) - } -} diff --git a/.example/util/guid/guid_length.go b/.example/util/guid/guid_length.go deleted file mode 100644 index c04c594f8..000000000 --- a/.example/util/guid/guid_length.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "fmt" - "math" - "strconv" -) - -func main() { - // 36*36^2+36*36+36 - var s string - fmt.Println(strconv.ParseUint("zzz", 36, 3)) - fmt.Println(1 << 1) - // MaxInt64 - s = strconv.FormatUint(math.MaxUint64, 16) - fmt.Println(s, len(s)) - // PID - s = strconv.FormatInt(1000000, 36) - fmt.Println(s, len(s)) -} diff --git a/.example/util/guid/guid_unique.go b/.example/util/guid/guid_unique.go deleted file mode 100644 index f804c45a6..000000000 --- a/.example/util/guid/guid_unique.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/util/guid" -) - -func main() { - for i := 0; i < 100; i++ { - s := guid.S([]byte("123")) - fmt.Println(s, len(s)) - } - fmt.Println() - for i := 0; i < 100; i++ { - s := guid.S([]byte("123"), []byte("456")) - fmt.Println(s, len(s)) - } - fmt.Println() - for i := 0; i < 100; i++ { - s := guid.S([]byte("123"), []byte("456"), []byte("789")) - fmt.Println(s, len(s)) - } -} diff --git a/.example/util/gutil/dump.go b/.example/util/gutil/dump.go deleted file mode 100644 index 5fa013bd4..000000000 --- a/.example/util/gutil/dump.go +++ /dev/null @@ -1,11 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/util/gutil" -) - -func main() { - gutil.Dump(map[interface{}]interface{}{ - 1: "john", - }) -} diff --git a/.example/util/gutil/stack.go b/.example/util/gutil/stack.go deleted file mode 100644 index 93e89cc68..000000000 --- a/.example/util/gutil/stack.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/util/gutil" -) - -func Test(s *interface{}) { - //debug.PrintStack() - gutil.PrintStack() -} - -func main() { - Test(nil) -} diff --git a/.example/util/gutil/try_catch.go b/.example/util/gutil/try_catch.go deleted file mode 100644 index b4c5e5487..000000000 --- a/.example/util/gutil/try_catch.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/util/gutil" -) - -func main() { - gutil.TryCatch(func() { - fmt.Println(1) - gutil.Throw("error") - fmt.Println(2) - }, func(err error) { - fmt.Println(err) - }) -} diff --git a/.example/util/gvalid/config.toml b/.example/util/gvalid/config.toml deleted file mode 100644 index 26beac3a7..000000000 --- a/.example/util/gvalid/config.toml +++ /dev/null @@ -1,14 +0,0 @@ - - - -# MySQL. -[database] - [database.default] - link = "mysql:root:12345678@tcp(127.0.0.1:3306)/test" - debug = true - - - - - - diff --git a/.example/util/gvalid/gvalid.go b/.example/util/gvalid/gvalid.go deleted file mode 100644 index 96c52b835..000000000 --- a/.example/util/gvalid/gvalid.go +++ /dev/null @@ -1,71 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gvalid" -) - -func main() { - //rule := "length:6,16" - //if m := gvalid.Check(context.TODO(), "123456", rule, nil); m != nil { - // fmt.Println(m) - //} - //if m := gvalid.Check(context.TODO(), "12345", rule, nil); m != nil { - // fmt.Println(m) - // // map[length:字段长度为6到16个字符] - //} - - //rule := "integer|between:6,16" - //msgs := "请输入一个整数|参数大小不对啊老铁" - //fmt.Println(gvalid.Check(context.TODO(), "5.66", rule, msgs)) - //// map[integer:请输入一个整数 between:参数大小不对啊老铁] - - //// 参数长度至少为6个数字或者6个字母,但是总长度不能超过16个字符 - //rule := `regex:\d{6,}|\D{6,}|max-length:16` - //if m := gvalid.Check(context.TODO(), "123456", rule, nil); m != nil { - // fmt.Println(m) - //} - //if m := gvalid.Check(context.TODO(), "abcde6", rule, nil); m != nil { - // fmt.Println(m) - // // map[regex:字段值不合法] - //} - - //params := map[string]string { - // "passport" : "john", - // "password" : "123456", - // "password2" : "1234567", - //} - //rules := map[string]string { - // "passport" : "required|length:6,16", - // "password" : "required|length:6,16|same:password2", - // "password2" : "required|length:6,16", - //} - //fmt.Println(gvalid.CheckMap(context.TODO(), params, rules)) - //// map[passport:map[length:字段长度为6到16个字符] password:map[same:字段值不合法]] - - params := map[string]interface{}{ - "passport": "john", - "password": "123456", - "password2": "1234567", - "name": "gf", - } - rules := map[string]string{ - "passport": "required|length:6,16", - "password": "required|length:6,16|same:password2", - "password2": "required|length:6,16", - "name": "size:5", - } - msgs := map[string]interface{}{ - "passport": "账号不能为空|账号长度应当在:min到:max之间", - "password": map[string]string{ - "required": "密码不能为空", - "same": "两次密码输入不相等", - }, - "name": "名字长度必须为:size", - } - if e := gvalid.CheckMap(context.TODO(), params, rules, msgs); e != nil { - g.Dump(e.Maps()) - } - // map[passport:map[length:账号长度应当在6到16之间] password:map[same:两次密码输入不相等]] -} diff --git a/.example/util/gvalid/gvalid_checkstructwithdata.go b/.example/util/gvalid/gvalid_checkstructwithdata.go deleted file mode 100644 index a281a8cd5..000000000 --- a/.example/util/gvalid/gvalid_checkstructwithdata.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" - "github.com/gogf/gf/v2/util/gvalid" -) - -func main() { - type User struct { - Name string `v:"required#请输入用户姓名"` - Type int `v:"required#请选择用户类型"` - } - data := g.Map{ - "name": "john", - } - user := User{} - if err := gconv.Scan(data, &user); err != nil { - panic(err) - } - err := gvalid.CheckStructWithData(context.TODO(), user, data, nil) - // 也可以使用 - // err := g.Validator().Data(data).CheckStruct(user) - if err != nil { - g.Dump(err.Items()) - } -} diff --git a/.example/util/gvalid/gvalid_custom_message.go b/.example/util/gvalid/gvalid_custom_message.go deleted file mode 100644 index e19a7beca..000000000 --- a/.example/util/gvalid/gvalid_custom_message.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import ( - "context" - "fmt" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gvalid" -) - -func main() { - g.I18n().SetLanguage("cn") - err := gvalid.Check(context.TODO(), "", "required", nil) - fmt.Println(err.String()) -} diff --git a/.example/util/gvalid/gvalid_error.go b/.example/util/gvalid/gvalid_error.go deleted file mode 100644 index 0d02396e0..000000000 --- a/.example/util/gvalid/gvalid_error.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gvalid" -) - -// 返回结果方法示例 -func main() { - type User struct { - Password string `gvalid:"password@password"` - ConfiemPassword string `gvalid:"confirm_password@password|same:password#|密码与确认密码不一致"` - } - - user := &User{ - Password: "123456", - ConfiemPassword: "", - } - - e := gvalid.CheckStruct(context.TODO(), user, nil) - g.Dump(e.Map()) - g.Dump(e.Maps()) - g.Dump(e.String()) - g.Dump(e.Strings()) - g.Dump(e.FirstItem()) - g.Dump(e.FirstRule()) - g.Dump(e.FirstString()) -} diff --git a/.example/util/gvalid/gvalid_i18n.go b/.example/util/gvalid/gvalid_i18n.go deleted file mode 100644 index 492b37174..000000000 --- a/.example/util/gvalid/gvalid_i18n.go +++ /dev/null @@ -1,38 +0,0 @@ -package main - -import ( - "context" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/i18n/gi18n" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - type User struct { - Name string `v:"required#ReuiredUserName"` - Type int `v:"required#ReuiredUserType"` - Project string `v:"size:10#MustSize"` - } - var ( - data = g.Map{ - "name": "john", - "project": "gf", - } - user = User{} - ctxEn = gi18n.WithLanguage(context.TODO(), "en") - ctxCh = gi18n.WithLanguage(context.TODO(), "zh-CN") - ) - - if err := gconv.Scan(data, &user); err != nil { - panic(err) - } - // 英文 - if err := g.Validator().Ctx(ctxEn).Data(data).CheckStruct(user); err != nil { - g.Dump(err.String()) - } - // 中文 - if err := g.Validator().Ctx(ctxCh).Data(data).CheckStruct(user); err != nil { - g.Dump(err.String()) - } -} diff --git a/.example/util/gvalid/gvalid_i18n_http.go b/.example/util/gvalid/gvalid_i18n_http.go deleted file mode 100644 index 308dcbbf1..000000000 --- a/.example/util/gvalid/gvalid_i18n_http.go +++ /dev/null @@ -1,35 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/net/ghttp" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/i18n/gi18n" -) - -func main() { - type User struct { - Name string `v:"required#ReuiredUserName"` - Type int `v:"required#ReuiredUserType"` - Project string `v:"size:10#MustSize"` - } - s := g.Server() - s.Group("/", func(group *ghttp.RouterGroup) { - group.Middleware(func(r *ghttp.Request) { - lang := r.GetString("lang", "zh-CN") - r.SetCtx(gi18n.WithLanguage(r.Context(), lang)) - r.Middleware.Next() - }) - group.GET("/validate", func(r *ghttp.Request) { - var ( - err error - user = User{} - ) - if err = r.Parse(&user); err != nil { - r.Response.WriteExit(err) - } - r.Response.WriteExit(user) - }) - }) - s.SetPort(8199) -} diff --git a/.example/util/gvalid/gvalid_result.go b/.example/util/gvalid/gvalid_result.go deleted file mode 100644 index f65a7fc41..000000000 --- a/.example/util/gvalid/gvalid_result.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gvalid" -) - -func main() { - type User struct { - Name string `gvalid:"name @required|length:6,30#请输入用户名称|用户名称长度不够哦"` - Pass1 string `gvalid:"password1@required|password3"` - Pass2 string `gvalid:"password2@required|password3|same:password1#||两次密码不一致,请重新输入"` - } - - user := &User{ - Name: "john", - Pass1: "Abc123!@#", - Pass2: "123", - } - - e := gvalid.CheckStruct(context.TODO(), user, nil) - g.Dump(e.String()) - g.Dump(e.FirstString()) -} diff --git a/.example/util/gvalid/gvalid_sequence.go b/.example/util/gvalid/gvalid_sequence.go deleted file mode 100644 index 5545b09a7..000000000 --- a/.example/util/gvalid/gvalid_sequence.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "context" - "fmt" - - "github.com/gogf/gf/v2/util/gvalid" -) - -func main() { - params := map[string]interface{}{ - "passport": "", - "password": "123456", - "password2": "1234567", - } - rules := []string{ - "passport@required|length:6,16#账号不能为空|账号长度应当在:min到:max之间", - "password@required|length:6,16|same:password2#密码不能为空}|两次密码输入不相等", - "password2@required|length:6,16#", - } - if e := gvalid.CheckMap(context.TODO(), params, rules); e != nil { - fmt.Println(e.Map()) - fmt.Println(e.FirstItem()) - fmt.Println(e.FirstString()) - } - // map[required:账号不能为空 length:账号长度应当在6到16之间] - // passport map[required:账号不能为空 length:账号长度应当在6到16之间] - // 账号不能为空 -} diff --git a/.example/util/gvalid/gvalid_struct1.go b/.example/util/gvalid/gvalid_struct1.go deleted file mode 100644 index 4b8678dba..000000000 --- a/.example/util/gvalid/gvalid_struct1.go +++ /dev/null @@ -1,36 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gvalid" -) - -type User struct { - Uid int `gvalid:"uid @integer|min:1#用户UID不能为空"` - Name string `gvalid:"name @required|length:6,30#请输入用户名称|用户名称长度非法"` - Pass1 string `gvalid:"password1@required|password3"` - Pass2 string `gvalid:"password2@required|password3|same:password1#||两次密码不一致,请重新输入"` -} - -func main() { - user := &User{ - Name: "john", - Pass1: "Abc123!@#", - Pass2: "123", - } - - // 使用结构体定义的校验规则和错误提示进行校验 - g.Dump(gvalid.CheckStruct(context.TODO(), user, nil).Map()) - - // 自定义校验规则和错误提示,对定义的特定校验规则和错误提示进行覆盖 - rules := map[string]string{ - "Uid": "required", - } - msgs := map[string]interface{}{ - "Pass2": map[string]string{ - "password3": "名称不能为空", - }, - } - g.Dump(gvalid.CheckStruct(context.TODO(), user, rules, msgs).Map()) -} diff --git a/.example/util/gvalid/gvalid_struct2.go b/.example/util/gvalid/gvalid_struct2.go deleted file mode 100644 index 8c0511899..000000000 --- a/.example/util/gvalid/gvalid_struct2.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gvalid" -) - -// string默认值校验 -func main() { - type User struct { - Uid string `gvalid:"uid@integer"` - } - - user := &User{} - - g.Dump(gvalid.CheckStruct(context.TODO(), user, nil)) -} diff --git a/.example/util/gvalid/gvalid_struct3.go b/.example/util/gvalid/gvalid_struct3.go deleted file mode 100644 index 7262a6b08..000000000 --- a/.example/util/gvalid/gvalid_struct3.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gvalid" -) - -// same校验 -func main() { - type User struct { - Pass string `gvalid:"passwd1 @required|length:2,20|password3||密码强度不足"` - } - - user := &User{ - Pass: "1", - } - - g.Dump(gvalid.CheckStruct(context.TODO(), user, nil).Maps()) -} diff --git a/.example/util/gvalid/gvalid_struct_meta.go b/.example/util/gvalid/gvalid_struct_meta.go deleted file mode 100644 index e7d251fe5..000000000 --- a/.example/util/gvalid/gvalid_struct_meta.go +++ /dev/null @@ -1,40 +0,0 @@ -package main - -import ( - "context" - "fmt" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gmeta" -) - -type UserCreateReq struct { - gmeta.Meta `v:"UserCreateReq"` - Name string - Pass string -} - -func UserCreateReqChecker(ctx context.Context, rule string, value interface{}, message string, data interface{}) error { - user := &UserCreateReq{} - if v, ok := data.(*UserCreateReq); ok { - user = v - } - // SELECT COUNT(*) FROM `user` WHERE `name` = xxx - count, err := g.Model("user").Ctx(ctx).Where("name", user.Name).Count() - if err != nil { - return err - } - if count > 0 { - return gerror.Newf(`The name "%s" is already token`, user.Name) - } - return nil -} - -func main() { - user := &UserCreateReq{ - Name: "john", - Pass: "123456", - } - err := g.Validator().RuleFunc("UserCreateReq", UserCreateReqChecker).CheckStruct(user) - fmt.Println(err) -} diff --git a/.example/util/gvalid/i18n/en.toml b/.example/util/gvalid/i18n/en.toml deleted file mode 100644 index 7574fd595..000000000 --- a/.example/util/gvalid/i18n/en.toml +++ /dev/null @@ -1,7 +0,0 @@ -"gf.gvalid.required" = "字段不能为空" - - -"ReuiredUserName" = "Please input user name" -"ReuiredUserType" = "Please select user type" -"MustSize" = "Size of :attribute must be :size" - diff --git a/.example/util/gvalid/i18n/zh-CN.toml b/.example/util/gvalid/i18n/zh-CN.toml deleted file mode 100644 index 3db393e20..000000000 --- a/.example/util/gvalid/i18n/zh-CN.toml +++ /dev/null @@ -1,16 +0,0 @@ - - -"gf.gvalid.required" = "字段不能为空" - -"ReuiredUserName" = "请输入用户名称" -"ReuiredUserType" = "请选择用户类型" -"MustSize" = ":attribute长度必须为:size" - - - - - - - - - diff --git a/.gitignore b/.gitignore index fdb500de8..5af57e523 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,6 @@ bin/ cbuild **/.DS_Store .vscode/ -.example/other/ +.test/ main gf \ No newline at end of file diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 000000000..c5481fc95 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,949 @@ +# This file contains all available configuration options +# with their default values. + +# options for analysis running +run: + # default concurrency is a available CPU number + concurrency: 4 + + # timeout for analysis, e.g. 30s, 5m, default is 1m + timeout: 5m + + # exit code when at least one issue was found, default is 1 + issues-exit-code: 1 + + # include test files or not, default is true + tests: false + + # list of build tags, all linters use it. Default is empty list. + build-tags: +# - mytag + + # which dirs to skip: issues from them won't be reported; + # can use regexp here: generated.*, regexp is applied on full path; + # default value is empty list, but default dirs are skipped independently + # from this option's value (see skip-dirs-use-default). + # "/" will be replaced by current OS file path separator to properly work + # on Windows. + skip-dirs: + - .example + - .test + + # default is true. Enables skipping of directories: + # vendor$, third_party$, testdata$, examples$, Godeps$, builtin$ + skip-dirs-use-default: true + + # which files to skip: they will be analyzed, but issues from them + # won't be reported. Default value is empty list, but there is + # no need to include all autogenerated files, we confidently recognize + # autogenerated files. If it's not please let us know. + # "/" will be replaced by current OS file path separator to properly work + # on Windows. + skip-files: + - ".*_test\\.go$" + - ".*_packed\\.go$" + + # by default isn't set. If set we pass it to "go list -mod={option}". From "go help modules": + # If invoked with -mod=readonly, the go command is disallowed from the implicit + # automatic updating of go.mod described above. Instead, it fails when any changes + # to go.mod are needed. This setting is most useful to check that go.mod does + # not need updates, such as in a continuous integration and testing system. + # If invoked with -mod=vendor, the go command assumes that the vendor + # directory holds the correct copies of dependencies and ignores + # the dependency descriptions in go.mod. + #modules-download-mode: release|readonly|vendor + + # Allow multiple parallel golangci-lint instances running. + # If false (default) - golangci-lint acquires file lock on start. + allow-parallel-runners: true + + +# output configuration options +output: + # colored-line-number|line-number|json|tab|checkstyle|code-climate|junit-xml|github-actions + # default is "colored-line-number" + format: colored-line-number + + # print lines of code with issue, default is true + print-issued-lines: true + + # print linter name in the end of issue text, default is true + print-linter-name: true + + # make issues output unique by line, default is true + uniq-by-line: true + + # add a prefix to the output file references; default is no prefix + path-prefix: "" + + # sorts results by: filepath, line and column + sort-results: true + + +# all available settings of specific linters +linters-settings: + bidichk: + # The following configurations check for all mentioned invisible unicode + # runes. It can be omitted because all runes are enabled by default. + left-to-right-embedding: true + right-to-left-embedding: true + pop-directional-formatting: true + left-to-right-override: true + right-to-left-override: true + left-to-right-isolate: true + right-to-left-isolate: true + first-strong-isolate: true + pop-directional-isolate: true + + cyclop: + # the maximal code complexity to report + max-complexity: 50 + # the maximal average package complexity. If it's higher than 0.0 (float) the check is enabled (default 0.0) + package-average: 0.0 + # should ignore tests (default false) + skip-tests: false + + dogsled: + # checks assignments with too many blank identifiers; default is 2 + max-blank-identifiers: 2 + + dupl: + # tokens count to trigger issue, 150 by default + threshold: 100 + + errcheck: + # report about not checking of errors in type assertions: `a := b.(MyStruct)`; + # default is false: such cases aren't reported by default. + check-type-assertions: false + + # report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`; + # default is false: such cases aren't reported by default. + check-blank: false + + # [deprecated] comma-separated list of pairs of the form pkg:regex + # the regex is used to ignore names within pkg. (default "fmt:.*"). + # see https://github.com/kisielk/errcheck#the-deprecated-method for details + #ignore: fmt:.*,io/ioutil:^Read.* + + # [deprecated] use exclude-functions instead. + # path to a file containing a list of functions to exclude from checking + # see https://github.com/kisielk/errcheck#excluding-functions for details + # exclude: /path/to/file.txt + + # list of functions to exclude from checking, where each entry is a single function to exclude. + # see https://github.com/kisielk/errcheck#excluding-functions for details + exclude-functions: +# - io/ioutil.ReadFile +# - io.Copy(*bytes.Buffer) +# - io.Copy(os.Stdout) + + errorlint: + # Check whether fmt.Errorf uses the %w verb for formatting errors. See the readme for caveats + errorf: true + # Check for plain type assertions and type switches + asserts: true + # Check for plain error comparisons + comparison: true + + exhaustive: + # check switch statements in generated files also + check-generated: false + # presence of "default" case in switch statements satisfies exhaustiveness, + # even if all enum members are not listed + default-signifies-exhaustive: false + # enum members matching the supplied regex do not have to be listed in + # switch statements to satisfy exhaustiveness + ignore-enum-members: "" + # consider enums only in package scopes, not in inner scopes + package-scope-only: false + + exhaustivestruct: + # Struct Patterns is list of expressions to match struct packages and names + # The struct packages have the form example.com/package.ExampleStruct + # The matching patterns can use matching syntax from https://pkg.go.dev/path#Match + # If this list is empty, all structs are tested. + struct-patterns: +# - '*.Test' +# - 'example.com/package.ExampleStruct' +# - '*.Test2' +# - '*.Embedded' +# - '*.External' + + forbidigo: + # Forbid the following identifiers (identifiers are written using regexp): + forbid: +# - ^print.*$ +# - 'fmt\.Print.*' +# - fmt.Println.* # too much log noise +# - ginkgo\\.F.* # these are used just for local development + # Exclude godoc examples from forbidigo checks. Default is true. + exclude_godoc_examples: false + + funlen: + lines: 150 + statements: 50 + + gci: + # put imports beginning with prefix after 3rd-party packages; + # only support one prefix + # if not set, use goimports.local-prefixes + local-prefixes: github.com/gogf/gf + + gocognit: + # minimal code complexity to report, 30 by default (but we recommend 10-20) + min-complexity: 50 + + goconst: + # minimal length of string constant, 3 by default + min-len: 3 + # minimum occurrences of constant string count to trigger issue, 3 by default + min-occurrences: 3 + # ignore test files, false by default + ignore-tests: true + # look for existing constants matching the values, true by default + match-constant: true + # search also for duplicated numbers, false by default + numbers: false + # minimum value, only works with goconst.numbers, 3 by default + min: 3 + # maximum value, only works with goconst.numbers, 3 by default + max: 3 + # ignore when constant is not used as function argument, true by default + ignore-calls: true + + gocritic: + # Which checks should be enabled; can't be combined with 'disabled-checks'; + # See https://go-critic.github.io/overview#checks-overview + # To check which checks are enabled run `GL_DEBUG=gocritic golangci-lint run` + # By default list of stable checks is used. + enabled-checks: + - nestingReduce + - unnamedresult + - ruleguard + - truncateCmp + + # Which checks should be disabled; can't be combined with 'enabled-checks'; default is empty + disabled-checks: + - regexpMust + - ifElseChain + - exitAfterDefer + + # Enable multiple checks by tags, run `GL_DEBUG=gocritic golangci-lint run` to see all tags and checks. + # Empty list by default. See https://github.com/go-critic/go-critic#usage -> section "Tags". + enabled-tags: + - performance + disabled-tags: + - experimental + + # Settings passed to gocritic. + # The settings key is the name of a supported gocritic checker. + # The list of supported checkers can be find in https://go-critic.github.io/overview. + settings: + captLocal: # must be valid enabled check name + # whether to restrict checker to params only (default true) + paramsOnly: true + elseif: + # whether to skip balanced if-else pairs (default true) + skipBalanced: true + hugeParam: + # size in bytes that makes the warning trigger (default 80) + sizeThreshold: 80 + nestingReduce: + # min number of statements inside a branch to trigger a warning (default 5) + bodyWidth: 5 + rangeExprCopy: + # size in bytes that makes the warning trigger (default 512) + sizeThreshold: 512 + # whether to check test functions (default true) + skipTestFuncs: true + rangeValCopy: + # size in bytes that makes the warning trigger (default 128) + sizeThreshold: 32 + # whether to check test functions (default true) + skipTestFuncs: true + ruleguard: + # Enable debug to identify which 'Where' condition was rejected. + # The value of the parameter is the name of a function in a ruleguard file. + # + # When a rule is evaluated: + # If: + # The Match() clause is accepted; and + # One of the conditions in the Where() clause is rejected, + # Then: + # ruleguard prints the specific Where() condition that was rejected. + # + # The flag is passed to the ruleguard 'debug-group' argument. + debug: 'emptyDecl' + # Deprecated, use 'failOn' param. + # If set to true, identical to failOn='all', otherwise failOn='' + failOnError: false + # Determines the behavior when an error occurs while parsing ruleguard files. + # If flag is not set, log error and skip rule files that contain an error. + # If flag is set, the value must be a comma-separated list of error conditions. + # - 'all': fail on all errors. + # - 'import': ruleguard rule imports a package that cannot be found. + # - 'dsl': gorule file does not comply with the ruleguard DSL. + failOn: dsl + # Comma-separated list of file paths containing ruleguard rules. + # If a path is relative, it is relative to the directory where the golangci-lint command is executed. + # The special '${configDir}' variable is substituted with the absolute directory containing the golangci config file. + # Glob patterns such as 'rules-*.go' may be specified. + rules: '' #${configDir}/ruleguard/rules-*.go,${configDir}/myrule1.go' + #tooManyResultsChecker: + # maximum number of results (default 5) + #maxResults: 10 + truncateCmp: + # whether to skip int/uint/uintptr types (default true) + skipArchDependent: true + underef: + # whether to skip (*x).method() calls where x is a pointer receiver (default true) + skipRecvDeref: true + unnamedResult: + # whether to check exported functions + checkExported: true + + gocyclo: + # minimal code complexity to report, 30 by default (but we recommend 10-20) + min-complexity: 30 + + godot: + # comments to be checked: `declarations`, `toplevel`, or `all` + scope: declarations + # list of regexps for excluding particular comment lines from check + exclude: + # example: exclude comments which contain numbers + # - '[0-9]+' + # check that each sentence starts with a capital letter + capital: false + + godox: + # report any comments starting with keywords, this is useful for TODO or FIXME comments that + # might be left in the code accidentally and should be resolved before merging + keywords: # default keywords are TODO, BUG, and FIXME, these can be overwritten by this setting + #- NOTE + - BUG + - FIXME + - OPTIMIZE # marks code that should be optimized before merging + - HACK # marks hack-arounds that should be removed before merging + + gofmt: + # simplify code: gofmt with `-s` option, true by default + simplify: true + + gofumpt: + # Select the Go version to target. The default is `1.15`. + lang-version: "1.16" + + # Choose whether or not to use the extra rules that are disabled + # by default + extra-rules: false + + goheader: + values: + const: + # define here const type values in format k:v, for example: + # COMPANY: MY COMPANY + regexp: + # define here regexp type values, for example + # AUTHOR: .*@mycompany\.com + template: # |- + # put here copyright header template for source code files, for example: + # Note: {{ YEAR }} is a builtin value that returns the year relative to the current machine time. + # + # {{ AUTHOR }} {{ COMPANY }} {{ YEAR }} + # SPDX-License-Identifier: Apache-2.0 + + # Licensed under the Apache License, Version 2.0 (the "License"); + # you may not use this file except in compliance with the License. + # You may obtain a copy of the License at: + + # http://www.apache.org/licenses/LICENSE-2.0 + + # Unless required by applicable law or agreed to in writing, software + # distributed under the License is distributed on an "AS IS" BASIS, + # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + # See the License for the specific language governing permissions and + # limitations under the License. + template-path: + # also as alternative of directive 'template' you may put the path to file with the template source + + goimports: + # put imports beginning with prefix after 3rd-party packages; + # it's a comma-separated list of prefixes + local-prefixes: github.com/gogf/gf + + golint: + # minimal confidence for issues, default is 0.8 + min-confidence: 0.9 + + gomnd: + settings: + mnd: + # the list of enabled checks, see https://github.com/tommy-muehle/go-mnd/#checks for description. + checks: argument,case,condition,operation,return,assign + # ignored-numbers: 1000 + # ignored-files: magic_.*.go + # ignored-functions: math.* + + gomoddirectives: + # Allow local `replace` directives. Default is false. + replace-local: false + # List of allowed `replace` directives. Default is empty. + replace-allow-list: + - launchpad.net/gocheck + - github.com/coreos/etcd + - google.golang.org/grpc + - gitlab.jntmedia.cn/lanren/core + # Allow to not explain why the version has been retracted in the `retract` directives. Default is false. + retract-allow-no-explanation: false + # Forbid the use of the `exclude` directives. Default is false. + exclude-forbidden: false + + gomodguard: + allowed: + modules: # List of allowed modules + # - gopkg.in/yaml.v2 + - gorm.io/gorm + - gorm.io/driver/mysql + - k8s.io/klog + domains: # List of allowed module domains + # - golang.org + - google.golang.org + - gopkg.in + - golang.org + - github.com + - go.uber.org + blocked: + modules: # List of blocked modules + # - github.com/uudashr/go-module: # Blocked module + # recommendations: # Recommended modules that should be used instead (Optional) + # - golang.org/x/mod + # reason: "`mod` is the official go.mod parser library." # Reason why the recommended module should be used (Optional) + versions: # List of blocked module version constraints + # - github.com/mitchellh/go-homedir: # Blocked module with version constraint + # version: "< 1.1.0" # Version constraint, see https://github.com/Masterminds/semver#basic-comparisons + # reason: "testing if blocked version constraint works." # Reason why the version constraint exists. (Optional) + local_replace_directives: false # Set to true to raise lint issues for packages that are loaded from a local path via replace directive + + gosec: + # To select a subset of rules to run. + # Available rules: https://github.com/securego/gosec#available-rules + includes: + - G401 + - G306 + - G101 + # To specify a set of rules to explicitly exclude. + # Available rules: https://github.com/securego/gosec#available-rules + excludes: + - G204 + # Exclude generated files + exclude-generated: true + # Filter out the issues with a lower severity than the given value. Valid options are: low, medium, high. + severity: "low" + # Filter out the issues with a lower confidence than the given value. Valid options are: low, medium, high. + confidence: "low" + # To specify the configuration of rules. + # The configuration of rules is not fully documented by gosec: + # https://github.com/securego/gosec#configuration + # https://github.com/securego/gosec/blob/569328eade2ccbad4ce2d0f21ee158ab5356a5cf/rules/rulelist.go#L60-L102 + config: + G306: "0600" + G101: + pattern: "(?i)example" + ignore_entropy: false + entropy_threshold: "80.0" + per_char_threshold: "3.0" + truncate: "32" + + gosimple: + # Select the Go version to target. The default is '1.13'. + go: "1.16" + # https://staticcheck.io/docs/options#checks + checks: [ "all" ] + + govet: + # report about shadowed variables + check-shadowing: true + + # settings per analyzer + settings: + printf: # analyzer name, run `go tool vet help` to see all analyzers + funcs: # run `go tool vet help printf` to see available settings for `printf` analyzer + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf + + # enable or disable analyzers by name + # run `go tool vet help` to see all analyzers + enable: + - atomicalign + enable-all: false + disable: + - shadow + disable-all: false + + depguard: + list-type: blacklist + include-go-root: false + packages: + - github.com/sirupsen/logrus + packages-with-error-message: + # specify an error message to output when a blacklisted package is used + - github.com/sirupsen/logrus: "logging is allowed only by logutils.Log" + + ifshort: + # Maximum length of variable declaration measured in number of lines, after which linter won't suggest using short syntax. + # Has higher priority than max-decl-chars. + max-decl-lines: 1 + # Maximum length of variable declaration measured in number of characters, after which linter won't suggest using short syntax. + max-decl-chars: 30 + + importas: + # if set to `true`, force to use alias. + no-unaliased: true + # List of aliases + alias: + # using `servingv1` alias for `knative.dev/serving/pkg/apis/serving/v1` package + - pkg: knative.dev/serving/pkg/apis/serving/v1 + alias: servingv1 + # using `autoscalingv1alpha1` alias for `knative.dev/serving/pkg/apis/autoscaling/v1alpha1` package + - pkg: knative.dev/serving/pkg/apis/autoscaling/v1alpha1 + alias: autoscalingv1alpha1 + # You can specify the package path by regular expression, + # and alias by regular expression expansion syntax like below. + # see https://github.com/julz/importas#use-regular-expression for details + - pkg: knative.dev/serving/pkg/apis/(\w+)/(v[\w\d]+) + alias: $1$2 + + ireturn: + # ireturn allows using `allow` and `reject` settings at the same time. + # Both settings are lists of the keywords and regular expressions matched to interface or package names. + # keywords: + # - `empty` for `interface{}` + # - `error` for errors + # - `stdlib` for standard library + # - `anon` for anonymous interfaces + + # By default, it allows using errors, empty interfaces, anonymous interfaces, + # and interfaces provided by the standard library. + allow: + - anon + - error + - empty + - stdlib + # You can specify idiomatic endings for interface + - (or|er)$ + + # Reject patterns +# reject: +# - github.com\/user\/package\/v4\.Type + + lll: + # max line length, lines longer will be reported. Default is 120. + # '\t' is counted as 1 character by default, and can be changed with the tab-width option + line-length: 240 + # tab width in spaces. Default to 1. + tab-width: 4 + + makezero: + # Allow only slices initialized with a length of zero. Default is false. + always: false + + maligned: + # print struct with more effective memory layout or not, false by default + suggest-new: true + + misspell: + # Correct spellings using locale preferences for US or UK. + # Default is to use a neutral variety of English. + # Setting locale to US will correct the British spelling of 'colour' to 'color'. + locale: US + ignore-words: + - someword + + nakedret: + # make an issue if func has more lines of code than this setting and it has naked returns; default is 30 + max-func-lines: 30 + + nestif: + # minimal complexity of if statements to report, 5 by default + min-complexity: 4 + + nilnil: + # By default, nilnil checks all returned types below. + checked-types: + - ptr + - func + - iface + - map + - chan + + nlreturn: + # size of the block (including return statement that is still "OK") + # so no return split required. + block-size: 1 + + nolintlint: + # Disable to ensure that all nolint directives actually have an effect. Default is true. + allow-unused: true + # Disable to ensure that nolint directives don't have a leading space. Default is true. + allow-leading-space: true + # Exclude following linters from requiring an explanation. Default is []. + allow-no-explanation: [ ] + # Enable to require an explanation of nonzero length after each nolint directive. Default is false. + require-explanation: false + # Enable to require nolint directives to mention the specific linter being suppressed. Default is false. + require-specific: true + + prealloc: + # XXX: we don't recommend using this linter before doing performance profiling. + # For most programs usage of prealloc will be a premature optimization. + + # Report preallocation suggestions only on simple loops that have no returns/breaks/continues/gotos in them. + # True by default. + simple: true + range-loops: true # Report preallocation suggestions on range loops, true by default + for-loops: false # Report preallocation suggestions on for loops, false by default + + promlinter: + # Promlinter cannot infer all metrics name in static analysis. + # Enable strict mode will also include the errors caused by failing to parse the args. + strict: false + # Please refer to https://github.com/yeya24/promlinter#usage for detailed usage. + disabled-linters: + # - "Help" + # - "MetricUnits" + # - "Counter" + # - "HistogramSummaryReserved" + # - "MetricTypeInName" + # - "ReservedChars" + # - "CamelCase" + # - "lintUnitAbbreviations" + + predeclared: + # comma-separated list of predeclared identifiers to not report on + ignore: "" + # include method names and field names (i.e., qualified names) in checks + q: false + + rowserrcheck: + packages: + - github.com/jmoiron/sqlx + + revive: + # see https://github.com/mgechev/revive#available-rules for details. + ignore-generated-header: true + severity: warning + rules: + - name: indent-error-flow + severity: warning + - name: add-constant + severity: warning + arguments: + - maxLitCount: "3" + allowStrs: '""' + allowInts: "0,1,2" + allowFloats: "0.0,0.,1.0,1.,2.0,2." + + staticcheck: + # Select the Go version to target. The default is '1.13'. + go: "1.16" + # https://staticcheck.io/docs/options#checks + checks: [ "all" ] + + stylecheck: + # Select the Go version to target. The default is '1.13'. + go: "1.16" + # https://staticcheck.io/docs/options#checks + checks: [ "all", "-ST1000", "-ST1003", "-ST1016", "-ST1020", "-ST1021", "-ST1022" ] + # https://staticcheck.io/docs/options#dot_import_whitelist + dot-import-whitelist: + - fmt + # https://staticcheck.io/docs/options#initialisms + initialisms: [ "ACL", "API", "ASCII", "CPU", "CSS", "DNS", "EOF", "GUID", "HTML", "HTTP", "HTTPS", "ID", "IP", "JSON", "QPS", "RAM", "RPC", "SLA", "SMTP", "SQL", "SSH", "TCP", "TLS", "TTL", "UDP", "UI", "GID", "UID", "UUID", "URI", "URL", "UTF8", "VM", "XML", "XMPP", "XSRF", "XSS" ] + # https://staticcheck.io/docs/options#http_status_code_whitelist + http-status-code-whitelist: [ "200", "400", "404", "500" ] + + tagliatelle: + # check the struck tag name case + case: + # use the struct field name to check the name of the struct tag + use-field-name: true + rules: + # any struct tag type can be used. + # support string case: `camel`, `pascal`, `kebab`, `snake`, `goCamel`, `goPascal`, `goKebab`, `goSnake`, `upper`, `lower` + json: camel + yaml: camel + xml: camel + bson: camel + avro: snake + mapstructure: kebab + + testpackage: + # regexp pattern to skip files + skip-regexp: (export|internal)_test\.go + + thelper: + # The following configurations enable all checks. It can be omitted because all checks are enabled by default. + # You can enable only required checks deleting unnecessary checks. + test: + first: true + name: true + begin: true + benchmark: + first: true + name: true + begin: true + tb: + first: true + name: true + begin: true + + tenv: + # The option `all` will run against whole test files (`_test.go`) regardless of method/function signatures. + # By default, only methods that take `*testing.T`, `*testing.B`, and `testing.TB` as arguments are checked. + all: false + + unparam: + # Inspect exported functions, default is false. Set to true if no external program/library imports your code. + # XXX: if you enable this setting, unparam will report a lot of false-positives in text editors: + # if it's called for subdir of a project it can't find external interfaces. All text editor integrations + # with golangci-lint call it on a directory with the changed file. + check-exported: false + + unused: + # Select the Go version to target. The default is '1.13'. + go: "1.16" + + varnamelen: + # The longest distance, in source lines, that is being considered a "small scope." (defaults to 5) + # Variables used in at most this many lines will be ignored. + max-distance: 5 + # The minimum length of a variable's name that is considered "long." (defaults to 3) + # Variable names that are at least this long will be ignored. + min-name-length: 1 + # Check method receiver names. (defaults to false) + check-receiver: false + # Check named return values. (defaults to false) + check-return: false + # Ignore "ok" variables that hold the bool return value of a type assertion. (defaults to false) + ignore-type-assert-ok: false + # Ignore "ok" variables that hold the bool return value of a map index. (defaults to false) + ignore-map-index-ok: false + # Ignore "ok" variables that hold the bool return value of a channel receive. (defaults to false) + ignore-chan-recv-ok: false + # Optional list of variable names that should be ignored completely. (defaults to empty list) + ignore-names: + - err + # Optional list of variable declarations that should be ignored completely. (defaults to empty list) + # Entries must be in the form of " " or " *". + ignore-decls: + - c echo.Context + - t testing.T + - f *foo.Bar + - e error + - i int + + whitespace: + multi-if: false # Enforces newlines (or comments) after every multi-line if statement + multi-func: false # Enforces newlines (or comments) after every multi-line function signature + + wrapcheck: + # An array of strings that specify substrings of signatures to ignore. + # If this set, it will override the default set of ignored signatures. + # See https://github.com/tomarrell/wrapcheck#configuration for more information. + ignoreSigs: + - .Errorf( + - errors.New( + - errors.Unwrap( + - .Wrap( + - .Wrapf( + - .WithMessage( + - .WithMessagef( + - .WithStack( + ignorePackageGlobs: + - encoding/* + - github.com/pkg/* + + wsl: + # See https://github.com/bombsimon/wsl/blob/master/doc/configuration.md for + # documentation of available settings. These are the defaults for + # `golangci-lint`. + allow-assign-and-anything: false + allow-assign-and-call: true + allow-cuddle-declarations: false + allow-multiline-assign: true + allow-separated-leading-comment: false + allow-trailing-comment: false + force-case-trailing-whitespace: 0 + force-err-cuddling: false + force-short-decl-cuddling: false + strict-append: true + + # The custom section can be used to define linter plugins to be loaded at runtime. + # See README doc for more info. + # custom: + # Each custom linter should have a unique name. + # example: + # The path to the plugin *.so. Can be absolute or local. Required for each custom linter + # path: /path/to/example.so + # The description of the linter. Optional, just for documentation purposes. + # description: This is an example usage of a plugin linter. + # Intended to point to the repo location of the linter. Optional, just for documentation purposes. + # original-url: github.com/golangci/example-linter + +linters: + #disable-all: true + #enable: + # - megacheck + # - govet + enable-all: true + disable: + - maligned + - prealloc + #- tagliatelle + #- wrapcheck + #- forcetypeassert + - goerr113 + - gomnd + - wsl + - testpackage + - gochecknoglobals + - interfacer + - maligned + - scopelint + - gocritic + - typecheck +# presets: +# - bugs +# - unused + fast: false + + +issues: + # List of regexps of issue texts to exclude, empty list by default. + # But independently from this option we use default exclude patterns, + # it can be disabled by `exclude-use-default: false`. To list all + # excluded by default patterns execute `golangci-lint run --help` + exclude: + - abcdef + - tools/.* + - test/.* + - third_party/.* + + # Excluding configuration per-path, per-linter, per-text and per-source + exclude-rules: + # Exclude some linters from running on tests files. + - linters: + - revive + path: (log/.*)\.go + - linters: + - wrapcheck + path: (cmd/.*|pkg/.*)\.go + - linters: + - typecheck + path: (pkg/storage/.*)\.go + + - path: (cmd/.*|test/.*|tools/.*)\.go + linters: + - forbidigo + - path: (cmd/[a-z]*/.*|store/.*)\.go + linters: + - dupl + - linters: + - gocritic + text: (hugeParam:|rangeValCopy:) + + - path: (cmd/[a-z]*/.*)\.go + linters: + - lll + + - path: (validator/.*|code/.*|validator/.*) + linters: + - gochecknoinits + - path: (pkg/app/.*)\.go + linters: + - gocyclo + - errcheck + - dupl + - gosec + + # Exclude known linters from partially hard-vendored code, + # which is impossible to exclude via "nolint" comments. + - path: internal/hmac/ + text: "weak cryptographic primitive" + linters: + - gosec + + # Exclude some staticcheck messages + - linters: + - staticcheck + text: "SA9003:" + + # Exclude lll issues for long lines with go:generate + - linters: + - lll + source: "^//go:generate " + + # Independently from option `exclude` we use default exclude patterns, + # it can be disabled by this option. To list all + # excluded by default patterns execute `golangci-lint run --help`. + # Default value for this option is true. + exclude-use-default: false + + # The default value is false. If set to true exclude and exclude-rules + # regular expressions become case sensitive. + exclude-case-sensitive: false + + # The list of ids of default excludes to include or disable. By default it's empty. + include: + - EXC0002 # disable excluding of issues about comments from golint + + # Maximum issues count per one linter. Set to 0 to disable. Default is 50. + max-issues-per-linter: 0 + + # Maximum count of issues with the same text. Set to 0 to disable. Default is 3. + max-same-issues: 0 + + # Show only new issues: if there are unstaged changes or untracked files, + # only those changes are analyzed, else only changes in HEAD~ are analyzed. + # It's a super-useful option for integration of golangci-lint into existing + # large codebase. It's not practical to fix all existing issues at the moment + # of integration: much better don't allow issues in new code. + # Default is false. + new: false + + # Show only new issues created after git revision `REV` + new-from-rev: REV + + # Show only new issues created in git patch with set file path. + # new-from-patch: path/to/patch/file + + # Fix found issues (if it's supported by the linter) + fix: true + +severity: + # Default value is empty string. + # Set the default severity for issues. If severity rules are defined and the issues + # do not match or no severity is provided to the rule this will be the default + # severity applied. Severities should match the supported severity names of the + # selected out format. + # - Code climate: https://docs.codeclimate.com/docs/issues#issue-severity + # - Checkstyle: https://checkstyle.sourceforge.io/property_types.html#severity + # - GitHub: https://help.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-error-message + default-severity: error + + # The default value is false. + # If set to true severity-rules regular expressions become case sensitive. + case-sensitive: false + + # Default value is empty list. + # When a list of severity rules are provided, severity information will be added to lint + # issues. Severity rules have the same filtering capability as exclude rules except you + # are allowed to specify one matcher per severity rule. + # Only affects out formats that support setting severity information. + rules: + - linters: + - dupl + severity: info diff --git a/container/garray/garray_func.go b/container/garray/garray_func.go index 364654084..155cca0d8 100644 --- a/container/garray/garray_func.go +++ b/container/garray/garray_func.go @@ -8,11 +8,6 @@ package garray import "strings" -// iInterfaces is used for type assert api for Interfaces. -type iInterfaces interface { - Interfaces() []interface{} -} - // defaultComparatorInt for int comparison. func defaultComparatorInt(a, b int) int { if a < b { diff --git a/container/garray/garray_normal_any.go b/container/garray/garray_normal_any.go index e43b77d0b..fe43a82ab 100644 --- a/container/garray/garray_normal_any.go +++ b/container/garray/garray_normal_any.go @@ -9,15 +9,15 @@ package garray import ( "bytes" "fmt" + "math" + "sort" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/empty" "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/text/gstr" - "math" - "sort" - "github.com/gogf/gf/v2/internal/rwmutex" + "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/grand" ) diff --git a/container/garray/garray_normal_int.go b/container/garray/garray_normal_int.go index 0d4ccaec8..5dacdc95b 100644 --- a/container/garray/garray_normal_int.go +++ b/container/garray/garray_normal_int.go @@ -9,12 +9,12 @@ package garray import ( "bytes" "fmt" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/internal/json" "math" "sort" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/rwmutex" "github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/grand" diff --git a/container/garray/garray_normal_str.go b/container/garray/garray_normal_str.go index 715a74ae8..0e178e156 100644 --- a/container/garray/garray_normal_str.go +++ b/container/garray/garray_normal_str.go @@ -8,15 +8,15 @@ package garray import ( "bytes" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/text/gstr" "math" "sort" "strings" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/rwmutex" + "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/grand" ) @@ -407,9 +407,8 @@ func (a *StrArray) SubSlice(offset int, length ...int) []string { s := make([]string, size) copy(s, a.array[offset:]) return s - } else { - return a.array[offset:end] } + return a.array[offset:end] } // Append is alias of PushRight,please See PushRight. diff --git a/container/garray/garray_sorted_any.go b/container/garray/garray_sorted_any.go index a9db1108e..1b702dec0 100644 --- a/container/garray/garray_sorted_any.go +++ b/container/garray/garray_sorted_any.go @@ -9,16 +9,16 @@ package garray import ( "bytes" "fmt" - "github.com/gogf/gf/v2/internal/empty" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/text/gstr" - "github.com/gogf/gf/v2/util/gutil" "math" "sort" + "github.com/gogf/gf/v2/internal/empty" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/rwmutex" + "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/grand" + "github.com/gogf/gf/v2/util/gutil" ) // SortedArray is a golang sorted array with rich features. diff --git a/container/garray/garray_sorted_int.go b/container/garray/garray_sorted_int.go index 0b01eb7cd..fd2730438 100644 --- a/container/garray/garray_sorted_int.go +++ b/container/garray/garray_sorted_int.go @@ -9,10 +9,10 @@ package garray import ( "bytes" "fmt" - "github.com/gogf/gf/v2/internal/json" "math" "sort" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/rwmutex" "github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/grand" diff --git a/container/garray/garray_sorted_str.go b/container/garray/garray_sorted_str.go index 3c7e03449..768fec23a 100644 --- a/container/garray/garray_sorted_str.go +++ b/container/garray/garray_sorted_str.go @@ -8,13 +8,13 @@ package garray import ( "bytes" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/text/gstr" "math" "sort" "strings" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/rwmutex" + "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/grand" ) diff --git a/container/garray/garray_z_bench_any_test.go b/container/garray/garray_z_bench_any_test.go index 2eca2a91d..b316e23b5 100644 --- a/container/garray/garray_z_bench_any_test.go +++ b/container/garray/garray_z_bench_any_test.go @@ -7,8 +7,9 @@ package garray_test import ( - "github.com/gogf/gf/v2/container/garray" "testing" + + "github.com/gogf/gf/v2/container/garray" ) type anySortedArrayItem struct { diff --git a/container/garray/garray_z_example_any_test.go b/container/garray/garray_z_example_normal_any_test.go similarity index 100% rename from container/garray/garray_z_example_any_test.go rename to container/garray/garray_z_example_normal_any_test.go index 701c2ac66..a7b914ef5 100644 --- a/container/garray/garray_z_example_any_test.go +++ b/container/garray/garray_z_example_normal_any_test.go @@ -8,9 +8,9 @@ package garray_test import ( "fmt" - "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/container/garray" + "github.com/gogf/gf/v2/frame/g" ) func ExampleNew() { diff --git a/container/garray/garray_z_example_normal_int_test.go b/container/garray/garray_z_example_normal_int_test.go new file mode 100644 index 000000000..6052ca601 --- /dev/null +++ b/container/garray/garray_z_example_normal_int_test.go @@ -0,0 +1,710 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +package garray_test + +import ( + "fmt" + + "github.com/gogf/gf/v2/container/garray" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" + "github.com/gogf/gf/v2/util/gconv" +) + +func ExampleIntArray_Walk() { + var array garray.IntArray + tables := g.SliceInt{10, 20} + prefix := 99 + array.Append(tables...) + // Add prefix for given table names. + array.Walk(func(value int) int { + return prefix + value + }) + fmt.Println(array.Slice()) + + // Output: + // [109 119] +} + +func ExampleNewIntArray() { + s := garray.NewIntArray() + s.Append(10) + s.Append(20) + s.Append(15) + s.Append(30) + fmt.Println(s.Slice()) + + // Output: + // [10 20 15 30] +} + +func ExampleNewIntArraySize() { + s := garray.NewIntArraySize(3, 5) + s.Set(0, 10) + s.Set(1, 20) + s.Set(2, 15) + s.Set(3, 30) + fmt.Println(s.Slice(), s.Len(), cap(s.Slice())) + + // Output: + // [10 20 15] 3 5 +} + +func ExampleNewIntArrayFrom() { + s := garray.NewIntArrayFrom(g.SliceInt{10, 20, 15, 30}) + fmt.Println(s.Slice(), s.Len(), cap(s.Slice())) + + // Output: + // [10 20 15 30] 4 4 +} + +func ExampleNewIntArrayFromCopy() { + s := garray.NewIntArrayFromCopy(g.SliceInt{10, 20, 15, 30}) + fmt.Println(s.Slice(), s.Len(), cap(s.Slice())) + + // Output: + // [10 20 15 30] 4 4 +} + +func ExampleIntArray_At() { + s := garray.NewIntArrayFrom(g.SliceInt{10, 20, 15, 30}) + sAt := s.At(2) + fmt.Println(sAt) + + // Output: + // 15 +} + +func ExampleIntArray_Get() { + s := garray.NewIntArrayFrom(g.SliceInt{10, 20, 15, 30}) + sGet, sBool := s.Get(3) + fmt.Println(sGet, sBool) + + // Output: + // 30 true +} + +func ExampleIntArray_Set() { + s := garray.NewIntArraySize(3, 5) + s.Set(0, 10) + s.Set(1, 20) + s.Set(2, 15) + s.Set(3, 30) + fmt.Println(s.Slice()) + + // Output: + // [10 20 15] +} + +func ExampleIntArray_SetArray() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30}) + fmt.Println(s.Slice()) + + // Output: + // [10 20 15 30] +} + +func ExampleIntArray_Replace() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30}) + fmt.Println(s.Slice()) + s.Replace(g.SliceInt{12, 13}) + fmt.Println(s.Slice()) + + // Output: + // [10 20 15 30] + // [12 13 15 30] +} + +func ExampleIntArray_Sum() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30}) + a := s.Sum() + fmt.Println(a) + + // Output: + // 75 +} + +func ExampleIntArray_Sort() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30}) + a := s.Sort() + fmt.Println(a) + + // Output: + // [10,15,20,30] +} + +func ExampleIntArray_SortFunc() { + s := garray.NewIntArrayFrom(g.SliceInt{10, 20, 15, 30}) + fmt.Println(s) + s.SortFunc(func(v1, v2 int) bool { + // fmt.Println(v1,v2) + return v1 > v2 + }) + fmt.Println(s) + s.SortFunc(func(v1, v2 int) bool { + return v1 < v2 + }) + fmt.Println(s) + + // Output: + // [10,20,15,30] + // [30,20,15,10] + // [10,15,20,30] +} + +func ExampleIntArray_InsertBefore() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30}) + s.InsertBefore(1, 99) + fmt.Println(s.Slice()) + + // Output: + // [10 99 20 15 30] +} + +func ExampleIntArray_InsertAfter() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30}) + s.InsertAfter(1, 99) + fmt.Println(s.Slice()) + + // Output: + // [10 20 99 15 30] +} + +func ExampleIntArray_Remove() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30}) + fmt.Println(s) + s.Remove(1) + fmt.Println(s.Slice()) + + // Output: + // [10,20,15,30] + // [10 15 30] +} + +func ExampleIntArray_RemoveValue() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30}) + fmt.Println(s) + s.RemoveValue(20) + fmt.Println(s.Slice()) + + // Output: + // [10,20,15,30] + // [10 15 30] +} + +func ExampleIntArray_PushLeft() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30}) + fmt.Println(s) + s.PushLeft(96, 97, 98, 99) + fmt.Println(s.Slice()) + + // Output: + // [10,20,15,30] + // [96 97 98 99 10 20 15 30] +} + +func ExampleIntArray_PushRight() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30}) + fmt.Println(s) + s.PushRight(96, 97, 98, 99) + fmt.Println(s.Slice()) + + // Output: + // [10,20,15,30] + // [10 20 15 30 96 97 98 99] +} + +func ExampleIntArray_PopLeft() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30}) + fmt.Println(s) + s.PopLeft() + fmt.Println(s.Slice()) + + // Output: + // [10,20,15,30] + // [20 15 30] +} + +func ExampleIntArray_PopRight() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30}) + fmt.Println(s) + s.PopRight() + fmt.Println(s.Slice()) + + // Output: + // [10,20,15,30] + // [10 20 15] +} + +func ExampleIntArray_PopRand() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30, 40, 50, 60, 70}) + fmt.Println(s) + r, _ := s.PopRand() + fmt.Println(s) + fmt.Println(r) + + // May Output: + // [10,20,15,30,40,50,60,70] + // [10,20,15,30,40,60,70] + // 50 +} + +func ExampleIntArray_PopRands() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + fmt.Println(s) + r := s.PopRands(2) + fmt.Println(s) + fmt.Println(r) + + // May Output: + // [10,20,15,30,40,50,60] + // [10,20,15,30,40] + // [50 60] +} + +func ExampleIntArray_PopLefts() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + fmt.Println(s) + r := s.PopLefts(2) + fmt.Println(s) + fmt.Println(r) + + // Output: + // [10,20,15,30,40,50,60] + // [15,30,40,50,60] + // [10 20] +} + +func ExampleIntArray_PopRights() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + fmt.Println(s) + r := s.PopRights(2) + fmt.Println(s) + fmt.Println(r) + + // Output: + // [10,20,15,30,40,50,60] + // [10,20,15,30,40] + // [50 60] +} + +func ExampleIntArray_Range() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + fmt.Println(s) + r := s.Range(2, 5) + fmt.Println(r) + + // Output: + // [10,20,15,30,40,50,60] + // [15 30 40] +} + +func ExampleIntArray_SubSlice() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + fmt.Println(s) + r := s.SubSlice(3, 4) + fmt.Println(r) + + // Output: + // [10,20,15,30,40,50,60] + // [30 40 50 60] +} + +func ExampleIntArray_Append() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + fmt.Println(s) + s.Append(96, 97, 98) + fmt.Println(s) + + // Output: + // [10,20,15,30,40,50,60] + // [10,20,15,30,40,50,60,96,97,98] +} + +func ExampleIntArray_Len() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + fmt.Println(s) + fmt.Println(s.Len()) + + // Output: + // [10,20,15,30,40,50,60] + // 7 +} + +func ExampleIntArray_Slice() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + fmt.Println(s.Slice()) + + // Output: + // [10 20 15 30 40 50 60] +} + +func ExampleIntArray_Interfaces() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + r := s.Interfaces() + fmt.Println(r) + + // Output: + // [10 20 15 30 40 50 60] +} + +func ExampleIntArray_Clone() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + fmt.Println(s) + r := s.Clone() + fmt.Println(r) + + // Output: + // [10,20,15,30,40,50,60] + // [10,20,15,30,40,50,60] +} + +func ExampleIntArray_Clear() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + fmt.Println(s) + fmt.Println(s.Clear()) + fmt.Println(s) + + // Output: + // [10,20,15,30,40,50,60] + // [] + // [] +} + +func ExampleIntArray_Contains() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + fmt.Println(s.Contains(20)) + fmt.Println(s.Contains(21)) + + // Output: + // true + // false +} + +func ExampleIntArray_Search() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + fmt.Println(s.Search(20)) + fmt.Println(s.Search(21)) + + // Output: + // 1 + // -1 +} + +func ExampleIntArray_Unique() { + s := garray.NewIntArray() + s.SetArray(g.SliceInt{10, 20, 15, 15, 20, 50, 60}) + fmt.Println(s) + fmt.Println(s.Unique()) + + // Output: + // [10,20,15,15,20,50,60] + // [10,20,15,50,60] +} + +func ExampleIntArray_LockFunc() { + s := garray.NewIntArrayFrom(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + s.LockFunc(func(array []int) { + for i := 0; i < len(array)-1; i++ { + fmt.Println(array[i]) + } + }) + + // Output: + // 10 + // 20 + // 15 + // 30 + // 40 + // 50 +} + +func ExampleIntArray_RLockFunc() { + s := garray.NewIntArrayFrom(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + s.RLockFunc(func(array []int) { + for i := 0; i < len(array); i++ { + fmt.Println(array[i]) + } + }) + + // Output: + // 10 + // 20 + // 15 + // 30 + // 40 + // 50 + // 60 +} + +func ExampleIntArray_Merge() { + s1 := garray.NewIntArray() + s2 := garray.NewIntArray() + s1.SetArray(g.SliceInt{10, 20, 15}) + s2.SetArray(g.SliceInt{40, 50, 60}) + fmt.Println(s1) + fmt.Println(s2) + s1.Merge(s2) + fmt.Println(s1) + + // Output: + // [10,20,15] + // [40,50,60] + // [10,20,15,40,50,60] +} + +func ExampleIntArray_Fill() { + s := garray.NewIntArrayFrom(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + fmt.Println(s) + s.Fill(2, 3, 99) + fmt.Println(s) + + // Output: + // [10,20,15,30,40,50,60] + // [10,20,99,99,99,50,60] +} + +func ExampleIntArray_Chunk() { + s := garray.NewIntArrayFrom(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + fmt.Println(s) + r := s.Chunk(3) + fmt.Println(r) + + // Output: + // [10,20,15,30,40,50,60] + // [[10 20 15] [30 40 50] [60]] +} + +func ExampleIntArray_Pad() { + s := garray.NewIntArrayFrom(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + s.Pad(8, 99) + fmt.Println(s) + s.Pad(-10, 89) + fmt.Println(s) + + // Output: + // [10,20,15,30,40,50,60,99] + // [89,89,10,20,15,30,40,50,60,99] +} + +func ExampleIntArray_Rand() { + s := garray.NewIntArrayFrom(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + fmt.Println(s) + fmt.Println(s.Rand()) + + // May Output: + // [10,20,15,30,40,50,60] + // 10 true +} + +func ExampleIntArray_Rands() { + s := garray.NewIntArrayFrom(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + fmt.Println(s) + fmt.Println(s.Rands(3)) + + // May Output: + // [10,20,15,30,40,50,60] + // [20 50 20] +} + +func ExampleIntArray_Shuffle() { + s := garray.NewIntArrayFrom(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + fmt.Println(s) + fmt.Println(s.Shuffle()) + + // May Output: + // [10,20,15,30,40,50,60] + // [10,40,15,50,20,60,30] +} + +func ExampleIntArray_Reverse() { + s := garray.NewIntArrayFrom(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + fmt.Println(s) + fmt.Println(s.Reverse()) + + // Output: + // [10,20,15,30,40,50,60] + // [60,50,40,30,15,20,10] +} + +func ExampleIntArray_Join() { + s := garray.NewIntArrayFrom(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + fmt.Println(s) + fmt.Println(s.Join(",")) + + // Output: + // [10,20,15,30,40,50,60] + // 10,20,15,30,40,50,60 +} + +func ExampleIntArray_CountValues() { + s := garray.NewIntArrayFrom(g.SliceInt{10, 20, 15, 15, 40, 40, 40}) + fmt.Println(s.CountValues()) + + // Output: + // map[10:1 15:2 20:1 40:3] +} + +func ExampleIntArray_Iterator() { + s := garray.NewIntArrayFrom(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + s.Iterator(func(k int, v int) bool { + fmt.Println(k, v) + return true + }) + + // Output: + // 0 10 + // 1 20 + // 2 15 + // 3 30 + // 4 40 + // 5 50 + // 6 60 +} + +func ExampleIntArray_IteratorAsc() { + s := garray.NewIntArrayFrom(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + s.IteratorAsc(func(k int, v int) bool { + fmt.Println(k, v) + return true + }) + + // Output: + // 0 10 + // 1 20 + // 2 15 + // 3 30 + // 4 40 + // 5 50 + // 6 60 +} + +func ExampleIntArray_IteratorDesc() { + s := garray.NewIntArrayFrom(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + s.IteratorDesc(func(k int, v int) bool { + fmt.Println(k, v) + return true + }) + + // Output: + // 6 60 + // 5 50 + // 4 40 + // 3 30 + // 2 15 + // 1 20 + // 0 10 +} + +func ExampleIntArray_String() { + s := garray.NewIntArrayFrom(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + fmt.Println(s) + fmt.Println(s.String()) + + // Output: + // [10,20,15,30,40,50,60] + // [10,20,15,30,40,50,60] +} + +func ExampleIntArray_MarshalJSON() { + type Student struct { + Id int + Name string + Scores garray.IntArray + } + var array garray.IntArray + array.SetArray(g.SliceInt{98, 97, 96}) + s := Student{ + Id: 1, + Name: "john", + Scores: array, + } + b, _ := json.Marshal(s) + fmt.Println(string(b)) + + // Output: + // {"Id":1,"Name":"john","Scores":[98,97,96]} +} + +func ExampleIntArray_UnmarshalJSON() { + b := []byte(`{"Id":1,"Name":"john","Scores":[98,96,97]}`) + type Student struct { + Id int + Name string + Scores *garray.IntArray + } + s := Student{} + json.Unmarshal(b, &s) + fmt.Println(s) + + // Output: + // {1 john [98,96,97]} +} + +func ExampleIntArray_UnmarshalValue() { + type Student struct { + Name string + Scores *garray.IntArray + } + + var s *Student + gconv.Struct(g.Map{ + "name": "john", + "scores": g.SliceInt{96, 98, 97}, + }, &s) + fmt.Println(s) + + // Output: + // &{john [96,98,97]} +} + +func ExampleIntArray_FilterEmpty() { + s := garray.NewIntArrayFrom(g.SliceInt{10, 40, 50, 0, 0, 0, 60}) + fmt.Println(s) + fmt.Println(s.FilterEmpty()) + + // Output: + // [10,40,50,0,0,0,60] + // [10,40,50,60] +} + +func ExampleIntArray_IsEmpty() { + s := garray.NewIntArrayFrom(g.SliceInt{10, 20, 15, 30, 40, 50, 60}) + fmt.Println(s.IsEmpty()) + s1 := garray.NewIntArray() + fmt.Println(s1.IsEmpty()) + + // Output: + // false + // true +} diff --git a/container/garray/garray_z_example_str_test.go b/container/garray/garray_z_example_normal_str_test.go similarity index 97% rename from container/garray/garray_z_example_str_test.go rename to container/garray/garray_z_example_normal_str_test.go index f07bded82..0444cc676 100644 --- a/container/garray/garray_z_example_str_test.go +++ b/container/garray/garray_z_example_normal_str_test.go @@ -8,6 +8,7 @@ package garray_test import ( "fmt" + "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/internal/json" @@ -30,7 +31,7 @@ func ExampleStrArray_Walk() { // [gf_user gf_user_detail] } -func ExampleStrArray_NewStrArray() { +func ExampleNewStrArray() { s := garray.NewStrArray() s.Append("We") s.Append("are") @@ -42,7 +43,7 @@ func ExampleStrArray_NewStrArray() { // [We are GF fans] } -func ExampleStrArray_NewStrArraySize() { +func ExampleNewStrArraySize() { s := garray.NewStrArraySize(3, 5) s.Set(0, "We") s.Set(1, "are") @@ -54,7 +55,7 @@ func ExampleStrArray_NewStrArraySize() { // [We are GF] 3 5 } -func ExampleStrArray_NewStrArrayFrom() { +func ExampleNewStrArrayFrom() { s := garray.NewStrArrayFrom(g.SliceStr{"We", "are", "GF", "fans", "!"}) fmt.Println(s.Slice(), s.Len(), cap(s.Slice())) @@ -62,14 +63,6 @@ func ExampleStrArray_NewStrArrayFrom() { // [We are GF fans !] 5 5 } -func ExampleStrArray_NewStrArrayFromCopy() { - s := garray.NewStrArrayFromCopy(g.SliceStr{"We", "are", "GF", "fans", "!"}) - fmt.Println(s.Slice(), s.Len(), cap(s.Slice())) - - // Output: - // [We are GF fans !] 5 5 -} - func ExampleStrArray_At() { s := garray.NewStrArrayFrom(g.SliceStr{"We", "are", "GF", "fans", "!"}) sAt := s.At(2) diff --git a/container/garray/garray_z_example_sorted_str_test.go b/container/garray/garray_z_example_sorted_str_test.go new file mode 100644 index 000000000..37b08ce27 --- /dev/null +++ b/container/garray/garray_z_example_sorted_str_test.go @@ -0,0 +1,574 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +package garray_test + +import ( + "fmt" + + "github.com/gogf/gf/v2/container/garray" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" + "github.com/gogf/gf/v2/util/gconv" +) + +func ExampleSortedStrArray_Walk() { + var array garray.SortedStrArray + tables := g.SliceStr{"user", "user_detail"} + prefix := "gf_" + array.Append(tables...) + // Add prefix for given table names. + array.Walk(func(value string) string { + return prefix + value + }) + fmt.Println(array.Slice()) + + // Output: + // [gf_user gf_user_detail] +} + +func ExampleNewSortedStrArray() { + s := garray.NewSortedStrArray() + s.Append("b") + s.Append("d") + s.Append("c") + s.Append("a") + fmt.Println(s.Slice()) + + // Output: + // [a b c d] +} + +func ExampleNewSortedStrArraySize() { + s := garray.NewSortedStrArraySize(3) + s.SetArray([]string{"b", "d", "a", "c"}) + fmt.Println(s.Slice(), s.Len(), cap(s.Slice())) + + // Output: + // [a b c d] 4 4 +} + +func ExampleNewStrArrayFromCopy() { + s := garray.NewSortedStrArrayFromCopy(g.SliceStr{"b", "d", "c", "a"}) + fmt.Println(s.Slice()) + + // Output: + // [a b c d] +} + +func ExampleSortedStrArray_At() { + s := garray.NewSortedStrArrayFrom(g.SliceStr{"b", "d", "c", "a"}) + sAt := s.At(2) + fmt.Println(s) + fmt.Println(sAt) + + // Output: + // ["a","b","c","d"] + // c + +} + +func ExampleSortedStrArray_Get() { + s := garray.NewSortedStrArrayFrom(g.SliceStr{"b", "d", "c", "a", "e"}) + sGet, sBool := s.Get(3) + fmt.Println(s) + fmt.Println(sGet, sBool) + + // Output: + // ["a","b","c","d","e"] + // d true +} + +func ExampleSortedStrArray_SetArray() { + s := garray.NewSortedStrArray() + s.SetArray([]string{"b", "d", "a", "c"}) + fmt.Println(s.Slice()) + + // Output: + // [a b c d] +} + +func ExampleSortedStrArray_SetUnique() { + s := garray.NewSortedStrArray() + s.SetArray([]string{"b", "d", "a", "c", "c", "a"}) + fmt.Println(s.SetUnique(true)) + + // Output: + // ["a","b","c","d"] +} + +func ExampleSortedStrArray_Sum() { + s := garray.NewSortedStrArray() + s.SetArray([]string{"5", "3", "2"}) + fmt.Println(s) + a := s.Sum() + fmt.Println(a) + + // Output: + // ["2","3","5"] + // 10 +} + +func ExampleSortedStrArray_Sort() { + s := garray.NewSortedStrArray() + s.SetArray(g.SliceStr{"b", "d", "a", "c"}) + fmt.Println(s) + a := s.Sort() + fmt.Println(a) + + // Output: + // ["a","b","c","d"] + // ["a","b","c","d"] +} + +func ExampleSortedStrArray_Remove() { + s := garray.NewSortedStrArray() + s.SetArray(g.SliceStr{"b", "d", "c", "a"}) + fmt.Println(s.Slice()) + s.Remove(1) + fmt.Println(s.Slice()) + + // Output: + // [a b c d] + // [a c d] +} + +func ExampleSortedStrArray_RemoveValue() { + s := garray.NewSortedStrArray() + s.SetArray(g.SliceStr{"b", "d", "c", "a"}) + fmt.Println(s.Slice()) + s.RemoveValue("b") + fmt.Println(s.Slice()) + + // Output: + // [a b c d] + // [a c d] +} + +func ExampleSortedStrArray_PopLeft() { + s := garray.NewSortedStrArray() + s.SetArray(g.SliceStr{"b", "d", "c", "a"}) + r, _ := s.PopLeft() + fmt.Println(r) + fmt.Println(s.Slice()) + + // Output: + // a + // [b c d] +} + +func ExampleSortedStrArray_PopRight() { + s := garray.NewSortedStrArray() + s.SetArray(g.SliceStr{"b", "d", "c", "a"}) + fmt.Println(s.Slice()) + r, _ := s.PopRight() + fmt.Println(r) + fmt.Println(s.Slice()) + + // Output: + // [a b c d] + // d + // [a b c] +} + +func ExampleSortedStrArray_PopRights() { + s := garray.NewSortedStrArray() + s.SetArray(g.SliceStr{"c", "b", "a", "d", "f", "e", "h", "g"}) + r := s.PopRights(2) + fmt.Println(r) + fmt.Println(s) + + // Output: + // [g h] + // ["a","b","c","d","e","f"] +} + +func ExampleSortedStrArray_Rand() { + s := garray.NewSortedStrArray() + s.SetArray(g.SliceStr{"c", "b", "a", "d", "f", "e", "h", "g"}) + r, _ := s.PopRand() + fmt.Println(r) + fmt.Println(s) + + // May Output: + // b + // ["a","c","d","e","f","g","h"] +} + +func ExampleSortedStrArray_PopRands() { + s := garray.NewSortedStrArray() + s.SetArray(g.SliceStr{"c", "b", "a", "d", "f", "e", "h", "g"}) + r := s.PopRands(2) + fmt.Println(r) + fmt.Println(s) + + // May Output: + // [d a] + // ["b","c","e","f","g","h"] +} + +func ExampleSortedStrArray_PopLefts() { + s := garray.NewSortedStrArray() + s.SetArray(g.SliceStr{"c", "b", "a", "d", "f", "e", "h", "g"}) + r := s.PopLefts(2) + fmt.Println(r) + fmt.Println(s) + + // Output: + // [a b] + // ["c","d","e","f","g","h"] +} + +func ExampleSortedStrArray_Range() { + s := garray.NewSortedStrArray() + s.SetArray(g.SliceStr{"c", "b", "a", "d", "f", "e", "h", "g"}) + r := s.Range(2, 5) + fmt.Println(r) + + // Output: + // [c d e] +} + +func ExampleSortedStrArray_SubSlice() { + s := garray.NewSortedStrArray() + s.SetArray(g.SliceStr{"c", "b", "a", "d", "f", "e", "h", "g"}) + r := s.SubSlice(3, 4) + fmt.Println(s.Slice()) + fmt.Println(r) + + // Output: + // [a b c d e f g h] + // [d e f g] +} + +func ExampleSortedStrArray_Add() { + s := garray.NewSortedStrArray() + s.Add("b", "d", "c", "a") + fmt.Println(s) + + // Output: + // ["a","b","c","d"] +} + +func ExampleSortedStrArray_Append() { + s := garray.NewSortedStrArray() + s.SetArray(g.SliceStr{"b", "d", "c", "a"}) + fmt.Println(s) + s.Append("f", "e", "g") + fmt.Println(s) + + // Output: + // ["a","b","c","d"] + // ["a","b","c","d","e","f","g"] +} + +func ExampleSortedStrArray_Len() { + s := garray.NewSortedStrArray() + s.SetArray(g.SliceStr{"c", "b", "a", "d", "f", "e", "h", "g"}) + fmt.Println(s) + fmt.Println(s.Len()) + + // Output: + // ["a","b","c","d","e","f","g","h"] + // 8 +} + +func ExampleSortedStrArray_Slice() { + s := garray.NewSortedStrArray() + s.SetArray(g.SliceStr{"c", "b", "a", "d", "f", "e", "h", "g"}) + fmt.Println(s.Slice()) + + // Output: + // [a b c d e f g h] +} + +func ExampleSortedStrArray_Interfaces() { + s := garray.NewSortedStrArray() + s.SetArray(g.SliceStr{"c", "b", "a", "d", "f", "e", "h", "g"}) + r := s.Interfaces() + fmt.Println(r) + + // Output: + // [a b c d e f g h] +} + +func ExampleSortedStrArray_Clone() { + s := garray.NewSortedStrArray() + s.SetArray(g.SliceStr{"c", "b", "a", "d", "f", "e", "h", "g"}) + r := s.Clone() + fmt.Println(r) + fmt.Println(s) + + // Output: + // ["a","b","c","d","e","f","g","h"] + // ["a","b","c","d","e","f","g","h"] +} + +func ExampleSortedStrArray_Clear() { + s := garray.NewSortedStrArray() + s.SetArray(g.SliceStr{"c", "b", "a", "d", "f", "e", "h", "g"}) + fmt.Println(s) + fmt.Println(s.Clear()) + fmt.Println(s) + + // Output: + // ["a","b","c","d","e","f","g","h"] + // [] + // [] +} + +func ExampleSortedStrArray_Contains() { + s := garray.NewSortedStrArray() + s.SetArray(g.SliceStr{"c", "b", "a", "d", "f", "e", "h", "g"}) + fmt.Println(s.Contains("e")) + fmt.Println(s.Contains("E")) + fmt.Println(s.Contains("z")) + + // Output: + // true + // false + // false +} + +func ExampleSortedStrArray_ContainsI() { + s := garray.NewSortedStrArray() + s.SetArray(g.SliceStr{"c", "b", "a", "d", "f", "e", "h", "g"}) + fmt.Println(s) + fmt.Println(s.ContainsI("E")) + fmt.Println(s.ContainsI("z")) + + // Output: + // ["a","b","c","d","e","f","g","h"] + // true + // false +} + +func ExampleSortedStrArray_Search() { + s := garray.NewSortedStrArray() + s.SetArray(g.SliceStr{"c", "b", "a", "d", "f", "e", "h", "g"}) + fmt.Println(s) + fmt.Println(s.Search("e")) + fmt.Println(s.Search("E")) + fmt.Println(s.Search("z")) + + // Output: + // ["a","b","c","d","e","f","g","h"] + // 4 + // -1 + // -1 +} + +func ExampleSortedStrArray_Unique() { + s := garray.NewSortedStrArray() + s.SetArray(g.SliceStr{"a", "b", "c", "c", "c", "d", "d"}) + fmt.Println(s) + fmt.Println(s.Unique()) + + // Output: + // ["a","b","c","c","c","d","d"] + // ["a","b","c","d"] +} + +func ExampleSortedStrArray_LockFunc() { + s := garray.NewSortedStrArrayFrom(g.SliceStr{"b", "c", "a"}) + s.LockFunc(func(array []string) { + array[len(array)-1] = "GF fans" + }) + fmt.Println(s) + + // Output: + // ["a","b","GF fans"] +} + +func ExampleSortedStrArray_RLockFunc() { + s := garray.NewSortedStrArrayFrom(g.SliceStr{"b", "c", "a"}) + s.RLockFunc(func(array []string) { + array[len(array)-1] = "GF fans" + fmt.Println(array[len(array)-1]) + }) + fmt.Println(s) + + // Output: + // GF fans + // ["a","b","GF fans"] +} + +func ExampleSortedStrArray_Merge() { + s1 := garray.NewSortedStrArray() + s2 := garray.NewSortedStrArray() + s1.SetArray(g.SliceStr{"b", "c", "a"}) + s2.SetArray(g.SliceStr{"e", "d", "f"}) + fmt.Println(s1) + fmt.Println(s2) + s1.Merge(s2) + fmt.Println(s1) + + // Output: + // ["a","b","c"] + // ["d","e","f"] + // ["a","b","c","d","e","f"] +} + +func ExampleSortedStrArray_Chunk() { + s := garray.NewSortedStrArrayFrom(g.SliceStr{"c", "b", "a", "d", "f", "e", "h", "g"}) + r := s.Chunk(3) + fmt.Println(r) + + // Output: + // [[a b c] [d e f] [g h]] +} + +func ExampleSortedStrArray_Rands() { + s := garray.NewSortedStrArrayFrom(g.SliceStr{"c", "b", "a", "d", "f", "e", "h", "g"}) + fmt.Println(s) + fmt.Println(s.Rands(3)) + + // May Output: + // ["a","b","c","d","e","f","g","h"] + // [h g c] +} + +func ExampleSortedStrArray_Join() { + s := garray.NewSortedStrArrayFrom(g.SliceStr{"c", "b", "a", "d", "f", "e", "h", "g"}) + fmt.Println(s.Join(",")) + + // Output: + // a,b,c,d,e,f,g,h +} + +func ExampleSortedStrArray_CountValues() { + s := garray.NewSortedStrArrayFrom(g.SliceStr{"a", "b", "c", "c", "c", "d", "d"}) + fmt.Println(s.CountValues()) + + // Output: + // map[a:1 b:1 c:3 d:2] +} + +func ExampleSortedStrArray_Iterator() { + s := garray.NewSortedStrArrayFrom(g.SliceStr{"b", "c", "a"}) + s.Iterator(func(k int, v string) bool { + fmt.Println(k, v) + return true + }) + + // Output: + // 0 a + // 1 b + // 2 c +} + +func ExampleSortedStrArray_IteratorAsc() { + s := garray.NewSortedStrArrayFrom(g.SliceStr{"b", "c", "a"}) + s.IteratorAsc(func(k int, v string) bool { + fmt.Println(k, v) + return true + }) + + // Output: + // 0 a + // 1 b + // 2 c +} + +func ExampleSortedStrArray_IteratorDesc() { + s := garray.NewSortedStrArrayFrom(g.SliceStr{"b", "c", "a"}) + s.IteratorDesc(func(k int, v string) bool { + fmt.Println(k, v) + return true + }) + + // Output: + // 2 c + // 1 b + // 0 a +} + +func ExampleSortedStrArray_String() { + s := garray.NewSortedStrArrayFrom(g.SliceStr{"b", "c", "a"}) + fmt.Println(s.String()) + + // Output: + // ["a","b","c"] +} + +func ExampleSortedStrArray_MarshalJSON() { + type Student struct { + ID int + Name string + Levels garray.SortedStrArray + } + r := garray.NewSortedStrArrayFrom(g.SliceStr{"b", "c", "a"}) + s := Student{ + ID: 1, + Name: "john", + Levels: *r, + } + b, _ := json.Marshal(s) + fmt.Println(string(b)) + + // Output: + // {"ID":1,"Name":"john","Levels":["a","b","c"]} +} + +func ExampleSortedStrArray_UnmarshalJSON() { + b := []byte(`{"Id":1,"Name":"john","Lessons":["Math","English","Sport"]}`) + type Student struct { + Id int + Name string + Lessons *garray.StrArray + } + s := Student{} + json.Unmarshal(b, &s) + fmt.Println(s) + + // Output: + // {1 john ["Math","English","Sport"]} +} + +func ExampleSortedStrArray_UnmarshalValue() { + type Student struct { + Name string + Lessons *garray.StrArray + } + var s *Student + gconv.Struct(g.Map{ + "name": "john", + "lessons": []byte(`["Math","English","Sport"]`), + }, &s) + fmt.Println(s) + + var s1 *Student + gconv.Struct(g.Map{ + "name": "john", + "lessons": g.SliceStr{"Math", "English", "Sport"}, + }, &s1) + fmt.Println(s1) + + // Output: + // &{john ["Math","English","Sport"]} + // &{john ["Math","English","Sport"]} +} + +func ExampleSortedStrArray_FilterEmpty() { + s := garray.NewSortedStrArrayFrom(g.SliceStr{"b", "a", "", "c", "", "", "d"}) + fmt.Println(s) + fmt.Println(s.FilterEmpty()) + + // Output: + // ["","","","a","b","c","d"] + // ["a","b","c","d"] +} + +func ExampleSortedStrArray_IsEmpty() { + s := garray.NewSortedStrArrayFrom(g.SliceStr{"b", "a", "", "c", "", "", "d"}) + fmt.Println(s.IsEmpty()) + s1 := garray.NewSortedStrArray() + fmt.Println(s1.IsEmpty()) + + // Output: + // false + // true +} diff --git a/container/garray/garray_z_unit_all_basic_test.go b/container/garray/garray_z_unit_all_basic_test.go index 77e7f9a21..1fff15620 100644 --- a/container/garray/garray_z_unit_all_basic_test.go +++ b/container/garray/garray_z_unit_all_basic_test.go @@ -9,13 +9,13 @@ package garray_test import ( - "github.com/gogf/gf/v2/util/gutil" "strings" "testing" "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gconv" + "github.com/gogf/gf/v2/util/gutil" ) func Test_Array_Var(t *testing.T) { diff --git a/container/garray/garray_z_unit_normal_any_array_test.go b/container/garray/garray_z_unit_normal_any_test.go similarity index 96% rename from container/garray/garray_z_unit_normal_any_array_test.go rename to container/garray/garray_z_unit_normal_any_test.go index f0735b3f6..d1e132174 100644 --- a/container/garray/garray_z_unit_normal_any_array_test.go +++ b/container/garray/garray_z_unit_normal_any_test.go @@ -9,12 +9,12 @@ package garray_test import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/internal/json" "testing" "time" "github.com/gogf/gf/v2/container/garray" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gconv" ) @@ -260,7 +260,7 @@ func TestArray_Merge(t *testing.T) { array2 := garray.NewArrayFrom(i2) t.Assert(array1.Merge(array2).Slice(), []interface{}{0, 1, 2, 3, 4, 5, 6, 7}) - //s1 := []string{"a", "b", "c", "d"} + // s1 := []string{"a", "b", "c", "d"} s2 := []string{"e", "f"} i3 := garray.NewIntArrayFrom([]int{1, 2, 3}) i4 := garray.NewArrayFrom([]interface{}{3}) @@ -502,16 +502,16 @@ func TestArray_LockFunc(t *testing.T) { ch1 := make(chan int64, 3) ch2 := make(chan int64, 3) - //go1 - go a1.LockFunc(func(n1 []interface{}) { //读写锁 - time.Sleep(2 * time.Second) //暂停2秒 + // go1 + go a1.LockFunc(func(n1 []interface{}) { // 读写锁 + time.Sleep(2 * time.Second) // 暂停2秒 n1[2] = "g" ch2 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) }) - //go2 + // go2 go func() { - time.Sleep(100 * time.Millisecond) //故意暂停0.01秒,等go1执行锁后,再开始执行. + time.Sleep(100 * time.Millisecond) // 故意暂停0.01秒,等go1执行锁后,再开始执行. ch1 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) a1.Len() ch1 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) @@ -519,10 +519,10 @@ func TestArray_LockFunc(t *testing.T) { t1 := <-ch1 t2 := <-ch1 - <-ch2 //等待go1完成 + <-ch2 // 等待go1完成 // 防止ci抖动,以豪秒为单位 - t.AssertGT(t2-t1, 20) //go1加的读写互斥锁,所go2读的时候被阻塞。 + t.AssertGT(t2-t1, 20) // go1加的读写互斥锁,所go2读的时候被阻塞。 t.Assert(a1.Contains("g"), true) }) } @@ -534,16 +534,16 @@ func TestArray_RLockFunc(t *testing.T) { ch1 := make(chan int64, 3) ch2 := make(chan int64, 1) - //go1 - go a1.RLockFunc(func(n1 []interface{}) { //读锁 - time.Sleep(2 * time.Second) //暂停1秒 + // go1 + go a1.RLockFunc(func(n1 []interface{}) { // 读锁 + time.Sleep(2 * time.Second) // 暂停1秒 n1[2] = "g" ch2 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) }) - //go2 + // go2 go func() { - time.Sleep(100 * time.Millisecond) //故意暂停0.01秒,等go1执行锁后,再开始执行. + time.Sleep(100 * time.Millisecond) // 故意暂停0.01秒,等go1执行锁后,再开始执行. ch1 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) a1.Len() ch1 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) @@ -551,10 +551,10 @@ func TestArray_RLockFunc(t *testing.T) { t1 := <-ch1 t2 := <-ch1 - <-ch2 //等待go1完成 + <-ch2 // 等待go1完成 // 防止ci抖动,以豪秒为单位 - t.AssertLT(t2-t1, 20) //go1加的读锁,所go2读的时候,并没有阻塞。 + t.AssertLT(t2-t1, 20) // go1加的读锁,所go2读的时候,并没有阻塞。 t.Assert(a1.Contains("g"), true) }) } diff --git a/container/garray/garray_z_unit_normal_int_array_test.go b/container/garray/garray_z_unit_normal_int_test.go similarity index 96% rename from container/garray/garray_z_unit_normal_int_array_test.go rename to container/garray/garray_z_unit_normal_int_test.go index de097bc49..e8e3b79b3 100644 --- a/container/garray/garray_z_unit_normal_int_array_test.go +++ b/container/garray/garray_z_unit_normal_int_test.go @@ -9,15 +9,14 @@ package garray_test import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/internal/json" "testing" "time" - "github.com/gogf/gf/v2/util/gconv" - "github.com/gogf/gf/v2/container/garray" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gconv" ) func Test_IntArray_Basic(t *testing.T) { @@ -534,16 +533,16 @@ func TestIntArray_LockFunc(t *testing.T) { ch1 := make(chan int64, 3) ch2 := make(chan int64, 3) - //go1 - go a1.LockFunc(func(n1 []int) { //读写锁 - time.Sleep(2 * time.Second) //暂停2秒 + // go1 + go a1.LockFunc(func(n1 []int) { // 读写锁 + time.Sleep(2 * time.Second) // 暂停2秒 n1[2] = 6 ch2 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) }) - //go2 + // go2 go func() { - time.Sleep(100 * time.Millisecond) //故意暂停0.01秒,等go1执行锁后,再开始执行. + time.Sleep(100 * time.Millisecond) // 故意暂停0.01秒,等go1执行锁后,再开始执行. ch1 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) a1.Len() ch1 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) @@ -551,10 +550,10 @@ func TestIntArray_LockFunc(t *testing.T) { t1 := <-ch1 t2 := <-ch1 - <-ch2 //等待go1完成 + <-ch2 // 等待go1完成 // 防止ci抖动,以豪秒为单位 - t.AssertGT(t2-t1, 20) //go1加的读写互斥锁,所go2读的时候被阻塞。 + t.AssertGT(t2-t1, 20) // go1加的读写互斥锁,所go2读的时候被阻塞。 t.Assert(a1.Contains(6), true) }) } @@ -579,16 +578,16 @@ func TestIntArray_RLockFunc(t *testing.T) { ch1 := make(chan int64, 3) ch2 := make(chan int64, 1) - //go1 - go a1.RLockFunc(func(n1 []int) { //读锁 - time.Sleep(2 * time.Second) //暂停1秒 + // go1 + go a1.RLockFunc(func(n1 []int) { // 读锁 + time.Sleep(2 * time.Second) // 暂停1秒 n1[2] = 6 ch2 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) }) - //go2 + // go2 go func() { - time.Sleep(100 * time.Millisecond) //故意暂停0.01秒,等go1执行锁后,再开始执行. + time.Sleep(100 * time.Millisecond) // 故意暂停0.01秒,等go1执行锁后,再开始执行. ch1 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) a1.Len() ch1 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) @@ -596,10 +595,10 @@ func TestIntArray_RLockFunc(t *testing.T) { t1 := <-ch1 t2 := <-ch1 - <-ch2 //等待go1完成 + <-ch2 // 等待go1完成 // 防止ci抖动,以豪秒为单位 - t.AssertLT(t2-t1, 20) //go1加的读锁,所go2读的时候,并没有阻塞。 + t.AssertLT(t2-t1, 20) // go1加的读锁,所go2读的时候,并没有阻塞。 t.Assert(a1.Contains(6), true) }) } @@ -758,7 +757,7 @@ func TestIntArray_UnmarshalValue(t *testing.T) { t.Assert(v.Array.Slice(), g.Slice{1, 2, 3}) }) // Map - //gtest.C(t, func(t *gtest.T) { + // gtest.C(t, func(t *gtest.T) { // var v *V // err := gconv.Struct(g.Map{ // "name": "john", @@ -767,7 +766,7 @@ func TestIntArray_UnmarshalValue(t *testing.T) { // t.Assert(err, nil) // t.Assert(v.Name, "john") // t.Assert(v.Array.Slice(), g.Slice{1, 2, 3}) - //}) + // }) } func TestIntArray_FilterEmpty(t *testing.T) { diff --git a/container/garray/garray_z_unit_normal_str_array_test.go b/container/garray/garray_z_unit_normal_str_test.go similarity index 96% rename from container/garray/garray_z_unit_normal_str_array_test.go rename to container/garray/garray_z_unit_normal_str_test.go index 9cb7b67f6..d5d8bcf6e 100644 --- a/container/garray/garray_z_unit_normal_str_array_test.go +++ b/container/garray/garray_z_unit_normal_str_test.go @@ -9,13 +9,13 @@ package garray_test import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/internal/json" "strings" "testing" "time" "github.com/gogf/gf/v2/container/garray" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gconv" ) @@ -534,16 +534,16 @@ func TestStrArray_RLockFunc(t *testing.T) { ch1 := make(chan int64, 3) ch2 := make(chan int64, 1) - //go1 - go a1.RLockFunc(func(n1 []string) { //读锁 - time.Sleep(2 * time.Second) //暂停1秒 + // go1 + go a1.RLockFunc(func(n1 []string) { // 读锁 + time.Sleep(2 * time.Second) // 暂停1秒 n1[2] = "g" ch2 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) }) - //go2 + // go2 go func() { - time.Sleep(100 * time.Millisecond) //故意暂停0.01秒,等go1执行锁后,再开始执行. + time.Sleep(100 * time.Millisecond) // 故意暂停0.01秒,等go1执行锁后,再开始执行. ch1 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) a1.Len() ch1 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) @@ -551,10 +551,10 @@ func TestStrArray_RLockFunc(t *testing.T) { t1 := <-ch1 t2 := <-ch1 - <-ch2 //等待go1完成 + <-ch2 // 等待go1完成 // 防止ci抖动,以豪秒为单位 - t.AssertLT(t2-t1, 20) //go1加的读锁,所go2读的时候,并没有阻塞。 + t.AssertLT(t2-t1, 20) // go1加的读锁,所go2读的时候,并没有阻塞。 t.Assert(a1.Contains("g"), true) }) } @@ -578,16 +578,16 @@ func TestStrArray_LockFunc(t *testing.T) { ch1 := make(chan int64, 3) ch2 := make(chan int64, 3) - //go1 - go a1.LockFunc(func(n1 []string) { //读写锁 - time.Sleep(2 * time.Second) //暂停2秒 + // go1 + go a1.LockFunc(func(n1 []string) { // 读写锁 + time.Sleep(2 * time.Second) // 暂停2秒 n1[2] = "g" ch2 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) }) - //go2 + // go2 go func() { - time.Sleep(100 * time.Millisecond) //故意暂停0.01秒,等go1执行锁后,再开始执行. + time.Sleep(100 * time.Millisecond) // 故意暂停0.01秒,等go1执行锁后,再开始执行. ch1 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) a1.Len() ch1 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) @@ -595,10 +595,10 @@ func TestStrArray_LockFunc(t *testing.T) { t1 := <-ch1 t2 := <-ch1 - <-ch2 //等待go1完成 + <-ch2 // 等待go1完成 // 防止ci抖动,以豪秒为单位 - t.AssertGT(t2-t1, 20) //go1加的读写互斥锁,所go2读的时候被阻塞。 + t.AssertGT(t2-t1, 20) // go1加的读写互斥锁,所go2读的时候被阻塞。 t.Assert(a1.Contains("g"), true) }) } diff --git a/container/garray/garray_z_unit_sorted_any_array_test.go b/container/garray/garray_z_unit_sorted_any_test.go similarity index 97% rename from container/garray/garray_z_unit_sorted_any_array_test.go rename to container/garray/garray_z_unit_sorted_any_test.go index 92e4ed515..1513aa342 100644 --- a/container/garray/garray_z_unit_sorted_any_array_test.go +++ b/container/garray/garray_z_unit_sorted_any_test.go @@ -9,16 +9,16 @@ package garray_test import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/util/gutil" "strings" "testing" "time" "github.com/gogf/gf/v2/container/garray" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gconv" + "github.com/gogf/gf/v2/util/gutil" ) func TestSortedArray_NewSortedArrayFrom(t *testing.T) { @@ -554,16 +554,16 @@ func TestSortedArray_LockFunc(t *testing.T) { ch1 := make(chan int64, 3) ch2 := make(chan int64, 3) - //go1 - go a1.LockFunc(func(n1 []interface{}) { //读写锁 - time.Sleep(2 * time.Second) //暂停2秒 + // go1 + go a1.LockFunc(func(n1 []interface{}) { // 读写锁 + time.Sleep(2 * time.Second) // 暂停2秒 n1[2] = "g" ch2 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) }) - //go2 + // go2 go func() { - time.Sleep(100 * time.Millisecond) //故意暂停0.01秒,等go1执行锁后,再开始执行. + time.Sleep(100 * time.Millisecond) // 故意暂停0.01秒,等go1执行锁后,再开始执行. ch1 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) a1.Len() ch1 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) @@ -571,10 +571,10 @@ func TestSortedArray_LockFunc(t *testing.T) { t1 := <-ch1 t2 := <-ch1 - <-ch2 //等待go1完成 + <-ch2 // 等待go1完成 // 防止ci抖动,以豪秒为单位 - t.AssertGT(t2-t1, 20) //go1加的读写互斥锁,所go2读的时候被阻塞。 + t.AssertGT(t2-t1, 20) // go1加的读写互斥锁,所go2读的时候被阻塞。 t.Assert(a1.Contains("g"), true) }) } @@ -589,16 +589,16 @@ func TestSortedArray_RLockFunc(t *testing.T) { ch1 := make(chan int64, 3) ch2 := make(chan int64, 3) - //go1 - go a1.RLockFunc(func(n1 []interface{}) { //读写锁 - time.Sleep(2 * time.Second) //暂停2秒 + // go1 + go a1.RLockFunc(func(n1 []interface{}) { // 读写锁 + time.Sleep(2 * time.Second) // 暂停2秒 n1[2] = "g" ch2 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) }) - //go2 + // go2 go func() { - time.Sleep(100 * time.Millisecond) //故意暂停0.01秒,等go1执行锁后,再开始执行. + time.Sleep(100 * time.Millisecond) // 故意暂停0.01秒,等go1执行锁后,再开始执行. ch1 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) a1.Len() ch1 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) @@ -606,10 +606,10 @@ func TestSortedArray_RLockFunc(t *testing.T) { t1 := <-ch1 t2 := <-ch1 - <-ch2 //等待go1完成 + <-ch2 // 等待go1完成 // 防止ci抖动,以豪秒为单位 - t.AssertLT(t2-t1, 20) //go1加的读锁,所go2读的时候不会被阻塞。 + t.AssertLT(t2-t1, 20) // go1加的读锁,所go2读的时候不会被阻塞。 t.Assert(a1.Contains("g"), true) }) } diff --git a/container/garray/garray_z_unit_sorted_int_array_test.go b/container/garray/garray_z_unit_sorted_int_test.go similarity index 95% rename from container/garray/garray_z_unit_sorted_int_array_test.go rename to container/garray/garray_z_unit_sorted_int_test.go index b060f4c7d..c653340c6 100644 --- a/container/garray/garray_z_unit_sorted_int_array_test.go +++ b/container/garray/garray_z_unit_sorted_int_test.go @@ -9,15 +9,14 @@ package garray_test import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/internal/json" "testing" "time" - "github.com/gogf/gf/v2/util/gconv" - "github.com/gogf/gf/v2/container/garray" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gconv" ) func TestNewSortedIntArrayFrom(t *testing.T) { @@ -337,7 +336,7 @@ func TestSortedIntArray_Chunk(t *testing.T) { gtest.C(t, func(t *gtest.T) { a1 := []int{1, 2, 3, 4, 5} array1 := garray.NewSortedIntArrayFrom(a1) - ns1 := array1.Chunk(2) //按每几个元素切成一个数组 + ns1 := array1.Chunk(2) // 按每几个元素切成一个数组 ns2 := array1.Chunk(-1) t.Assert(len(ns1), 3) t.Assert(ns1[0], []int{1, 2}) @@ -427,7 +426,7 @@ func TestSortedIntArray_CountValues(t *testing.T) { gtest.C(t, func(t *gtest.T) { a1 := []int{1, 2, 3, 4, 5, 3} array1 := garray.NewSortedIntArrayFrom(a1) - ns1 := array1.CountValues() //按每几个元素切成一个数组 + ns1 := array1.CountValues() // 按每几个元素切成一个数组 t.Assert(len(ns1), 5) t.Assert(ns1[2], 1) t.Assert(ns1[3], 2) @@ -460,16 +459,16 @@ func TestSortedIntArray_LockFunc(t *testing.T) { a1 := garray.NewSortedIntArrayFrom(s1, true) ch1 := make(chan int64, 3) ch2 := make(chan int64, 3) - //go1 - go a1.LockFunc(func(n1 []int) { //读写锁 - time.Sleep(2 * time.Second) //暂停2秒 + // go1 + go a1.LockFunc(func(n1 []int) { // 读写锁 + time.Sleep(2 * time.Second) // 暂停2秒 n1[2] = 6 ch2 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) }) - //go2 + // go2 go func() { - time.Sleep(100 * time.Millisecond) //故意暂停0.01秒,等go1执行锁后,再开始执行. + time.Sleep(100 * time.Millisecond) // 故意暂停0.01秒,等go1执行锁后,再开始执行. ch1 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) a1.Len() ch1 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) @@ -477,10 +476,10 @@ func TestSortedIntArray_LockFunc(t *testing.T) { t1 := <-ch1 t2 := <-ch1 - <-ch2 //等待go1完成 + <-ch2 // 等待go1完成 // 防止ci抖动,以豪秒为单位 - t.AssertGT(t2-t1, 20) //go1加的读写互斥锁,所go2读的时候被阻塞。 + t.AssertGT(t2-t1, 20) // go1加的读写互斥锁,所go2读的时候被阻塞。 t.Assert(a1.Contains(6), true) }) } @@ -492,16 +491,16 @@ func TestSortedIntArray_RLockFunc(t *testing.T) { ch1 := make(chan int64, 3) ch2 := make(chan int64, 1) - //go1 - go a1.RLockFunc(func(n1 []int) { //读锁 - time.Sleep(2 * time.Second) //暂停1秒 + // go1 + go a1.RLockFunc(func(n1 []int) { // 读锁 + time.Sleep(2 * time.Second) // 暂停1秒 n1[2] = 6 ch2 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) }) - //go2 + // go2 go func() { - time.Sleep(100 * time.Millisecond) //故意暂停0.01秒,等go1执行锁后,再开始执行. + time.Sleep(100 * time.Millisecond) // 故意暂停0.01秒,等go1执行锁后,再开始执行. ch1 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) a1.Len() ch1 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) @@ -509,10 +508,10 @@ func TestSortedIntArray_RLockFunc(t *testing.T) { t1 := <-ch1 t2 := <-ch1 - <-ch2 //等待go1完成 + <-ch2 // 等待go1完成 // 防止ci抖动,以豪秒为单位 - t.AssertLT(t2-t1, 20) //go1加的读锁,所go2读的时候,并没有阻塞。 + t.AssertLT(t2-t1, 20) // go1加的读锁,所go2读的时候,并没有阻塞。 t.Assert(a1.Contains(6), true) }) } diff --git a/container/garray/garray_z_unit_sorted_str_array_test.go b/container/garray/garray_z_unit_sorted_str_test.go similarity index 96% rename from container/garray/garray_z_unit_sorted_str_array_test.go rename to container/garray/garray_z_unit_sorted_str_test.go index 7da5ecd1f..7625064a1 100644 --- a/container/garray/garray_z_unit_sorted_str_array_test.go +++ b/container/garray/garray_z_unit_sorted_str_test.go @@ -9,12 +9,12 @@ package garray_test import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/internal/json" "testing" "time" "github.com/gogf/gf/v2/container/garray" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gconv" ) @@ -479,16 +479,16 @@ func TestSortedStrArray_LockFunc(t *testing.T) { ch1 := make(chan int64, 3) ch2 := make(chan int64, 3) - //go1 - go a1.LockFunc(func(n1 []string) { //读写锁 - time.Sleep(2 * time.Second) //暂停2秒 + // go1 + go a1.LockFunc(func(n1 []string) { // 读写锁 + time.Sleep(2 * time.Second) // 暂停2秒 n1[2] = "g" ch2 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) }) - //go2 + // go2 go func() { - time.Sleep(100 * time.Millisecond) //故意暂停0.01秒,等go1执行锁后,再开始执行. + time.Sleep(100 * time.Millisecond) // 故意暂停0.01秒,等go1执行锁后,再开始执行. ch1 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) a1.Len() ch1 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) @@ -496,10 +496,10 @@ func TestSortedStrArray_LockFunc(t *testing.T) { t1 := <-ch1 t2 := <-ch1 - <-ch2 //等待go1完成 + <-ch2 // 等待go1完成 // 防止ci抖动,以豪秒为单位 - t.AssertGT(t2-t1, 20) //go1加的读写互斥锁,所go2读的时候被阻塞。 + t.AssertGT(t2-t1, 20) // go1加的读写互斥锁,所go2读的时候被阻塞。 t.Assert(a1.Contains("g"), true) }) } @@ -511,16 +511,16 @@ func TestSortedStrArray_RLockFunc(t *testing.T) { ch1 := make(chan int64, 3) ch2 := make(chan int64, 1) - //go1 - go a1.RLockFunc(func(n1 []string) { //读锁 - time.Sleep(2 * time.Second) //暂停1秒 + // go1 + go a1.RLockFunc(func(n1 []string) { // 读锁 + time.Sleep(2 * time.Second) // 暂停1秒 n1[2] = "g" ch2 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) }) - //go2 + // go2 go func() { - time.Sleep(100 * time.Millisecond) //故意暂停0.01秒,等go1执行锁后,再开始执行. + time.Sleep(100 * time.Millisecond) // 故意暂停0.01秒,等go1执行锁后,再开始执行. ch1 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) a1.Len() ch1 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) @@ -528,10 +528,10 @@ func TestSortedStrArray_RLockFunc(t *testing.T) { t1 := <-ch1 t2 := <-ch1 - <-ch2 //等待go1完成 + <-ch2 // 等待go1完成 // 防止ci抖动,以豪秒为单位 - t.AssertLT(t2-t1, 20) //go1加的读锁,所go2读的时候,并没有阻塞。 + t.AssertLT(t2-t1, 20) // go1加的读锁,所go2读的时候,并没有阻塞。 t.Assert(a1.Contains("g"), true) }) } diff --git a/container/glist/glist.go b/container/glist/glist.go index 03bfa261b..d3e82a082 100644 --- a/container/glist/glist.go +++ b/container/glist/glist.go @@ -11,10 +11,10 @@ package glist import ( "bytes" "container/list" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/util/gconv" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/rwmutex" + "github.com/gogf/gf/v2/util/gconv" ) type ( diff --git a/container/glist/glist_z_example_test.go b/container/glist/glist_z_example_test.go index 54126b760..25781401a 100644 --- a/container/glist/glist_z_example_test.go +++ b/container/glist/glist_z_example_test.go @@ -9,10 +9,10 @@ package glist_test import ( "container/list" "fmt" - "github.com/gogf/gf/v2/container/garray" - "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/container/glist" + "github.com/gogf/gf/v2/frame/g" ) func ExampleNew() { diff --git a/container/glist/glist_z_unit_test.go b/container/glist/glist_z_unit_test.go index f7d7d2098..edd1f7c4b 100644 --- a/container/glist/glist_z_unit_test.go +++ b/container/glist/glist_z_unit_test.go @@ -8,11 +8,11 @@ package glist import ( "container/list" + "testing" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gconv" - - "testing" ) func checkListLen(t *gtest.T, l *List, len int) bool { @@ -46,34 +46,34 @@ func TestVar(t *testing.T) { if v := l.PopBack(); v != 1 { t.Errorf("EXPECT %v, GOT %v", 1, v) } else { - //fmt.Println(v) + // fmt.Println(v) } if v := l.PopBack(); v != 2 { t.Errorf("EXPECT %v, GOT %v", 2, v) } else { - //fmt.Println(v) + // fmt.Println(v) } if v := l.PopBack(); v != nil { t.Errorf("EXPECT %v, GOT %v", nil, v) } else { - //fmt.Println(v) + // fmt.Println(v) } l.PushBack(1) l.PushBack(2) if v := l.PopFront(); v != 1 { t.Errorf("EXPECT %v, GOT %v", 1, v) } else { - //fmt.Println(v) + // fmt.Println(v) } if v := l.PopFront(); v != 2 { t.Errorf("EXPECT %v, GOT %v", 2, v) } else { - //fmt.Println(v) + // fmt.Println(v) } if v := l.PopFront(); v != nil { t.Errorf("EXPECT %v, GOT %v", nil, v) } else { - //fmt.Println(v) + // fmt.Println(v) } } @@ -84,34 +84,34 @@ func TestBasic(t *testing.T) { if v := l.PopBack(); v != 1 { t.Errorf("EXPECT %v, GOT %v", 1, v) } else { - //fmt.Println(v) + // fmt.Println(v) } if v := l.PopBack(); v != 2 { t.Errorf("EXPECT %v, GOT %v", 2, v) } else { - //fmt.Println(v) + // fmt.Println(v) } if v := l.PopBack(); v != nil { t.Errorf("EXPECT %v, GOT %v", nil, v) } else { - //fmt.Println(v) + // fmt.Println(v) } l.PushBack(1) l.PushBack(2) if v := l.PopFront(); v != 1 { t.Errorf("EXPECT %v, GOT %v", 1, v) } else { - //fmt.Println(v) + // fmt.Println(v) } if v := l.PopFront(); v != 2 { t.Errorf("EXPECT %v, GOT %v", 2, v) } else { - //fmt.Println(v) + // fmt.Println(v) } if v := l.PopFront(); v != nil { t.Errorf("EXPECT %v, GOT %v", nil, v) } else { - //fmt.Println(v) + // fmt.Println(v) } } @@ -221,13 +221,13 @@ func checkList(t *gtest.T, l *List, es []interface{}) { i++ } - //for e := l.Front(); e != nil; e = e.Next() { + // for e := l.Front(); e != nil; e = e.Next() { // le := e.Value.(int) // if le != es[i] { // t.Errorf("elt[%d].Value() = %v, want %v", i, le, es[i]) // } // i++ - //} + // } } func TestExtending(t *testing.T) { @@ -283,11 +283,11 @@ func TestRemove(t *testing.T) { e1 := l.PushBack(1) e2 := l.PushBack(2) checkListPointers(t, l, []*Element{e1, e2}) - //e := l.Front() - //l.Remove(e) - //checkListPointers(t, l, []*Element{e2}) - //l.Remove(e) - //checkListPointers(t, l, []*Element{e2}) + // e := l.Front() + // l.Remove(e) + // checkListPointers(t, l, []*Element{e2}) + // l.Remove(e) + // checkListPointers(t, l, []*Element{e2}) }) } @@ -322,12 +322,12 @@ func TestIssue6349(t *testing.T) { if e.Value != 1 { t.Errorf("e.value = %d, want 1", e.Value) } - //if e.Next() != nil { + // if e.Next() != nil { // t.Errorf("e.Next() != nil") - //} - //if e.Prev() != nil { + // } + // if e.Prev() != nil { // t.Errorf("e.Prev() != nil") - //} + // } } func TestMove(t *testing.T) { @@ -474,7 +474,7 @@ func TestList_PopBacks(t *testing.T) { i1 := l.PopBacks(2) t.Assert(i1, []interface{}{1, 2}) - l.PushBacks(a2) //4.3,a,c,b,e + l.PushBacks(a2) // 4.3,a,c,b,e i1 = l.PopBacks(3) t.Assert(i1, []interface{}{"e", "b", "c"}) }) diff --git a/container/gmap/gmap_hash_any_any_map.go b/container/gmap/gmap_hash_any_any_map.go index 1d56eb859..a1f4b3230 100644 --- a/container/gmap/gmap_hash_any_any_map.go +++ b/container/gmap/gmap_hash_any_any_map.go @@ -7,14 +7,11 @@ package gmap import ( - "github.com/gogf/gf/v2/internal/json" - - "github.com/gogf/gf/v2/internal/empty" - - "github.com/gogf/gf/v2/util/gconv" - "github.com/gogf/gf/v2/container/gvar" + "github.com/gogf/gf/v2/internal/empty" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/rwmutex" + "github.com/gogf/gf/v2/util/gconv" ) type AnyAnyMap struct { diff --git a/container/gmap/gmap_hash_int_any_map.go b/container/gmap/gmap_hash_int_any_map.go index 4d2986eb8..15a0953e0 100644 --- a/container/gmap/gmap_hash_int_any_map.go +++ b/container/gmap/gmap_hash_int_any_map.go @@ -8,11 +8,9 @@ package gmap import ( - "github.com/gogf/gf/v2/internal/json" - - "github.com/gogf/gf/v2/internal/empty" - "github.com/gogf/gf/v2/container/gvar" + "github.com/gogf/gf/v2/internal/empty" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/rwmutex" "github.com/gogf/gf/v2/util/gconv" ) diff --git a/container/gmap/gmap_hash_int_int_map.go b/container/gmap/gmap_hash_int_int_map.go index e82593db2..36e2f74fb 100644 --- a/container/gmap/gmap_hash_int_int_map.go +++ b/container/gmap/gmap_hash_int_int_map.go @@ -7,12 +7,10 @@ package gmap import ( - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/util/gconv" - "github.com/gogf/gf/v2/internal/empty" - + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/rwmutex" + "github.com/gogf/gf/v2/util/gconv" ) type IntIntMap struct { diff --git a/container/gmap/gmap_hash_int_str_map.go b/container/gmap/gmap_hash_int_str_map.go index 7be2376ca..94a026ef8 100644 --- a/container/gmap/gmap_hash_int_str_map.go +++ b/container/gmap/gmap_hash_int_str_map.go @@ -7,10 +7,8 @@ package gmap import ( - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/internal/empty" - + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/rwmutex" "github.com/gogf/gf/v2/util/gconv" ) diff --git a/container/gmap/gmap_hash_str_any_map.go b/container/gmap/gmap_hash_str_any_map.go index 832fbdd5d..8846a2971 100644 --- a/container/gmap/gmap_hash_str_any_map.go +++ b/container/gmap/gmap_hash_str_any_map.go @@ -8,11 +8,9 @@ package gmap import ( - "github.com/gogf/gf/v2/internal/json" - - "github.com/gogf/gf/v2/internal/empty" - "github.com/gogf/gf/v2/container/gvar" + "github.com/gogf/gf/v2/internal/empty" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/rwmutex" "github.com/gogf/gf/v2/util/gconv" ) diff --git a/container/gmap/gmap_hash_str_int_map.go b/container/gmap/gmap_hash_str_int_map.go index f068940d5..a6c7fc773 100644 --- a/container/gmap/gmap_hash_str_int_map.go +++ b/container/gmap/gmap_hash_str_int_map.go @@ -8,9 +8,8 @@ package gmap import ( - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/internal/empty" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/rwmutex" "github.com/gogf/gf/v2/util/gconv" ) diff --git a/container/gmap/gmap_hash_str_str_map.go b/container/gmap/gmap_hash_str_str_map.go index 3a0900d7b..1ffb2b527 100644 --- a/container/gmap/gmap_hash_str_str_map.go +++ b/container/gmap/gmap_hash_str_str_map.go @@ -8,12 +8,10 @@ package gmap import ( - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/util/gconv" - "github.com/gogf/gf/v2/internal/empty" - + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/rwmutex" + "github.com/gogf/gf/v2/util/gconv" ) type StrStrMap struct { diff --git a/container/gmap/gmap_list_map.go b/container/gmap/gmap_list_map.go index a0f2f1e30..3ef696dfe 100644 --- a/container/gmap/gmap_list_map.go +++ b/container/gmap/gmap_list_map.go @@ -7,15 +7,12 @@ package gmap import ( - "github.com/gogf/gf/v2/internal/json" - - "github.com/gogf/gf/v2/internal/empty" - - "github.com/gogf/gf/v2/util/gconv" - "github.com/gogf/gf/v2/container/glist" "github.com/gogf/gf/v2/container/gvar" + "github.com/gogf/gf/v2/internal/empty" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/rwmutex" + "github.com/gogf/gf/v2/util/gconv" ) type ListMap struct { diff --git a/container/gmap/gmap_tree_map.go b/container/gmap/gmap_tree_map.go index f357355ca..c81caa48a 100644 --- a/container/gmap/gmap_tree_map.go +++ b/container/gmap/gmap_tree_map.go @@ -10,7 +10,7 @@ import ( "github.com/gogf/gf/v2/container/gtree" ) -// Map based on red-black tree, alias of RedBlackTree. +// TreeMap based on red-black tree, alias of RedBlackTree. type TreeMap = gtree.RedBlackTree // NewTreeMap instantiates a tree map with the custom comparator. diff --git a/container/gmap/gmap_z_basic_test.go b/container/gmap/gmap_z_basic_test.go index df3f6788b..55182170f 100644 --- a/container/gmap/gmap_z_basic_test.go +++ b/container/gmap/gmap_z_basic_test.go @@ -7,11 +7,11 @@ package gmap_test import ( - "github.com/gogf/gf/v2/util/gutil" "testing" "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gutil" ) func getValue() interface{} { @@ -163,15 +163,15 @@ func Test_Map_Lock(t *testing.T) { func Test_Map_Clone(t *testing.T) { gtest.C(t, func(t *gtest.T) { - //clone 方法是深克隆 + // clone 方法是深克隆 m := gmap.NewFrom(map[interface{}]interface{}{1: 1, "key1": "val1"}) m_clone := m.Clone() m.Remove(1) - //修改原 map,clone 后的 map 不影响 + // 修改原 map,clone 后的 map 不影响 t.AssertIN(1, m_clone.Keys()) m_clone.Remove("key1") - //修改clone map,原 map 不影响 + // 修改clone map,原 map 不影响 t.AssertIN("key1", m.Keys()) }) } diff --git a/container/gmap/gmap_z_example_any_any_test.go b/container/gmap/gmap_z_example_any_any_test.go index cee0ab69d..d320db84b 100644 --- a/container/gmap/gmap_z_example_any_any_test.go +++ b/container/gmap/gmap_z_example_any_any_test.go @@ -8,9 +8,9 @@ package gmap_test import ( "fmt" - "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/container/gmap" + "github.com/gogf/gf/v2/frame/g" ) func ExampleNew() { diff --git a/container/gmap/gmap_z_unit_any_any_test.go b/container/gmap/gmap_z_unit_hash_any_any_test.go similarity index 98% rename from container/gmap/gmap_z_unit_any_any_test.go rename to container/gmap/gmap_z_unit_hash_any_any_test.go index 0b8ed354c..7de3be37e 100644 --- a/container/gmap/gmap_z_unit_any_any_test.go +++ b/container/gmap/gmap_z_unit_hash_any_any_test.go @@ -7,14 +7,15 @@ package gmap_test import ( + "testing" + "time" + "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gconv" - "testing" - "time" ) func Test_AnyAnyMap_Var(t *testing.T) { @@ -148,16 +149,16 @@ func Test_AnyAnyMap_Lock(t *testing.T) { func Test_AnyAnyMap_Clone(t *testing.T) { gtest.C(t, func(t *gtest.T) { - //clone 方法是深克隆 + // clone 方法是深克隆 m := gmap.NewAnyAnyMapFrom(map[interface{}]interface{}{1: 1, 2: "2"}) m_clone := m.Clone() m.Remove(1) - //修改原 map,clone 后的 map 不影响 + // 修改原 map,clone 后的 map 不影响 t.AssertIN(1, m_clone.Keys()) m_clone.Remove(2) - //修改clone map,原 map 不影响 + // 修改clone map,原 map 不影响 t.AssertIN(2, m.Keys()) }) } diff --git a/container/gmap/gmap_z_unit_int_any_test.go b/container/gmap/gmap_z_unit_hash_int_any_test.go similarity index 98% rename from container/gmap/gmap_z_unit_int_any_test.go rename to container/gmap/gmap_z_unit_hash_int_any_test.go index fb5e72665..13c65d2b3 100644 --- a/container/gmap/gmap_z_unit_int_any_test.go +++ b/container/gmap/gmap_z_unit_hash_int_any_test.go @@ -7,14 +7,14 @@ package gmap_test import ( - "github.com/gogf/gf/v2/container/garray" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/util/gconv" "testing" + "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/container/gmap" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gconv" ) func getAny() interface{} { @@ -150,16 +150,16 @@ func Test_IntAnyMap_Lock(t *testing.T) { } func Test_IntAnyMap_Clone(t *testing.T) { gtest.C(t, func(t *gtest.T) { - //clone 方法是深克隆 + // clone 方法是深克隆 m := gmap.NewIntAnyMapFrom(map[int]interface{}{1: 1, 2: "2"}) m_clone := m.Clone() m.Remove(1) - //修改原 map,clone 后的 map 不影响 + // 修改原 map,clone 后的 map 不影响 t.AssertIN(1, m_clone.Keys()) m_clone.Remove(2) - //修改clone map,原 map 不影响 + // 修改clone map,原 map 不影响 t.AssertIN(2, m.Keys()) }) } diff --git a/container/gmap/gmap_z_unit_int_int_test.go b/container/gmap/gmap_z_unit_hash_int_int_test.go similarity index 98% rename from container/gmap/gmap_z_unit_int_int_test.go rename to container/gmap/gmap_z_unit_hash_int_int_test.go index c2a08bd04..d42c7f86f 100644 --- a/container/gmap/gmap_z_unit_int_int_test.go +++ b/container/gmap/gmap_z_unit_hash_int_int_test.go @@ -7,14 +7,14 @@ package gmap_test import ( - "github.com/gogf/gf/v2/container/garray" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/util/gconv" "testing" + "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/container/gmap" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gconv" ) func getInt() int { @@ -155,16 +155,16 @@ func Test_IntIntMap_Lock(t *testing.T) { func Test_IntIntMap_Clone(t *testing.T) { gtest.C(t, func(t *gtest.T) { - //clone 方法是深克隆 + // clone 方法是深克隆 m := gmap.NewIntIntMapFrom(map[int]int{1: 1, 2: 2}) m_clone := m.Clone() m.Remove(1) - //修改原 map,clone 后的 map 不影响 + // 修改原 map,clone 后的 map 不影响 t.AssertIN(1, m_clone.Keys()) m_clone.Remove(2) - //修改clone map,原 map 不影响 + // 修改clone map,原 map 不影响 t.AssertIN(2, m.Keys()) }) } diff --git a/container/gmap/gmap_z_unit_int_str_test.go b/container/gmap/gmap_z_unit_hash_int_str_test.go similarity index 96% rename from container/gmap/gmap_z_unit_int_str_test.go rename to container/gmap/gmap_z_unit_hash_int_str_test.go index 0d2cddbe1..046e2f466 100644 --- a/container/gmap/gmap_z_unit_int_str_test.go +++ b/container/gmap/gmap_z_unit_hash_int_str_test.go @@ -7,14 +7,14 @@ package gmap_test import ( - "github.com/gogf/gf/v2/container/garray" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/util/gconv" "testing" + "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/container/gmap" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gconv" ) func getStr() string { @@ -76,8 +76,8 @@ func Test_IntStrMap_Basic(t *testing.T) { t.AssertIN("a", m.Values()) t.AssertIN("c", m.Values()) - //反转之后不成为以下 map,flip 操作只是翻转原 map - //t.Assert(m.Map(), map[string]int{"a": 1, "c": 3}) + // 反转之后不成为以下 map,flip 操作只是翻转原 map + // t.Assert(m.Map(), map[string]int{"a": 1, "c": 3}) m_f := gmap.NewIntStrMap() m_f.Set(1, "2") m_f.Flip() @@ -155,16 +155,16 @@ func Test_IntStrMap_Lock(t *testing.T) { func Test_IntStrMap_Clone(t *testing.T) { gtest.C(t, func(t *gtest.T) { - //clone 方法是深克隆 + // clone 方法是深克隆 m := gmap.NewIntStrMapFrom(map[int]string{1: "a", 2: "b", 3: "c"}) m_clone := m.Clone() m.Remove(1) - //修改原 map,clone 后的 map 不影响 + // 修改原 map,clone 后的 map 不影响 t.AssertIN(1, m_clone.Keys()) m_clone.Remove(2) - //修改clone map,原 map 不影响 + // 修改clone map,原 map 不影响 t.AssertIN(2, m.Keys()) }) } diff --git a/container/gmap/gmap_z_unit_str_any_test.go b/container/gmap/gmap_z_unit_hash_str_any_test.go similarity index 98% rename from container/gmap/gmap_z_unit_str_any_test.go rename to container/gmap/gmap_z_unit_hash_str_any_test.go index 0fefa09e0..3dd044478 100644 --- a/container/gmap/gmap_z_unit_str_any_test.go +++ b/container/gmap/gmap_z_unit_hash_str_any_test.go @@ -7,14 +7,14 @@ package gmap_test import ( - "github.com/gogf/gf/v2/container/garray" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/util/gconv" "testing" + "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/container/gmap" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gconv" ) func Test_StrAnyMap_Var(t *testing.T) { @@ -148,16 +148,16 @@ func Test_StrAnyMap_Lock(t *testing.T) { } func Test_StrAnyMap_Clone(t *testing.T) { gtest.C(t, func(t *gtest.T) { - //clone 方法是深克隆 + // clone 方法是深克隆 m := gmap.NewStrAnyMapFrom(map[string]interface{}{"a": 1, "b": "2"}) m_clone := m.Clone() m.Remove("a") - //修改原 map,clone 后的 map 不影响 + // 修改原 map,clone 后的 map 不影响 t.AssertIN("a", m_clone.Keys()) m_clone.Remove("b") - //修改clone map,原 map 不影响 + // 修改clone map,原 map 不影响 t.AssertIN("b", m.Keys()) }) } diff --git a/container/gmap/gmap_z_unit_str_int_test.go b/container/gmap/gmap_z_unit_hash_str_int_test.go similarity index 98% rename from container/gmap/gmap_z_unit_str_int_test.go rename to container/gmap/gmap_z_unit_hash_str_int_test.go index 30cc8e470..431e4fa13 100644 --- a/container/gmap/gmap_z_unit_str_int_test.go +++ b/container/gmap/gmap_z_unit_hash_str_int_test.go @@ -7,14 +7,14 @@ package gmap_test import ( - "github.com/gogf/gf/v2/container/garray" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/util/gconv" "testing" + "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/container/gmap" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gconv" ) func Test_StrIntMap_Var(t *testing.T) { @@ -152,16 +152,16 @@ func Test_StrIntMap_Lock(t *testing.T) { func Test_StrIntMap_Clone(t *testing.T) { gtest.C(t, func(t *gtest.T) { - //clone 方法是深克隆 + // clone 方法是深克隆 m := gmap.NewStrIntMapFrom(map[string]int{"a": 1, "b": 2, "c": 3}) m_clone := m.Clone() m.Remove("a") - //修改原 map,clone 后的 map 不影响 + // 修改原 map,clone 后的 map 不影响 t.AssertIN("a", m_clone.Keys()) m_clone.Remove("b") - //修改clone map,原 map 不影响 + // 修改clone map,原 map 不影响 t.AssertIN("b", m.Keys()) }) } diff --git a/container/gmap/gmap_z_unit_str_str_test.go b/container/gmap/gmap_z_unit_hash_str_str_test.go similarity index 98% rename from container/gmap/gmap_z_unit_str_str_test.go rename to container/gmap/gmap_z_unit_hash_str_str_test.go index f7f9ef823..2cfe9b4aa 100644 --- a/container/gmap/gmap_z_unit_str_str_test.go +++ b/container/gmap/gmap_z_unit_hash_str_str_test.go @@ -7,14 +7,14 @@ package gmap_test import ( - "github.com/gogf/gf/v2/container/garray" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/util/gconv" "testing" + "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/container/gmap" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gconv" ) func Test_StrStrMap_Var(t *testing.T) { @@ -149,16 +149,16 @@ func Test_StrStrMap_Lock(t *testing.T) { } func Test_StrStrMap_Clone(t *testing.T) { gtest.C(t, func(t *gtest.T) { - //clone 方法是深克隆 + // clone 方法是深克隆 m := gmap.NewStrStrMapFrom(map[string]string{"a": "a", "b": "b", "c": "c"}) m_clone := m.Clone() m.Remove("a") - //修改原 map,clone 后的 map 不影响 + // 修改原 map,clone 后的 map 不影响 t.AssertIN("a", m_clone.Keys()) m_clone.Remove("b") - //修改clone map,原 map 不影响 + // 修改clone map,原 map 不影响 t.AssertIN("b", m.Keys()) }) } diff --git a/container/gmap/gmap_z_unit_list_map_test.go b/container/gmap/gmap_z_unit_list_map_test.go index a0dc8c7f2..433dd48d0 100644 --- a/container/gmap/gmap_z_unit_list_map_test.go +++ b/container/gmap/gmap_z_unit_list_map_test.go @@ -7,14 +7,14 @@ package gmap_test import ( - "github.com/gogf/gf/v2/container/garray" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/util/gconv" "testing" + "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gconv" ) func Test_ListMap_Var(t *testing.T) { @@ -133,15 +133,15 @@ func Test_ListMap_Iterator(t *testing.T) { func Test_ListMap_Clone(t *testing.T) { gtest.C(t, func(t *gtest.T) { - //clone 方法是深克隆 + // clone 方法是深克隆 m := gmap.NewListMapFrom(map[interface{}]interface{}{1: 1, "key1": "val1"}) m_clone := m.Clone() m.Remove(1) - //修改原 map,clone 后的 map 不影响 + // 修改原 map,clone 后的 map 不影响 t.AssertIN(1, m_clone.Keys()) m_clone.Remove("key1") - //修改clone map,原 map 不影响 + // 修改clone map,原 map 不影响 t.AssertIN("key1", m.Keys()) }) } diff --git a/container/gmap/gmap_z_unit_tree_map_test.go b/container/gmap/gmap_z_unit_tree_map_test.go index f3320f574..b541d127d 100644 --- a/container/gmap/gmap_z_unit_tree_map_test.go +++ b/container/gmap/gmap_z_unit_tree_map_test.go @@ -7,13 +7,13 @@ package gmap_test import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/util/gconv" "testing" "github.com/gogf/gf/v2/container/gmap" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/gutil" ) @@ -152,15 +152,15 @@ func Test_TreeMap_Iterator(t *testing.T) { func Test_TreeMap_Clone(t *testing.T) { gtest.C(t, func(t *gtest.T) { - //clone 方法是深克隆 + // clone 方法是深克隆 m := gmap.NewTreeMapFrom(gutil.ComparatorString, map[interface{}]interface{}{1: 1, "key1": "val1"}) m_clone := m.Clone() m.Remove(1) - //修改原 map,clone 后的 map 不影响 + // 修改原 map,clone 后的 map 不影响 t.AssertIN(1, m_clone.Keys()) m_clone.Remove("key1") - //修改clone map,原 map 不影响 + // 修改clone map,原 map 不影响 t.AssertIN("key1", m.Keys()) }) } diff --git a/container/gpool/gpool.go b/container/gpool/gpool.go index 9ee4f80ba..12baececf 100644 --- a/container/gpool/gpool.go +++ b/container/gpool/gpool.go @@ -9,12 +9,12 @@ package gpool import ( "context" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" "time" "github.com/gogf/gf/v2/container/glist" "github.com/gogf/gf/v2/container/gtype" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/os/gtimer" ) @@ -38,10 +38,10 @@ type poolItem struct { expireAt int64 // Expire timestamp in milliseconds. } -// Creation function for object. +// NewFunc Creation function for object. type NewFunc func() (interface{}, error) -// Destruction function for object. +// ExpireFunc Destruction function for object. type ExpireFunc func(interface{}) // New creates and returns a new object pool. diff --git a/container/gpool/gpool_z_unit_test.go b/container/gpool/gpool_z_unit_test.go index 6ddf91beb..759bc9dce 100644 --- a/container/gpool/gpool_z_unit_test.go +++ b/container/gpool/gpool_z_unit_test.go @@ -11,9 +11,8 @@ import ( "testing" "time" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/container/gpool" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/test/gtest" ) @@ -30,29 +29,29 @@ var ef gpool.ExpireFunc = func(i interface{}) { func Test_Gpool(t *testing.T) { gtest.C(t, func(t *gtest.T) { // - //expire = 0 + // expire = 0 p1 := gpool.New(0, nf) p1.Put(1) p1.Put(2) time.Sleep(1 * time.Second) - //test won't be timeout + // test won't be timeout v1, err1 := p1.Get() t.Assert(err1, nil) t.AssertIN(v1, g.Slice{1, 2}) - //test clear + // test clear p1.Clear() t.Assert(p1.Size(), 0) - //test newFunc + // test newFunc v1, err1 = p1.Get() t.Assert(err1, nil) t.Assert(v1, "hello") - //put data again + // put data again p1.Put(3) p1.Put(4) v1, err1 = p1.Get() t.Assert(err1, nil) t.AssertIN(v1, g.Slice{3, 4}) - //test close + // test close p1.Close() v1, err1 = p1.Get() t.Assert(err1, nil) @@ -61,7 +60,7 @@ func Test_Gpool(t *testing.T) { gtest.C(t, func(t *gtest.T) { // - //expire > 0 + // expire > 0 p2 := gpool.New(2*time.Second, nil, ef) for index := 0; index < 10; index++ { p2.Put(index) @@ -70,12 +69,12 @@ func Test_Gpool(t *testing.T) { v2, err2 := p2.Get() t.Assert(err2, nil) t.Assert(v2, 0) - //test timeout expireFunc + // test timeout expireFunc time.Sleep(3 * time.Second) v2, err2 = p2.Get() t.Assert(err2, errors.New("pool is empty")) t.Assert(v2, nil) - //test close expireFunc + // test close expireFunc for index := 0; index < 10; index++ { p2.Put(index) } @@ -90,7 +89,7 @@ func Test_Gpool(t *testing.T) { gtest.C(t, func(t *gtest.T) { // - //expire < 0 + // expire < 0 p3 := gpool.New(-1, nil) v3, err3 := p3.Get() t.Assert(err3, errors.New("pool is empty")) diff --git a/container/gqueue/gqueue.go b/container/gqueue/gqueue.go index de2a06504..a778709b3 100644 --- a/container/gqueue/gqueue.go +++ b/container/gqueue/gqueue.go @@ -59,7 +59,7 @@ func New(limit ...int) *Queue { } // asyncLoopFromListToChannel starts an asynchronous goroutine, -// which handles the data synchronization from list to channel . +// which handles the data synchronization from list `q.list` to channel `q.C`. func (q *Queue) asyncLoopFromListToChannel() { defer func() { if q.closed.Val() { @@ -87,13 +87,13 @@ func (q *Queue) asyncLoopFromListToChannel() { <-q.events } } - // It should be here to close q.C if `q` is unlimited size. + // It should be here to close `q.C` if `q` is unlimited size. // It's the sender's responsibility to close channel when it should be closed. close(q.C) } // Push pushes the data `v` into the queue. -// Note that it would panics if Push is called after the queue is closed. +// Note that it would panic if Push is called after the queue is closed. func (q *Queue) Push(v interface{}) { if q.limit > 0 { q.C <- v @@ -121,14 +121,15 @@ func (q *Queue) Close() { } if q.limit > 0 { close(q.C) - } - for i := 0; i < defaultBatchSize; i++ { - q.Pop() + } else { + for i := 0; i < defaultBatchSize; i++ { + q.Pop() + } } } // Len returns the length of the queue. -// Note that the result might not be accurate as there's a +// Note that the result might not be accurate as there's an // asynchronous channel reading the list constantly. func (q *Queue) Len() (length int) { if q.list != nil { diff --git a/container/gqueue/gqueue_z_example_test.go b/container/gqueue/gqueue_z_example_test.go new file mode 100644 index 000000000..f76e5c2e5 --- /dev/null +++ b/container/gqueue/gqueue_z_example_test.go @@ -0,0 +1,133 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +package gqueue_test + +import ( + "context" + "fmt" + "time" + + "github.com/gogf/gf/v2/container/gqueue" + "github.com/gogf/gf/v2/os/gtimer" +) + +func ExampleNew() { + n := 10 + q := gqueue.New() + + // Producer + for i := 0; i < n; i++ { + q.Push(i) + } + + // Close the queue in three seconds. + gtimer.SetTimeout(context.Background(), time.Second*3, func(ctx context.Context) { + q.Close() + }) + + // The consumer constantly reads the queue data. + // If there is no data in the queue, it will block. + // The queue is read using the queue.C property exposed + // by the queue object and the selectIO multiplexing syntax + // example: + // for { + // select { + // case v := <-queue.C: + // if v != nil { + // fmt.Println(v) + // } else { + // return + // } + // } + // } + for { + if v := q.Pop(); v != nil { + fmt.Print(v) + } else { + break + } + } + + // Output: + // 0123456789 +} + +func ExampleQueue_Push() { + q := gqueue.New() + + for i := 0; i < 10; i++ { + q.Push(i) + } + + fmt.Println(q.Pop()) + fmt.Println(q.Pop()) + fmt.Println(q.Pop()) + + // Output: + // 0 + // 1 + // 2 +} + +func ExampleQueue_Pop() { + q := gqueue.New() + + for i := 0; i < 10; i++ { + q.Push(i) + } + + fmt.Println(q.Pop()) + q.Close() + fmt.Println(q.Pop()) + + // Output: + // 0 + // +} + +func ExampleQueue_Close() { + q := gqueue.New() + + for i := 0; i < 10; i++ { + q.Push(i) + } + + time.Sleep(time.Millisecond) + q.Close() + + fmt.Println(q.Len()) + fmt.Println(q.Pop()) + + // Output: + // 0 + // +} + +func ExampleQueue_Len() { + q := gqueue.New() + + q.Push(1) + q.Push(2) + + fmt.Println(q.Len()) + + // May Output: + // 2 +} + +func ExampleQueue_Size() { + q := gqueue.New() + + q.Push(1) + q.Push(2) + + // Size is alias of Len. + fmt.Println(q.Size()) + + // May Output: + // 2 +} diff --git a/container/gring/gring.go b/container/gring/gring.go index 08fddc982..08c4e51ab 100644 --- a/container/gring/gring.go +++ b/container/gring/gring.go @@ -193,17 +193,17 @@ func (r *Ring) RLockIteratorNext(f func(value interface{}) bool) { } } -// LockIteratorPrev iterates and locks writing backward +// RLockIteratorPrev 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. -func (r *Ring) LockIteratorPrev(f func(item *ring.Ring) bool) { +func (r *Ring) RLockIteratorPrev(f func(value interface{}) bool) { r.mu.RLock() defer r.mu.RUnlock() - if !f(r.ring) { + if r.ring.Value != nil && !f(r.ring.Value.(internalRingItem).Value) { return } for p := r.ring.Prev(); p != r.ring; p = p.Prev() { - if !f(p) { + if p.Value == nil || !f(p.Value.(internalRingItem).Value) { break } } diff --git a/container/gring/gring_bench_test.go b/container/gring/gring_z_bench_test.go similarity index 100% rename from container/gring/gring_bench_test.go rename to container/gring/gring_z_bench_test.go diff --git a/container/gring/gring_z_example_test.go b/container/gring/gring_z_example_test.go new file mode 100644 index 000000000..6b7032f9e --- /dev/null +++ b/container/gring/gring_z_example_test.go @@ -0,0 +1,289 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +package gring_test + +import ( + "fmt" + "github.com/gogf/gf/v2/container/gring" +) + +func ExampleNew() { + // Non concurrent safety + gring.New(10) + + // Concurrent safety + gring.New(10, true) + + // Output: +} + +func ExampleRing_Val() { + r := gring.New(10) + r.Set(1) + fmt.Println("Val:", r.Val()) + + r.Next().Set("GoFrame") + fmt.Println("Val:", r.Val()) + + // Output: + // Val: 1 + // Val: GoFrame +} + +func ExampleRing_Len() { + r1 := gring.New(10) + for i := 0; i < 5; i++ { + r1.Set(i).Next() + } + fmt.Println("Len:", r1.Len()) + + r2 := gring.New(10, true) + for i := 0; i < 10; i++ { + r2.Set(i).Next() + } + fmt.Println("Len:", r2.Len()) + + // Output: + // Len: 5 + // Len: 10 +} + +func ExampleRing_Cap() { + r1 := gring.New(10) + for i := 0; i < 5; i++ { + r1.Set(i).Next() + } + fmt.Println("Cap:", r1.Cap()) + + r2 := gring.New(10, true) + for i := 0; i < 10; i++ { + r2.Set(i).Next() + } + fmt.Println("Cap:", r2.Cap()) + + // Output: + // Cap: 10 + // Cap: 10 +} + +func ExampleRing_Set() { + r := gring.New(10) + r.Set(1) + fmt.Println("Val:", r.Val()) + + r.Next().Set("GoFrame") + fmt.Println("Val:", r.Val()) + + // Output: + // Val: 1 + // Val: GoFrame +} + +func ExampleRing_Put() { + r := gring.New(10) + r.Put(1) + fmt.Println("Val:", r.Val()) + fmt.Println("Val:", r.Prev().Val()) + + // Output: + // Val: + // Val: 1 +} + +func ExampleRing_Move() { + r := gring.New(10) + for i := 0; i < 10; i++ { + r.Set(i).Next() + } + // ring at Pos 0 + fmt.Println("CurVal:", r.Val()) + + r.Move(5) + + // ring at Pos 5 + fmt.Println("CurVal:", r.Val()) + + // Output: + // CurVal: 0 + // CurVal: 5 +} + +func ExampleRing_Prev() { + r := gring.New(10) + for i := 0; i < 5; i++ { + r.Set(i).Next() + } + + fmt.Println("Prev:", r.Prev().Val()) + fmt.Println("Prev:", r.Prev().Val()) + + // Output: + // Prev: 4 + // Prev: 3 +} + +func ExampleRing_Next() { + r := gring.New(10) + for i := 5; i > 0; i-- { + r.Set(i).Prev() + } + + fmt.Println("Prev:", r.Next().Val()) + fmt.Println("Prev:", r.Next().Val()) + + // Output: + // Prev: 1 + // Prev: 2 +} + +func ExampleRing_Link_Common() { + r := gring.New(10) + for i := 0; i < 5; i++ { + r.Set(i).Next() + } + + s := gring.New(10) + for i := 0; i < 10; i++ { + val := i + 5 + s.Set(val).Next() + } + + r.Link(s) // Link Ring s to Ring r + + fmt.Println("Len:", r.Len()) + fmt.Println("Cap:", r.Cap()) + fmt.Println(r.SlicePrev()) + fmt.Println(r.SliceNext()) + + // Output: + // Len: 15 + // Cap: 20 + // [4 3 2 1 0] + // [5 6 7 8 9 10 11 12 13 14] +} + +func ExampleRing_Link_SameRing() { + r := gring.New(10) + for i := 0; i < 5; i++ { + r.Set(i).Next() + } + + same_r := r.Link(r.Prev()) + + fmt.Println("Len:", same_r.Len()) + fmt.Println("Cap:", same_r.Cap()) + fmt.Println(same_r.SlicePrev()) + fmt.Println(same_r.SliceNext()) + + // Output: + // Len: 1 + // Cap: 1 + // [4] + // [4] +} + +func ExampleRing_Unlink() { + r := gring.New(10) + for i := 0; i < 10; i++ { + r.Set(i).Next() + } + + fmt.Println("Before Unlink, Len:", r.Len()) + fmt.Println("Before Unlink, Cap:", r.Cap()) + fmt.Println("Before Unlink, ", r.SlicePrev()) + fmt.Println("Before Unlink, ", r.SliceNext()) + + r.Unlink(7) + + fmt.Println("After Unlink, Len:", r.Len()) + fmt.Println("After Unlink, Cap:", r.Cap()) + fmt.Println("After Unlink, ", r.SlicePrev()) + fmt.Println("After Unlink, ", r.SliceNext()) + + // Output: + // Before Unlink, Len: 10 + // Before Unlink, Cap: 10 + // Before Unlink, [0 9 8 7 6 5 4 3 2 1] + // Before Unlink, [0 1 2 3 4 5 6 7 8 9] + // After Unlink, Len: 7 + // After Unlink, Cap: 7 + // After Unlink, [1 7 6 5 4 3 2] + // After Unlink, [1 2 3 4 5 6 7] +} + +func ExampleRing_RLockIteratorNext() { + r := gring.New(10) + for i := 0; i < 10; i++ { + r.Set(i).Next() + } + + r.RLockIteratorNext(func(value interface{}) bool { + if value.(int) < 5 { + fmt.Println("IteratorNext Success, Value:", value) + return true + } + + return false + }) + + // Output: + // IteratorNext Success, Value: 0 + // IteratorNext Success, Value: 1 + // IteratorNext Success, Value: 2 + // IteratorNext Success, Value: 3 + // IteratorNext Success, Value: 4 +} + +func ExampleRing_RLockIteratorPrev() { + r := gring.New(10) + for i := 0; i < 10; i++ { + r.Set(i).Next() + } + + // move r to pos 9 + r.Prev() + + r.RLockIteratorPrev(func(value interface{}) bool { + if value.(int) >= 5 { + fmt.Println("IteratorPrev Success, Value:", value) + return true + } + + return false + }) + + // Output: + // IteratorPrev Success, Value: 9 + // IteratorPrev Success, Value: 8 + // IteratorPrev Success, Value: 7 + // IteratorPrev Success, Value: 6 + // IteratorPrev Success, Value: 5 +} + +func ExampleRing_SliceNext() { + r := gring.New(10) + for i := 0; i < 10; i++ { + r.Set(i).Next() + } + + fmt.Println(r.SliceNext()) + + // Output: + // [0 1 2 3 4 5 6 7 8 9] +} + +func ExampleRing_SlicePrev() { + r := gring.New(10) + for i := 0; i < 10; i++ { + r.Set(i).Next() + } + + fmt.Println(r.SlicePrev()) + + // Output: + // [0 9 8 7 6 5 4 3 2 1] +} diff --git a/container/gring/gring_unit_test.go b/container/gring/gring_z_unit_test.go similarity index 100% rename from container/gring/gring_unit_test.go rename to container/gring/gring_z_unit_test.go diff --git a/container/gset/gset_any_set.go b/container/gset/gset_any_set.go index c91b4fd6e..9ab7da1ad 100644 --- a/container/gset/gset_any_set.go +++ b/container/gset/gset_any_set.go @@ -9,6 +9,7 @@ package gset import ( "bytes" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/rwmutex" "github.com/gogf/gf/v2/text/gstr" @@ -97,7 +98,7 @@ func (set *Set) AddIfNotExist(item interface{}) bool { } // AddIfNotExistFunc checks whether item exists in the set, -// it adds the item to set and returns true if it does not exists in the set and +// it adds the item to set and returns true if it does not exist in the set and // function `f` returns true, or else it does nothing and returns false. // // Note that, if `item` is nil, it does nothing and returns false. The function `f` diff --git a/container/gset/gset_int_set.go b/container/gset/gset_int_set.go index 3c6320a95..efc75bbff 100644 --- a/container/gset/gset_int_set.go +++ b/container/gset/gset_int_set.go @@ -9,6 +9,7 @@ package gset import ( "bytes" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/rwmutex" "github.com/gogf/gf/v2/util/gconv" diff --git a/container/gset/gset_str_set.go b/container/gset/gset_str_set.go index a7f43e773..42c57fd07 100644 --- a/container/gset/gset_str_set.go +++ b/container/gset/gset_str_set.go @@ -9,11 +9,12 @@ package gset import ( "bytes" + "strings" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/rwmutex" "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" - "strings" ) type StrSet struct { diff --git a/container/gset/gset_z_example_any_test.go b/container/gset/gset_z_example_any_test.go index 70a41f582..383ca07ac 100644 --- a/container/gset/gset_z_example_any_test.go +++ b/container/gset/gset_z_example_any_test.go @@ -8,6 +8,7 @@ package gset_test import ( "fmt" + "github.com/gogf/gf/v2/container/gset" "github.com/gogf/gf/v2/frame/g" ) diff --git a/container/gset/gset_z_example_int_test.go b/container/gset/gset_z_example_int_test.go index 761e3552f..589b34a21 100644 --- a/container/gset/gset_z_example_int_test.go +++ b/container/gset/gset_z_example_int_test.go @@ -7,17 +7,402 @@ package gset_test import ( + "encoding/json" "fmt" + "github.com/gogf/gf/v2/container/gset" + "github.com/gogf/gf/v2/frame/g" ) +// New create and returns a new set, which contains un-repeated items. +// The parameter `safe` is used to specify whether using set in concurrent-safety, +// which is false in default. +func ExampleNewIntSet() { + intSet := gset.NewIntSet() + intSet.Add([]int{1, 2, 3}...) + fmt.Println(intSet.Slice()) + + // May Output: + // [2 1 3] +} + +// NewIntSetFrom returns a new set from `items`. +func ExampleNewFrom() { + intSet := gset.NewIntSetFrom([]int{1, 2, 3}) + fmt.Println(intSet.Slice()) + + // May Output: + // [2 1 3] +} + +// Add adds one or multiple items to the set. +func ExampleIntSet_Add() { + intSet := gset.NewIntSetFrom([]int{1, 2, 3}) + intSet.Add(1) + fmt.Println(intSet.Slice()) + fmt.Println(intSet.AddIfNotExist(1)) + + // Mya Output: + // [1 2 3] + // false +} + +// AddIfNotExist checks whether item exists in the set, +// it adds the item to set and returns true if it does not exists in the set, +// or else it does nothing and returns false. +func ExampleIntSet_AddIfNotExist() { + intSet := gset.NewIntSetFrom([]int{1, 2, 3}) + intSet.Add(1) + fmt.Println(intSet.Slice()) + fmt.Println(intSet.AddIfNotExist(1)) + + // Mya Output: + // [1 2 3] + // false +} + +// AddIfNotExistFunc checks whether item exists in the set, +// it adds the item to set and returns true if it does not exists in the set and function `f` returns true, +// or else it does nothing and returns false. +// Note that, the function `f` is executed without writing lock. +func ExampleIntSet_AddIfNotExistFunc() { + intSet := gset.NewIntSetFrom([]int{1, 2, 3}) + intSet.Add(1) + fmt.Println(intSet.Slice()) + fmt.Println(intSet.AddIfNotExistFunc(5, func() bool { + return true + })) + + // May Output: + // [1 2 3] + // true +} + +// AddIfNotExistFunc checks whether item exists in the set, +// it adds the item to set and returns true if it does not exists in the set and function `f` returns true, +// or else it does nothing and returns false. +// Note that, the function `f` is executed without writing lock. +func ExampleIntSet_AddIfNotExistFuncLock() { + intSet := gset.NewIntSetFrom([]int{1, 2, 3}) + intSet.Add(1) + fmt.Println(intSet.Slice()) + fmt.Println(intSet.AddIfNotExistFuncLock(4, func() bool { + return true + })) + + // May Output: + // [1 2 3] + // true +} + +// Clear deletes all items of the set. +func ExampleIntSet_Clear() { + intSet := gset.NewIntSetFrom([]int{1, 2, 3}) + fmt.Println(intSet.Size()) + intSet.Clear() + fmt.Println(intSet.Size()) + + // Output: + // 3 + // 0 +} + +// Complement returns a new set which is the complement from `set` to `full`. +// Which means, all the items in `newSet` are in `full` and not in `set`. +// It returns the difference between `full` and `set` if the given set `full` is not the full set of `set`. +func ExampleIntSet_Complement() { + intSet := gset.NewIntSetFrom([]int{1, 2, 3, 4, 5}) + s := gset.NewIntSetFrom([]int{1, 2, 3}) + fmt.Println(s.Complement(intSet).Slice()) + + // May Output: + // [4 5] +} + +// Contains checks whether the set contains `item`. func ExampleIntSet_Contains() { - var set gset.IntSet - set.Add(1) - fmt.Println(set.Contains(1)) - fmt.Println(set.Contains(2)) + var set1 gset.IntSet + set1.Add(1, 4, 5, 6, 7) + fmt.Println(set1.Contains(1)) + + var set2 gset.IntSet + set2.Add(1, 4, 5, 6, 7) + fmt.Println(set2.Contains(8)) // Output: // true // false } + +// Diff returns a new set which is the difference set from `set` to `other`. +// Which means, all the items in `newSet` are in `set` but not in `other`. +func ExampleIntSet_Diff() { + s1 := gset.NewIntSetFrom([]int{1, 2, 3}) + s2 := gset.NewIntSetFrom([]int{1, 2, 3, 4}) + fmt.Println(s2.Diff(s1).Slice()) + + // Output: + // [4] +} + +// Equal checks whether the two sets equal. +func ExampleIntSet_Equal() { + s1 := gset.NewIntSetFrom([]int{1, 2, 3}) + s2 := gset.NewIntSetFrom([]int{1, 2, 3, 4}) + fmt.Println(s2.Equal(s1)) + + s3 := gset.NewIntSetFrom([]int{1, 2, 3}) + s4 := gset.NewIntSetFrom([]int{1, 2, 3}) + fmt.Println(s3.Equal(s4)) + + // Output: + // false + // true +} + +// Intersect returns a new set which is the intersection from `set` to `other`. +// Which means, all the items in `newSet` are in `set` and also in `other`. +func ExampleIntSet_Intersect() { + s1 := gset.NewIntSet() + s1.Add([]int{1, 2, 3}...) + var s2 gset.IntSet + s2.Add([]int{1, 2, 3, 4}...) + fmt.Println(s2.Intersect(s1).Slice()) + + // May Output: + // [1 2 3] +} + +// IsSubsetOf checks whether the current set is a sub-set of `other` +func ExampleIntSet_IsSubsetOf() { + s1 := gset.NewIntSet() + s1.Add([]int{1, 2, 3, 4}...) + var s2 gset.IntSet + s2.Add([]int{1, 2, 4}...) + fmt.Println(s2.IsSubsetOf(s1)) + + // Output: + // true +} + +// Iterator iterates the set readonly with given callback function `f`, +// if `f` returns true then continue iterating; or false to stop. +func ExampleIntSet_Iterator() { + s1 := gset.NewIntSet() + s1.Add([]int{1, 2, 3, 4}...) + s1.Iterator(func(v int) bool { + fmt.Println("Iterator", v) + return true + }) + // May Output: + // Iterator 2 + // Iterator 3 + // Iterator 1 + // Iterator 4 +} + +// Join joins items with a string `glue`. +func ExampleIntSet_Join() { + s1 := gset.NewIntSet() + s1.Add([]int{1, 2, 3, 4}...) + fmt.Println(s1.Join(",")) + + // May Output: + // 3,4,1,2 +} + +// LockFunc locks writing with callback function `f`. +func ExampleIntSet_LockFunc() { + s1 := gset.NewIntSet() + s1.Add([]int{1, 2}...) + s1.LockFunc(func(m map[int]struct{}) { + m[3] = struct{}{} + }) + fmt.Println(s1.Slice()) + + // May Output + // [2 3 1] +} + +// MarshalJSON implements the interface MarshalJSON for json.Marshal. +func ExampleIntSet_MarshalJSON() { + type Student struct { + Id int + Name string + Scores *gset.IntSet + } + s := Student{ + Id: 1, + Name: "john", + Scores: gset.NewIntSetFrom([]int{100, 99, 98}), + } + b, _ := json.Marshal(s) + fmt.Println(string(b)) + + // May Output: + // {"Id":1,"Name":"john","Scores":[100,99,98]} +} + +// Merge adds items from `others` sets into `set`. +func ExampleIntSet_Merge() { + s1 := gset.NewIntSet() + s1.Add([]int{1, 2, 3, 4}...) + + s2 := gset.NewIntSet() + fmt.Println(s1.Merge(s2).Slice()) + + // May Output: + // [1 2 3 4] +} + +// Pops randomly pops an item from set. +func ExampleIntSet_Pop() { + s1 := gset.NewIntSet() + s1.Add([]int{1, 2, 3, 4}...) + + fmt.Println(s1.Pop()) + + // May Output: + // 1 +} + +// Pops randomly pops `size` items from set. +// It returns all items if size == -1. +func ExampleIntSet_Pops() { + s1 := gset.NewIntSet() + s1.Add([]int{1, 2, 3, 4}...) + for _, v := range s1.Pops(2) { + fmt.Println(v) + } + + // May Output: + // 1 + // 2 +} + +// RLockFunc locks reading with callback function `f`. +func ExampleIntSet_RLockFunc() { + s1 := gset.NewIntSet() + s1.Add([]int{1, 2, 3, 4}...) + s1.RLockFunc(func(m map[int]struct{}) { + fmt.Println(m) + }) + + // Output: + // map[1:{} 2:{} 3:{} 4:{}] +} + +// Remove deletes `item` from set. +func ExampleIntSet_Remove() { + s1 := gset.NewIntSet() + s1.Add([]int{1, 2, 3, 4}...) + s1.Remove(1) + fmt.Println(s1.Slice()) + + // May Output: + // [3 4 2] +} + +// Size returns the size of the set. +func ExampleIntSet_Size() { + s1 := gset.NewIntSet() + s1.Add([]int{1, 2, 3, 4}...) + fmt.Println(s1.Size()) + + // Output: + // 4 +} + +// Slice returns the a of items of the set as slice. +func ExampleIntSet_Slice() { + s1 := gset.NewIntSet() + s1.Add([]int{1, 2, 3, 4}...) + fmt.Println(s1.Slice()) + + // May Output: + // [1, 2, 3, 4] +} + +// String returns items as a string, which implements like json.Marshal does. +func ExampleIntSet_String() { + s1 := gset.NewIntSet() + s1.Add([]int{1, 2, 3, 4}...) + fmt.Println(s1.String()) + + // May Output: + // [1,2,3,4] +} + +// Sum sums items. Note: The items should be converted to int type, +// or you'd get a result that you unexpected. +func ExampleIntSet_Sum() { + s1 := gset.NewIntSet() + s1.Add([]int{1, 2, 3, 4}...) + fmt.Println(s1.Sum()) + + // Output: + // 10 +} + +// Union returns a new set which is the union of `set` and `other`. +// Which means, all the items in `newSet` are in `set` or in `other`. +func ExampleIntSet_Union() { + s1 := gset.NewIntSet() + s1.Add([]int{1, 2, 3, 4}...) + s2 := gset.NewIntSet() + s2.Add([]int{1, 2, 4}...) + fmt.Println(s1.Union(s2).Slice()) + + // May Output: + // [3 4 1 2] +} + +// UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal. +func ExampleIntSet_UnmarshalJSON() { + b := []byte(`{"Id":1,"Name":"john","Scores":[100,99,98]}`) + type Student struct { + Id int + Name string + Scores *gset.IntSet + } + s := Student{} + json.Unmarshal(b, &s) + fmt.Println(s) + + // May Output: + // {1 john [100,99,98]} +} + +// UnmarshalValue is an interface implement which sets any type of value for set. +func ExampleIntSet_UnmarshalValue() { + b := []byte(`{"Id":1,"Name":"john","Scores":100,99,98}`) + type Student struct { + Id int + Name string + Scores *gset.IntSet + } + s := Student{} + json.Unmarshal(b, &s) + fmt.Println(s) + + // May Output: + // {1 john [100,99,98]} +} + +// Walk applies a user supplied function `f` to every item of set. +func ExampleIntSet_Walk() { + var ( + set gset.IntSet + names = g.SliceInt{1, 0} + delta = 10 + ) + set.Add(names...) + // Add prefix for given table names. + set.Walk(func(item int) int { + return delta + item + }) + fmt.Println(set.Slice()) + + // May Output: + // [12 60] +} diff --git a/container/gset/gset_z_example_str_test.go b/container/gset/gset_z_example_str_test.go index 586e55615..b81df2f04 100644 --- a/container/gset/gset_z_example_str_test.go +++ b/container/gset/gset_z_example_str_test.go @@ -9,6 +9,7 @@ package gset_test import ( "encoding/json" "fmt" + "github.com/gogf/gf/v2/container/gset" "github.com/gogf/gf/v2/frame/g" ) diff --git a/container/gset/gset_z_unit_any_test.go b/container/gset/gset_z_unit_any_test.go index 5dec2a315..be0c56383 100644 --- a/container/gset/gset_z_unit_any_test.go +++ b/container/gset/gset_z_unit_any_test.go @@ -9,18 +9,17 @@ package gset_test import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/util/gconv" "strings" "sync" + "testing" "time" "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/container/gset" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" - - "testing" + "github.com/gogf/gf/v2/util/gconv" ) func TestSet_Var(t *testing.T) { diff --git a/container/gset/gset_z_unit_int_test.go b/container/gset/gset_z_unit_int_test.go index c9dda0968..5f7068c75 100644 --- a/container/gset/gset_z_unit_int_test.go +++ b/container/gset/gset_z_unit_int_test.go @@ -9,9 +9,6 @@ package gset_test import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/util/gconv" "strings" "sync" "testing" @@ -19,7 +16,10 @@ import ( "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/container/gset" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gconv" ) func TestIntSet_Var(t *testing.T) { diff --git a/container/gset/gset_z_unit_str_test.go b/container/gset/gset_z_unit_str_test.go index f9042d2d1..eae7cd15a 100644 --- a/container/gset/gset_z_unit_str_test.go +++ b/container/gset/gset_z_unit_str_test.go @@ -9,9 +9,6 @@ package gset_test import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/util/gconv" "strings" "sync" "testing" @@ -19,7 +16,10 @@ import ( "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/container/gset" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gconv" ) func TestStrSet_Var(t *testing.T) { diff --git a/container/gtree/gtree_avltree.go b/container/gtree/gtree_avltree.go index bec0198a3..589353d2d 100644 --- a/container/gtree/gtree_avltree.go +++ b/container/gtree/gtree_avltree.go @@ -8,12 +8,11 @@ package gtree import ( "fmt" - "github.com/gogf/gf/v2/internal/json" - - "github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/container/gvar" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/rwmutex" + "github.com/gogf/gf/v2/util/gconv" ) // AVLTree holds elements of the AVL tree. diff --git a/container/gtree/gtree_btree.go b/container/gtree/gtree_btree.go index ffd12c5ca..ec8362639 100644 --- a/container/gtree/gtree_btree.go +++ b/container/gtree/gtree_btree.go @@ -9,13 +9,12 @@ package gtree import ( "bytes" "fmt" - "github.com/gogf/gf/v2/internal/json" "strings" - "github.com/gogf/gf/v2/util/gconv" - "github.com/gogf/gf/v2/container/gvar" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/rwmutex" + "github.com/gogf/gf/v2/util/gconv" ) // BTree holds elements of the B-tree. @@ -587,9 +586,9 @@ func (tree *BTree) isLeaf(node *BTreeNode) bool { return len(node.Children) == 0 } -//func (tree *BTree) isFull(node *BTreeNode) bool { +// func (tree *BTree) isFull(node *BTreeNode) bool { // return len(node.Entries) == tree.maxEntries() -//} +// } func (tree *BTree) shouldSplit(node *BTreeNode) bool { return len(node.Entries) > tree.maxEntries() diff --git a/container/gtree/gtree_redblacktree.go b/container/gtree/gtree_redblacktree.go index 2b917d649..2433648a3 100644 --- a/container/gtree/gtree_redblacktree.go +++ b/container/gtree/gtree_redblacktree.go @@ -8,12 +8,12 @@ package gtree import ( "fmt" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/util/gconv" - "github.com/gogf/gf/v2/util/gutil" "github.com/gogf/gf/v2/container/gvar" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/rwmutex" + "github.com/gogf/gf/v2/util/gconv" + "github.com/gogf/gf/v2/util/gutil" ) type color bool @@ -119,7 +119,7 @@ func (tree *RedBlackTree) doSet(key interface{}, value interface{}) { compare := tree.getComparator()(key, node.Key) switch { case compare == 0: - //node.Key = key + // node.Key = key node.Value = value return case compare < 0: diff --git a/container/gtype/gtype_bool.go b/container/gtype/gtype_bool.go index 87b36a271..d1b00e3dd 100644 --- a/container/gtype/gtype_bool.go +++ b/container/gtype/gtype_bool.go @@ -8,8 +8,9 @@ package gtype import ( "bytes" - "github.com/gogf/gf/v2/util/gconv" "sync/atomic" + + "github.com/gogf/gf/v2/util/gconv" ) // Bool is a struct for concurrent-safe operation for type bool. @@ -80,9 +81,8 @@ func (v *Bool) String() string { func (v *Bool) MarshalJSON() ([]byte, error) { if v.Val() { return bytesTrue, nil - } else { - return bytesFalse, nil } + return bytesFalse, nil } // UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal. diff --git a/container/gtype/gtype_byte.go b/container/gtype/gtype_byte.go index 06403ec6e..5a8ffb385 100644 --- a/container/gtype/gtype_byte.go +++ b/container/gtype/gtype_byte.go @@ -7,9 +7,10 @@ package gtype import ( - "github.com/gogf/gf/v2/util/gconv" "strconv" "sync/atomic" + + "github.com/gogf/gf/v2/util/gconv" ) // Byte is a struct for concurrent-safe operation for type byte. diff --git a/container/gtype/gtype_bytes.go b/container/gtype/gtype_bytes.go index 22d7253b7..8a6834a0c 100644 --- a/container/gtype/gtype_bytes.go +++ b/container/gtype/gtype_bytes.go @@ -9,8 +9,9 @@ package gtype import ( "bytes" "encoding/base64" - "github.com/gogf/gf/v2/util/gconv" "sync/atomic" + + "github.com/gogf/gf/v2/util/gconv" ) // Bytes is a struct for concurrent-safe operation for type []byte. diff --git a/container/gtype/gtype_float32.go b/container/gtype/gtype_float32.go index 1ec36a574..fc096c8d7 100644 --- a/container/gtype/gtype_float32.go +++ b/container/gtype/gtype_float32.go @@ -7,10 +7,11 @@ package gtype import ( - "github.com/gogf/gf/v2/util/gconv" "math" "strconv" "sync/atomic" + + "github.com/gogf/gf/v2/util/gconv" ) // Float32 is a struct for concurrent-safe operation for type float32. diff --git a/container/gtype/gtype_float64.go b/container/gtype/gtype_float64.go index 8b6440af4..fd5a2e99e 100644 --- a/container/gtype/gtype_float64.go +++ b/container/gtype/gtype_float64.go @@ -7,10 +7,11 @@ package gtype import ( - "github.com/gogf/gf/v2/util/gconv" "math" "strconv" "sync/atomic" + + "github.com/gogf/gf/v2/util/gconv" ) // Float64 is a struct for concurrent-safe operation for type float64. diff --git a/container/gtype/gtype_int.go b/container/gtype/gtype_int.go index bee2bf629..9e6dbeaa6 100644 --- a/container/gtype/gtype_int.go +++ b/container/gtype/gtype_int.go @@ -7,9 +7,10 @@ package gtype import ( - "github.com/gogf/gf/v2/util/gconv" "strconv" "sync/atomic" + + "github.com/gogf/gf/v2/util/gconv" ) // Int is a struct for concurrent-safe operation for type int. diff --git a/container/gtype/gtype_int32.go b/container/gtype/gtype_int32.go index f554832f8..849f3dcd8 100644 --- a/container/gtype/gtype_int32.go +++ b/container/gtype/gtype_int32.go @@ -7,9 +7,10 @@ package gtype import ( - "github.com/gogf/gf/v2/util/gconv" "strconv" "sync/atomic" + + "github.com/gogf/gf/v2/util/gconv" ) // Int32 is a struct for concurrent-safe operation for type int32. diff --git a/container/gtype/gtype_int64.go b/container/gtype/gtype_int64.go index dbdbf21da..3bf12afef 100644 --- a/container/gtype/gtype_int64.go +++ b/container/gtype/gtype_int64.go @@ -7,9 +7,10 @@ package gtype import ( - "github.com/gogf/gf/v2/util/gconv" "strconv" "sync/atomic" + + "github.com/gogf/gf/v2/util/gconv" ) // Int64 is a struct for concurrent-safe operation for type int64. diff --git a/container/gtype/gtype_interface.go b/container/gtype/gtype_interface.go index 23633b4c0..455608dfc 100644 --- a/container/gtype/gtype_interface.go +++ b/container/gtype/gtype_interface.go @@ -7,9 +7,10 @@ package gtype import ( + "sync/atomic" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/util/gconv" - "sync/atomic" ) // Interface is a struct for concurrent-safe operation for type interface{}. diff --git a/container/gtype/gtype_uint.go b/container/gtype/gtype_uint.go index 2bff0da7a..e9dada149 100644 --- a/container/gtype/gtype_uint.go +++ b/container/gtype/gtype_uint.go @@ -7,9 +7,10 @@ package gtype import ( - "github.com/gogf/gf/v2/util/gconv" "strconv" "sync/atomic" + + "github.com/gogf/gf/v2/util/gconv" ) // Uint is a struct for concurrent-safe operation for type uint. diff --git a/container/gtype/gtype_uint32.go b/container/gtype/gtype_uint32.go index 86bd10b75..1e52377e3 100644 --- a/container/gtype/gtype_uint32.go +++ b/container/gtype/gtype_uint32.go @@ -7,9 +7,10 @@ package gtype import ( - "github.com/gogf/gf/v2/util/gconv" "strconv" "sync/atomic" + + "github.com/gogf/gf/v2/util/gconv" ) // Uint32 is a struct for concurrent-safe operation for type uint32. diff --git a/container/gtype/gtype_uint64.go b/container/gtype/gtype_uint64.go index 3eebc7268..f7cda75bb 100644 --- a/container/gtype/gtype_uint64.go +++ b/container/gtype/gtype_uint64.go @@ -7,9 +7,10 @@ package gtype import ( - "github.com/gogf/gf/v2/util/gconv" "strconv" "sync/atomic" + + "github.com/gogf/gf/v2/util/gconv" ) // Uint64 is a struct for concurrent-safe operation for type uint64. diff --git a/container/gtype/gtype_z_bench_basic_test.go b/container/gtype/gtype_z_bench_basic_test.go index 6ddc96424..26f13bd0a 100644 --- a/container/gtype/gtype_z_bench_basic_test.go +++ b/container/gtype/gtype_z_bench_basic_test.go @@ -9,11 +9,11 @@ package gtype_test import ( - "github.com/gogf/gf/v2/container/gtype" "strconv" "sync/atomic" "testing" + "github.com/gogf/gf/v2/container/gtype" "github.com/gogf/gf/v2/encoding/gbinary" ) diff --git a/container/gtype/gtype_z_bench_json_test.go b/container/gtype/gtype_z_bench_json_test.go index f434987c3..42cd4dc5b 100644 --- a/container/gtype/gtype_z_bench_json_test.go +++ b/container/gtype/gtype_z_bench_json_test.go @@ -9,9 +9,10 @@ package gtype_test import ( + "testing" + "github.com/gogf/gf/v2/container/gtype" "github.com/gogf/gf/v2/internal/json" - "testing" ) var ( diff --git a/container/gtype/gtype_z_unit_bool_test.go b/container/gtype/gtype_z_unit_bool_test.go index fc214c521..47c31c387 100644 --- a/container/gtype/gtype_z_unit_bool_test.go +++ b/container/gtype/gtype_z_unit_bool_test.go @@ -7,12 +7,12 @@ package gtype_test import ( - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/util/gconv" "testing" "github.com/gogf/gf/v2/container/gtype" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gconv" ) func Test_Bool(t *testing.T) { @@ -27,7 +27,7 @@ func Test_Bool(t *testing.T) { t.AssertEQ(iClone1.Set(true), false) t.AssertEQ(iClone1.Val(), true) - //空参测试 + // 空参测试 i2 := gtype.NewBool() t.AssertEQ(i2.Val(), false) }) diff --git a/container/gtype/gtype_z_unit_byte_test.go b/container/gtype/gtype_z_unit_byte_test.go index bbfa8a461..b035ff0a1 100644 --- a/container/gtype/gtype_z_unit_byte_test.go +++ b/container/gtype/gtype_z_unit_byte_test.go @@ -7,13 +7,13 @@ package gtype_test import ( - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/util/gconv" "sync" "testing" "github.com/gogf/gf/v2/container/gtype" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gconv" ) func Test_Byte(t *testing.T) { @@ -34,7 +34,7 @@ func Test_Byte(t *testing.T) { wg.Wait() t.AssertEQ(byte(addTimes), i.Val()) - //空参测试 + // 空参测试 i1 := gtype.NewByte() t.AssertEQ(i1.Val(), byte(0)) }) diff --git a/container/gtype/gtype_z_unit_bytes_test.go b/container/gtype/gtype_z_unit_bytes_test.go index 938078817..f6da7ab13 100644 --- a/container/gtype/gtype_z_unit_bytes_test.go +++ b/container/gtype/gtype_z_unit_bytes_test.go @@ -7,12 +7,12 @@ package gtype_test import ( - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/util/gconv" "testing" "github.com/gogf/gf/v2/container/gtype" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gconv" ) func Test_Bytes(t *testing.T) { diff --git a/container/gtype/gtype_z_unit_float32_test.go b/container/gtype/gtype_z_unit_float32_test.go index 4a8bddaf9..c0a081a6e 100644 --- a/container/gtype/gtype_z_unit_float32_test.go +++ b/container/gtype/gtype_z_unit_float32_test.go @@ -7,12 +7,13 @@ package gtype_test import ( + "math" + "testing" + "github.com/gogf/gf/v2/container/gtype" "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gconv" - "math" - "testing" ) func Test_Float32(t *testing.T) { @@ -22,7 +23,7 @@ func Test_Float32(t *testing.T) { t.AssertEQ(iClone.Set(0.1), float32(0)) t.AssertEQ(iClone.Val(), float32(0.1)) - //空参测试 + // 空参测试 i1 := gtype.NewFloat32() t.AssertEQ(i1.Val(), float32(0)) }) diff --git a/container/gtype/gtype_z_unit_float64_test.go b/container/gtype/gtype_z_unit_float64_test.go index 8089ba8f5..b5bf088f8 100644 --- a/container/gtype/gtype_z_unit_float64_test.go +++ b/container/gtype/gtype_z_unit_float64_test.go @@ -7,12 +7,13 @@ package gtype_test import ( + "math" + "testing" + "github.com/gogf/gf/v2/container/gtype" "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gconv" - "math" - "testing" ) func Test_Float64(t *testing.T) { @@ -21,7 +22,7 @@ func Test_Float64(t *testing.T) { iClone := i.Clone() t.AssertEQ(iClone.Set(0.1), float64(0)) t.AssertEQ(iClone.Val(), float64(0.1)) - //空参测试 + // 空参测试 i1 := gtype.NewFloat64() t.AssertEQ(i1.Val(), float64(0)) }) diff --git a/container/gtype/gtype_z_unit_int32_test.go b/container/gtype/gtype_z_unit_int32_test.go index c1fc9cfb8..3a13c5801 100644 --- a/container/gtype/gtype_z_unit_int32_test.go +++ b/container/gtype/gtype_z_unit_int32_test.go @@ -7,13 +7,14 @@ package gtype_test import ( + "math" + "sync" + "testing" + "github.com/gogf/gf/v2/container/gtype" "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gconv" - "math" - "sync" - "testing" ) func Test_Int32(t *testing.T) { @@ -34,7 +35,7 @@ func Test_Int32(t *testing.T) { wg.Wait() t.AssertEQ(int32(addTimes), i.Val()) - //空参测试 + // 空参测试 i1 := gtype.NewInt32() t.AssertEQ(i1.Val(), int32(0)) }) diff --git a/container/gtype/gtype_z_unit_int64_test.go b/container/gtype/gtype_z_unit_int64_test.go index e1da0f139..1c3966b5d 100644 --- a/container/gtype/gtype_z_unit_int64_test.go +++ b/container/gtype/gtype_z_unit_int64_test.go @@ -7,13 +7,14 @@ package gtype_test import ( + "math" + "sync" + "testing" + "github.com/gogf/gf/v2/container/gtype" "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gconv" - "math" - "sync" - "testing" ) func Test_Int64(t *testing.T) { @@ -34,7 +35,7 @@ func Test_Int64(t *testing.T) { wg.Wait() t.AssertEQ(int64(addTimes), i.Val()) - //空参测试 + // 空参测试 i1 := gtype.NewInt64() t.AssertEQ(i1.Val(), int64(0)) }) diff --git a/container/gtype/gtype_z_unit_int_test.go b/container/gtype/gtype_z_unit_int_test.go index 3d0d73fea..30c31d9f0 100644 --- a/container/gtype/gtype_z_unit_int_test.go +++ b/container/gtype/gtype_z_unit_int_test.go @@ -7,12 +7,13 @@ package gtype_test import ( + "sync" + "testing" + "github.com/gogf/gf/v2/container/gtype" "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gconv" - "sync" - "testing" ) func Test_Int(t *testing.T) { @@ -33,7 +34,7 @@ func Test_Int(t *testing.T) { wg.Wait() t.AssertEQ(addTimes, i.Val()) - //空参测试 + // 空参测试 i1 := gtype.NewInt() t.AssertEQ(i1.Val(), 0) }) diff --git a/container/gtype/gtype_z_unit_interface_test.go b/container/gtype/gtype_z_unit_interface_test.go index 710b6fa2f..c65a92601 100644 --- a/container/gtype/gtype_z_unit_interface_test.go +++ b/container/gtype/gtype_z_unit_interface_test.go @@ -7,11 +7,12 @@ package gtype_test import ( + "testing" + "github.com/gogf/gf/v2/container/gtype" "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gconv" - "testing" ) func Test_Interface(t *testing.T) { @@ -23,7 +24,7 @@ func Test_Interface(t *testing.T) { t.AssertEQ(iClone.Set(t2), t1) t.AssertEQ(iClone.Val().(Temp), t2) - //空参测试 + // 空参测试 i1 := gtype.New() t.AssertEQ(i1.Val(), nil) }) diff --git a/container/gtype/gtype_z_unit_string_test.go b/container/gtype/gtype_z_unit_string_test.go index 83bdcd968..c43830126 100644 --- a/container/gtype/gtype_z_unit_string_test.go +++ b/container/gtype/gtype_z_unit_string_test.go @@ -7,11 +7,12 @@ package gtype_test import ( + "testing" + "github.com/gogf/gf/v2/container/gtype" "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gconv" - "testing" ) func Test_String(t *testing.T) { @@ -21,7 +22,7 @@ func Test_String(t *testing.T) { t.AssertEQ(iClone.Set("123"), "abc") t.AssertEQ(iClone.Val(), "123") - //空参测试 + // 空参测试 i1 := gtype.NewString() t.AssertEQ(i1.Val(), "") }) diff --git a/container/gtype/gtype_z_unit_uint32_test.go b/container/gtype/gtype_z_unit_uint32_test.go index 2254358fa..3b0a75005 100644 --- a/container/gtype/gtype_z_unit_uint32_test.go +++ b/container/gtype/gtype_z_unit_uint32_test.go @@ -7,13 +7,14 @@ package gtype_test import ( + "math" + "sync" + "testing" + "github.com/gogf/gf/v2/container/gtype" "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gconv" - "math" - "sync" - "testing" ) func Test_Uint32(t *testing.T) { @@ -34,7 +35,7 @@ func Test_Uint32(t *testing.T) { wg.Wait() t.AssertEQ(uint32(addTimes), i.Val()) - //空参测试 + // 空参测试 i1 := gtype.NewUint32() t.AssertEQ(i1.Val(), uint32(0)) }) diff --git a/container/gtype/gtype_z_unit_uint64_test.go b/container/gtype/gtype_z_unit_uint64_test.go index 5435cc30e..f2285aa3d 100644 --- a/container/gtype/gtype_z_unit_uint64_test.go +++ b/container/gtype/gtype_z_unit_uint64_test.go @@ -7,14 +7,14 @@ package gtype_test import ( - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/util/gconv" "math" "sync" "testing" "github.com/gogf/gf/v2/container/gtype" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gconv" ) type Temp struct { @@ -40,7 +40,7 @@ func Test_Uint64(t *testing.T) { wg.Wait() t.AssertEQ(uint64(addTimes), i.Val()) - //空参测试 + // 空参测试 i1 := gtype.NewUint64() t.AssertEQ(i1.Val(), uint64(0)) }) diff --git a/container/gtype/gtype_z_unit_uint_test.go b/container/gtype/gtype_z_unit_uint_test.go index 34e798e2b..4521e6d6f 100644 --- a/container/gtype/gtype_z_unit_uint_test.go +++ b/container/gtype/gtype_z_unit_uint_test.go @@ -7,12 +7,13 @@ package gtype_test import ( + "sync" + "testing" + "github.com/gogf/gf/v2/container/gtype" "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gconv" - "sync" - "testing" ) func Test_Uint(t *testing.T) { @@ -33,7 +34,7 @@ func Test_Uint(t *testing.T) { wg.Wait() t.AssertEQ(uint(addTimes), i.Val()) - //空参测试 + // 空参测试 i1 := gtype.NewUint() t.AssertEQ(i1.Val(), uint(0)) }) diff --git a/container/gvar/gvar.go b/container/gvar/gvar.go index a5412d464..745919fb9 100644 --- a/container/gvar/gvar.go +++ b/container/gvar/gvar.go @@ -8,10 +8,10 @@ package gvar import ( - "github.com/gogf/gf/v2/internal/json" "time" "github.com/gogf/gf/v2/container/gtype" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/util/gconv" ) diff --git a/container/gvar/gvar_z_unit_basic_test.go b/container/gvar/gvar_z_unit_basic_test.go index ab8845e75..92c2fbd20 100644 --- a/container/gvar/gvar_z_unit_basic_test.go +++ b/container/gvar/gvar_z_unit_basic_test.go @@ -9,12 +9,12 @@ package gvar_test import ( "bytes" "encoding/binary" - "github.com/gogf/gf/v2/util/gconv" "testing" "time" "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gconv" ) func Test_Set(t *testing.T) { diff --git a/container/gvar/gvar_z_unit_is_test.go b/container/gvar/gvar_z_unit_is_test.go index 28d3168bc..c1b9daae7 100644 --- a/container/gvar/gvar_z_unit_is_test.go +++ b/container/gvar/gvar_z_unit_is_test.go @@ -7,9 +7,10 @@ package gvar_test import ( + "testing" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/test/gtest" - "testing" ) func TestVar_IsNil(t *testing.T) { diff --git a/container/gvar/gvar_z_unit_json_test.go b/container/gvar/gvar_z_unit_json_test.go index e52abe090..d5df2f8ef 100644 --- a/container/gvar/gvar_z_unit_json_test.go +++ b/container/gvar/gvar_z_unit_json_test.go @@ -7,11 +7,12 @@ package gvar_test import ( + "math" + "testing" + "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" - "math" - "testing" ) func TestVar_Json(t *testing.T) { diff --git a/container/gvar/gvar_z_unit_list_test.go b/container/gvar/gvar_z_unit_list_test.go index 9e024bd43..ecb648e96 100644 --- a/container/gvar/gvar_z_unit_list_test.go +++ b/container/gvar/gvar_z_unit_list_test.go @@ -7,10 +7,11 @@ package gvar_test import ( + "testing" + "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/test/gtest" - "testing" ) func TestVar_ListItemValues_Map(t *testing.T) { diff --git a/container/gvar/gvar_z_unit_map_test.go b/container/gvar/gvar_z_unit_map_test.go index 0498bc008..30eab6f66 100644 --- a/container/gvar/gvar_z_unit_map_test.go +++ b/container/gvar/gvar_z_unit_map_test.go @@ -7,10 +7,11 @@ package gvar_test import ( + "testing" + "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/test/gtest" - "testing" ) func TestVar_Map(t *testing.T) { diff --git a/container/gvar/gvar_z_unit_slice_test.go b/container/gvar/gvar_z_unit_slice_test.go index 66a319786..874bdfd38 100644 --- a/container/gvar/gvar_z_unit_slice_test.go +++ b/container/gvar/gvar_z_unit_slice_test.go @@ -7,9 +7,10 @@ package gvar_test import ( + "testing" + "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/test/gtest" - "testing" ) func TestVar_Ints(t *testing.T) { diff --git a/container/gvar/gvar_z_unit_struct_test.go b/container/gvar/gvar_z_unit_struct_test.go index 1102c4e05..f397acadb 100644 --- a/container/gvar/gvar_z_unit_struct_test.go +++ b/container/gvar/gvar_z_unit_struct_test.go @@ -7,11 +7,12 @@ package gvar_test import ( + "testing" + "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gconv" - "testing" ) func TestVar_Struct(t *testing.T) { diff --git a/crypto/gaes/gaes.go b/crypto/gaes/gaes.go index 21a04dcd4..cc86966ae 100644 --- a/crypto/gaes/gaes.go +++ b/crypto/gaes/gaes.go @@ -11,6 +11,7 @@ import ( "bytes" "crypto/aes" "crypto/cipher" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" ) diff --git a/crypto/gaes/gaes_test.go b/crypto/gaes/gaes_z_unit_test.go similarity index 99% rename from crypto/gaes/gaes_test.go rename to crypto/gaes/gaes_z_unit_test.go index d930fddb4..75ca55b3c 100644 --- a/crypto/gaes/gaes_test.go +++ b/crypto/gaes/gaes_z_unit_test.go @@ -11,9 +11,8 @@ package gaes_test import ( "testing" - "github.com/gogf/gf/v2/encoding/gbase64" - "github.com/gogf/gf/v2/crypto/gaes" + "github.com/gogf/gf/v2/encoding/gbase64" "github.com/gogf/gf/v2/test/gtest" ) diff --git a/crypto/gcrc32/gcrc32_test.go b/crypto/gcrc32/gcrc32_z_unit_test.go similarity index 100% rename from crypto/gcrc32/gcrc32_test.go rename to crypto/gcrc32/gcrc32_z_unit_test.go diff --git a/crypto/gdes/gdes.go b/crypto/gdes/gdes.go index e8d7676c7..684cb9b8e 100644 --- a/crypto/gdes/gdes.go +++ b/crypto/gdes/gdes.go @@ -11,6 +11,7 @@ import ( "bytes" "crypto/cipher" "crypto/des" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" ) diff --git a/crypto/gdes/gdes_test.go b/crypto/gdes/gdes_z_unit_test.go similarity index 100% rename from crypto/gdes/gdes_test.go rename to crypto/gdes/gdes_z_unit_test.go diff --git a/crypto/gmd5/gmd5_test.go b/crypto/gmd5/gmd5_z_unit_test.go similarity index 100% rename from crypto/gmd5/gmd5_test.go rename to crypto/gmd5/gmd5_z_unit_test.go diff --git a/crypto/gsha1/gsha1_test.go b/crypto/gsha1/gsha1_z_unit_test.go similarity index 100% rename from crypto/gsha1/gsha1_test.go rename to crypto/gsha1/gsha1_z_unit_test.go diff --git a/database/gdb/gdb.go b/database/gdb/gdb.go index 64ec50b23..be855644b 100644 --- a/database/gdb/gdb.go +++ b/database/gdb/gdb.go @@ -10,20 +10,17 @@ package gdb import ( "context" "database/sql" - "github.com/gogf/gf/v2/errors/gcode" "time" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/os/gcmd" - - "github.com/gogf/gf/v2/container/gvar" - "github.com/gogf/gf/v2/internal/intlog" - - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/container/gtype" + "github.com/gogf/gf/v2/container/gvar" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/os/gcache" + "github.com/gogf/gf/v2/os/gcmd" + "github.com/gogf/gf/v2/os/glog" "github.com/gogf/gf/v2/util/grand" ) @@ -304,7 +301,7 @@ var ( // in the field name as it conflicts with "db.table.field" pattern in SOME situations. regularFieldNameWithoutDotRegPattern = `^[\w\-]+$` - // tableFieldsMap caches the table information retrived from database. + // tableFieldsMap caches the table information retrieved from database. tableFieldsMap = gmap.New(true) // allDryRun sets dry-run feature for all database connections. @@ -432,7 +429,7 @@ func getConfigNodeByGroup(group string, master bool) (*ConfigNode, error) { // Calculation algorithm brief: // 1. If we have 2 nodes, and their weights are both 1, then the weight range is [0, 199]; // 2. Node1 weight range is [0, 99], and node2 weight range is [100, 199], ratio is 1:1; -// 3. If the random number is 99, it then chooses and returns node1; +// 3. If the random number is 99, it then chooses and returns node1;. func getConfigNodeByWeight(cg ConfigGroup) *ConfigNode { if len(cg) < 2 { return &cg[0] @@ -455,7 +452,7 @@ func getConfigNodeByWeight(cg ConfigGroup) *ConfigNode { max := 0 for i := 0; i < len(cg); i++ { max = min + cg[i].Weight*100 - //fmt.Printf("r: %d, min: %d, max: %d\n", r, min, max) + // fmt.Printf("r: %d, min: %d, max: %d\n", r, min, max) if r >= min && r < max { return &cg[i] } else { diff --git a/database/gdb/gdb_core.go b/database/gdb/gdb_core.go index 88b8d55a1..c4c495f00 100644 --- a/database/gdb/gdb_core.go +++ b/database/gdb/gdb_core.go @@ -11,17 +11,16 @@ import ( "context" "database/sql" "fmt" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/internal/intlog" "reflect" "strings" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/internal/utils" - "github.com/gogf/gf/v2/text/gstr" - "github.com/gogf/gf/v2/container/gvar" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/intlog" + "github.com/gogf/gf/v2/internal/utils" "github.com/gogf/gf/v2/text/gregex" + "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" ) @@ -394,7 +393,7 @@ func (c *Core) DoInsert(ctx context.Context, link Link, table string, list List, onDuplicateStr string // onDuplicateStr is used in "ON DUPLICATE KEY UPDATE" statement. ) // Handle the field names and placeholders. - for k, _ := range list[0] { + for k := range list[0] { keys = append(keys, k) } // Prepare the batch result pointer. @@ -449,9 +448,7 @@ func (c *Core) DoInsert(ctx context.Context, link Link, table string, list List, } func (c *Core) formatOnDuplicate(columns []string, option DoInsertOption) string { - var ( - onDuplicateStr string - ) + var onDuplicateStr string if option.OnDuplicateStr != "" { onDuplicateStr = option.OnDuplicateStr } else if len(option.OnDuplicateMap) > 0 { @@ -506,7 +503,7 @@ func (c *Core) formatOnDuplicate(columns []string, option DoInsertOption) string // "money>? AND name like ?", 99999, "vip_%" // "status IN (?)", g.Slice{1,2,3} // "age IN(?,?)", 18, 50 -// User{ Id : 1, UserName : "john"} +// User{ Id : 1, UserName : "john"}. func (c *Core) Update(ctx context.Context, table string, data interface{}, condition interface{}, args ...interface{}) (sql.Result, error) { return c.Model(table).Ctx(ctx).Data(data).Where(condition, args...).Update() } @@ -597,7 +594,7 @@ func (c *Core) DoUpdate(ctx context.Context, link Link, table string, data inter // "money>? AND name like ?", 99999, "vip_%" // "status IN (?)", g.Slice{1,2,3} // "age IN(?,?)", 18, 50 -// User{ Id : 1, UserName : "john"} +// User{ Id : 1, UserName : "john"}. func (c *Core) Delete(ctx context.Context, table string, condition interface{}, args ...interface{}) (result sql.Result, err error) { return c.Model(table).Ctx(ctx).Where(condition, args...).Delete() } diff --git a/database/gdb/gdb_core_config.go b/database/gdb/gdb_core_config.go index e4a4d2e27..c08e5bb4a 100644 --- a/database/gdb/gdb_core_config.go +++ b/database/gdb/gdb_core_config.go @@ -8,11 +8,11 @@ package gdb import ( "fmt" - "github.com/gogf/gf/v2/os/glog" "sync" "time" "github.com/gogf/gf/v2/os/gcache" + "github.com/gogf/gf/v2/os/glog" ) // Config is the configuration management object. diff --git a/database/gdb/gdb_core_structure.go b/database/gdb/gdb_core_structure.go index 6df0cd5a6..ebed7daa8 100644 --- a/database/gdb/gdb_core_structure.go +++ b/database/gdb/gdb_core_structure.go @@ -10,16 +10,12 @@ import ( "strings" "time" - "github.com/gogf/gf/v2/util/gutil" - - "github.com/gogf/gf/v2/text/gstr" - - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/encoding/gbinary" - + "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/text/gregex" + "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" + "github.com/gogf/gf/v2/util/gutil" ) // convertFieldValueToLocalValue automatically checks and converts field value from database type @@ -153,7 +149,7 @@ func (c *Core) convertFieldValueToLocalValue(fieldValue interface{}, fieldType s func (c *Core) mappingAndFilterData(schema, table string, data map[string]interface{}, filter bool) (map[string]interface{}, error) { if fieldsMap, err := c.db.TableFields(c.GetCtx(), c.guessPrimaryTableName(table), schema); err == nil { fieldsKeyMap := make(map[string]interface{}, len(fieldsMap)) - for k, _ := range fieldsMap { + for k := range fieldsMap { fieldsKeyMap[k] = nil } // Automatic data key to table field name mapping. @@ -170,7 +166,7 @@ func (c *Core) mappingAndFilterData(schema, table string, data map[string]interf // Data filtering. // It deletes all key-value pairs that has incorrect field name. if filter { - for dataKey, _ := range data { + for dataKey := range data { if _, ok := fieldsMap[dataKey]; !ok { delete(data, dataKey) } diff --git a/database/gdb/gdb_core_tracing.go b/database/gdb/gdb_core_tracing.go index 0cd86a973..74f818161 100644 --- a/database/gdb/gdb_core_tracing.go +++ b/database/gdb/gdb_core_tracing.go @@ -10,12 +10,14 @@ package gdb import ( "context" "fmt" - "github.com/gogf/gf/v2" - "github.com/gogf/gf/v2/net/gtrace" + "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/trace" + + "github.com/gogf/gf/v2" + "github.com/gogf/gf/v2/net/gtrace" ) const ( diff --git a/database/gdb/gdb_core_transaction.go b/database/gdb/gdb_core_transaction.go index d0c5cf613..755803585 100644 --- a/database/gdb/gdb_core_transaction.go +++ b/database/gdb/gdb_core_transaction.go @@ -9,17 +9,16 @@ package gdb import ( "context" "database/sql" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/internal/utils" "reflect" "github.com/gogf/gf/v2/container/gtype" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/utils" "github.com/gogf/gf/v2/os/gtime" + "github.com/gogf/gf/v2/text/gregex" "github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/guid" - - "github.com/gogf/gf/v2/text/gregex" ) // TX is the struct for transaction management. @@ -39,9 +38,7 @@ const ( transactionIdForLoggerCtx = "TransactionId" ) -var ( - transactionIdGenerator = gtype.NewUint64() -) +var transactionIdGenerator = gtype.NewUint64() // Begin starts and returns the transaction object. // You should call Commit or Rollback functions of the transaction object @@ -100,9 +97,7 @@ func (c *Core) doBeginCtx(ctx context.Context) (*TX, error) { // Note that, you should not Commit or Rollback the transaction in function `f` // as it is automatically handled by this function. func (c *Core) Transaction(ctx context.Context, f func(ctx context.Context, tx *TX) error) (err error) { - var ( - tx *TX - ) + var tx *TX if ctx == nil { ctx = c.GetCtx() } @@ -538,7 +533,7 @@ func (tx *TX) Save(table string, data interface{}, batch ...int) (sql.Result, er // "money>? AND name like ?", 99999, "vip_%" // "status IN (?)", g.Slice{1,2,3} // "age IN(?,?)", 18, 50 -// User{ Id : 1, UserName : "john"} +// User{ Id : 1, UserName : "john"}. func (tx *TX) Update(table string, data interface{}, condition interface{}, args ...interface{}) (sql.Result, error) { return tx.Model(table).Ctx(tx.ctx).Data(data).Where(condition, args...).Update() } @@ -553,7 +548,7 @@ func (tx *TX) Update(table string, data interface{}, condition interface{}, args // "money>? AND name like ?", 99999, "vip_%" // "status IN (?)", g.Slice{1,2,3} // "age IN(?,?)", 18, 50 -// User{ Id : 1, UserName : "john"} +// User{ Id : 1, UserName : "john"}. func (tx *TX) Delete(table string, condition interface{}, args ...interface{}) (sql.Result, error) { return tx.Model(table).Ctx(tx.ctx).Where(condition, args...).Delete() } diff --git a/database/gdb/gdb_core_underlying.go b/database/gdb/gdb_core_underlying.go index 218e7e477..15035b4cc 100644 --- a/database/gdb/gdb_core_underlying.go +++ b/database/gdb/gdb_core_underlying.go @@ -10,9 +10,9 @@ package gdb import ( "context" "database/sql" + "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/internal/intlog" - "github.com/gogf/gf/v2/os/gtime" ) @@ -128,9 +128,7 @@ func (c *Core) DoExec(ctx context.Context, link Link, sql string, args ...interf result = new(SqlResult) } mTime2 := gtime.TimestampMilli() - var ( - rowsAffected int64 - ) + var rowsAffected int64 if err == nil { rowsAffected, err = result.RowsAffected() } diff --git a/database/gdb/gdb_driver_mssql.go b/database/gdb/gdb_driver_mssql.go index a5e8894e9..d55ac4af4 100644 --- a/database/gdb/gdb_driver_mssql.go +++ b/database/gdb/gdb_driver_mssql.go @@ -15,16 +15,14 @@ import ( "context" "database/sql" "fmt" - "github.com/gogf/gf/v2/errors/gcode" "strconv" "strings" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/internal/intlog" - "github.com/gogf/gf/v2/text/gstr" - "github.com/gogf/gf/v2/text/gregex" + "github.com/gogf/gf/v2/text/gstr" ) // DriverMssql is the driver for SQL server database. diff --git a/database/gdb/gdb_driver_mysql.go b/database/gdb/gdb_driver_mysql.go index fc6331fb8..b93c6c2f0 100644 --- a/database/gdb/gdb_driver_mysql.go +++ b/database/gdb/gdb_driver_mysql.go @@ -10,14 +10,15 @@ import ( "context" "database/sql" "fmt" + "net/url" + + _ "github.com/go-sql-driver/mysql" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/text/gregex" "github.com/gogf/gf/v2/text/gstr" - "net/url" - - _ "github.com/go-sql-driver/mysql" ) // DriverMysql is the driver for mysql database. diff --git a/database/gdb/gdb_driver_oracle.go b/database/gdb/gdb_driver_oracle.go index f5b1bb40f..aced866f1 100644 --- a/database/gdb/gdb_driver_oracle.go +++ b/database/gdb/gdb_driver_oracle.go @@ -15,12 +15,12 @@ import ( "context" "database/sql" "fmt" - "github.com/gogf/gf/v2/errors/gcode" "reflect" "strconv" "strings" "time" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/text/gregex" @@ -98,7 +98,7 @@ func (d *DriverOracle) DoCommit(ctx context.Context, link Link, sql string, args if reflect.TypeOf(v).Kind() == reflect.String { valueStr := gconv.String(v) if gregex.IsMatchString(`^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$`, valueStr) { - //args[i] = fmt.Sprintf(`TO_DATE('%s','yyyy-MM-dd HH:MI:SS')`, valueStr) + // args[i] = fmt.Sprintf(`TO_DATE('%s','yyyy-MM-dd HH:MI:SS')`, valueStr) args[i], _ = time.ParseInLocation("2006-01-02 15:04:05", valueStr, time.Local) } } @@ -267,7 +267,7 @@ func (d *DriverOracle) DoInsert(ctx context.Context, link Link, table string, li listLength = len(list) valueHolder = make([]string, 0) ) - for k, _ := range list[0] { + for k := range list[0] { keys = append(keys, k) valueHolder = append(valueHolder, "?") } diff --git a/database/gdb/gdb_driver_pgsql.go b/database/gdb/gdb_driver_pgsql.go index c8b7f0065..ab1e9801e 100644 --- a/database/gdb/gdb_driver_pgsql.go +++ b/database/gdb/gdb_driver_pgsql.go @@ -15,14 +15,13 @@ import ( "context" "database/sql" "fmt" - "github.com/gogf/gf/v2/errors/gcode" "strings" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/intlog" - "github.com/gogf/gf/v2/text/gstr" - "github.com/gogf/gf/v2/text/gregex" + "github.com/gogf/gf/v2/text/gstr" ) // DriverPgsql is the driver for postgresql database. diff --git a/database/gdb/gdb_driver_sqlite.go b/database/gdb/gdb_driver_sqlite.go index 69b418ae9..15851f7f7 100644 --- a/database/gdb/gdb_driver_sqlite.go +++ b/database/gdb/gdb_driver_sqlite.go @@ -14,9 +14,9 @@ import ( "context" "database/sql" "fmt" - "github.com/gogf/gf/v2/errors/gcode" "strings" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/os/gfile" diff --git a/database/gdb/gdb_func.go b/database/gdb/gdb_func.go index d2360309b..8c69f2762 100644 --- a/database/gdb/gdb_func.go +++ b/database/gdb/gdb_func.go @@ -10,25 +10,23 @@ import ( "bytes" "database/sql" "fmt" - "github.com/gogf/gf/v2/errors/gcode" "reflect" "regexp" "strings" "time" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/empty" "github.com/gogf/gf/v2/internal/json" + "github.com/gogf/gf/v2/internal/structs" "github.com/gogf/gf/v2/internal/utils" "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/util/gmeta" - "github.com/gogf/gf/v2/util/gutil" - - "github.com/gogf/gf/v2/internal/structs" - "github.com/gogf/gf/v2/text/gregex" "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" + "github.com/gogf/gf/v2/util/gmeta" + "github.com/gogf/gf/v2/util/gutil" ) // iString is the type assert api for String. @@ -72,6 +70,11 @@ var ( structTagPriority = append([]string{OrmTagForStruct}, gconv.StructTagPriority...) ) +// isForDaoModel checks and returns whether given type is for dao model. +func isForDaoModel(t reflect.Type) bool { + return gstr.HasSuffix(t.String(), modelForDaoSuffix) +} + // getTableNameFromOrmTag retrieves and returns the table name from struct object. func getTableNameFromOrmTag(object interface{}) string { var tableName string @@ -279,7 +282,7 @@ func doQuoteWord(s, charLeft, charRight string) string { // "user u, user_detail ut" => "`user` u,`user_detail` ut" // "user.user u, user.user_detail ut" => "`user`.`user` u,`user`.`user_detail` ut" // "u.id, u.name, u.age" => "`u`.`id`,`u`.`name`,`u`.`age`" -// "u.id asc" => "`u`.`id` asc" +// "u.id asc" => "`u`.`id` asc". func doQuoteString(s, charLeft, charRight string) string { array1 := gstr.SplitAndTrim(s, ",") for k1, v1 := range array1 { @@ -373,7 +376,7 @@ func formatSql(sql string, args []interface{}) (newSql string, newArgs []interfa return handleArguments(sql, args) } -type formatWhereInput struct { +type formatWhereHolderInput struct { Where interface{} Args []interface{} OmitNil bool @@ -383,8 +386,8 @@ type formatWhereInput struct { Prefix string // Field prefix, eg: "user.", "order.". } -// formatWhere formats where statement and its arguments for `Where` and `Having` statements. -func formatWhere(db DB, in formatWhereInput) (newWhere string, newArgs []interface{}) { +// formatWhereHolder formats where statement and its arguments for `Where` and `Having` statements. +func formatWhereHolder(db DB, in formatWhereHolderInput) (newWhere string, newArgs []interface{}) { var ( buffer = bytes.NewBuffer(nil) reflectInfo = utils.OriginValueAndKind(in.Where) @@ -416,7 +419,7 @@ func formatWhere(db DB, in formatWhereInput) (newWhere string, newArgs []interfa case reflect.Struct: // If the `where` parameter is defined like `xxxForDao`, it then adds `OmitNil` option for this condition, // which will filter all nil parameters in `where`. - if gstr.HasSuffix(reflect.TypeOf(in.Where).String(), modelForDaoSuffix) { + if isForDaoModel(reflect.TypeOf(in.Where)) { in.OmitNil = true } // If `where` struct implements iIterator interface, @@ -451,8 +454,8 @@ func formatWhere(db DB, in formatWhereInput) (newWhere string, newArgs []interfa var ( reflectType = reflectInfo.OriginValue.Type() structField reflect.StructField + data = DataToMapDeep(in.Where) ) - data := DataToMapDeep(in.Where) if in.Table != "" { data, _ = db.GetCore().mappingAndFilterData(in.Schema, in.Table, data, true) } @@ -481,9 +484,7 @@ func formatWhere(db DB, in formatWhereInput) (newWhere string, newArgs []interfa default: // Usually a string. - var ( - whereStr = gconv.String(in.Where) - ) + whereStr := gconv.String(in.Where) // Is `whereStr` a field name which composed as a key-value condition? // Eg: // Where("id", 1) @@ -511,18 +512,14 @@ func formatWhere(db DB, in formatWhereInput) (newWhere string, newArgs []interfa // Regular string and parameter place holder handling. // Eg: // Where("id in(?) and name=?", g.Slice{1,2,3}, "john") - var ( - i = 0 - ) + i := 0 for { if i >= len(in.Args) { break } // Sub query, which is always used along with a string condition. if model, ok := in.Args[i].(*Model); ok { - var ( - index = -1 - ) + index := -1 whereStr, _ = gregex.ReplaceStringFunc(`(\?)`, whereStr, func(s string) string { index++ if i+len(newArgs) == index { @@ -607,13 +604,13 @@ func formatWhereInterfaces(db DB, where []interface{}, buffer *bytes.Buffer, new } type formatWhereKeyValueInput struct { - Db DB - Buffer *bytes.Buffer - Args []interface{} - Key string - Value interface{} - OmitEmpty bool - Prefix string // Field prefix, eg: "user.", "order.". + Db DB // Db is the underlying DB object for current operation. + Buffer *bytes.Buffer // Buffer is the sql statement string without Args for current operation. + Args []interface{} // Args is the full arguments of current operation. + Key string // The field name, eg: "id", "name", etc. + Value interface{} // The field value, can be any types. + OmitEmpty bool // Ignores current condition key if `value` is empty. + Prefix string // Field prefix, eg: "user", "order", etc. } // formatWhereKeyValue handles each key-value pair of the parameter map. @@ -833,9 +830,7 @@ func FormatSqlWithArgs(sql string, args []interface{}) string { if v, ok := args[index].(Raw); ok { return gconv.String(v) } - var ( - reflectInfo = utils.OriginValueAndKind(args[index]) - ) + reflectInfo := utils.OriginValueAndKind(args[index]) if reflectInfo.OriginKind == reflect.Ptr && (reflectInfo.OriginValue.IsNil() || !reflectInfo.OriginValue.IsValid()) { return "null" diff --git a/database/gdb/gdb_model.go b/database/gdb/gdb_model.go index c8a51945d..172176029 100644 --- a/database/gdb/gdb_model.go +++ b/database/gdb/gdb_model.go @@ -9,12 +9,10 @@ package gdb import ( "context" "fmt" - "github.com/gogf/gf/v2/util/gconv" - "time" "github.com/gogf/gf/v2/text/gregex" - "github.com/gogf/gf/v2/text/gstr" + "github.com/gogf/gf/v2/util/gconv" ) // Model is core struct implementing the DAO for ORM. @@ -45,8 +43,7 @@ type Model struct { distinct string // Force the query to only return distinct results. lockInfo string // Lock for update or in shared lock. cacheEnabled bool // Enable sql result cache feature. - cacheDuration time.Duration // Cache TTL duration (< 1 for removing cache, >= 0 for saving cache). - cacheName string // Cache name for custom operation. + cacheOption CacheOption // Cache option for query statement. unscoped bool // Disables soft deleting features when select/delete operations. safe bool // If true, it clones and returns a new model object whenever operation done; or else it changes the attribute of current model. onDuplicate interface{} // onDuplicate is used for ON "DUPLICATE KEY UPDATE" statement. @@ -98,7 +95,7 @@ func (c *Core) Model(tableNameQueryOrStruct ...interface{}) *Model { if len(tableNameQueryOrStruct) > 1 { conditionStr := gconv.String(tableNameQueryOrStruct[0]) if gstr.Contains(conditionStr, "?") { - tableStr, extraArgs = formatWhere(c.db, formatWhereInput{ + tableStr, extraArgs = formatWhereHolder(c.db, formatWhereHolderInput{ Where: conditionStr, Args: tableNameQueryOrStruct[1:], OmitNil: false, diff --git a/database/gdb/gdb_model_cache.go b/database/gdb/gdb_model_cache.go index d505abc3b..5704cd6ea 100644 --- a/database/gdb/gdb_model_cache.go +++ b/database/gdb/gdb_model_cache.go @@ -7,30 +7,37 @@ package gdb import ( - "github.com/gogf/gf/v2/internal/intlog" "time" + + "github.com/gogf/gf/v2/internal/intlog" ) +type CacheOption struct { + // Duration is the TTL for the cache. + // If the parameter `Duration` < 0, which means it clear the cache with given `Name`. + // If the parameter `Duration` = 0, which means it never expires. + // If the parameter `Duration` > 0, which means it expires after `Duration`. + Duration time.Duration + + // Name is an optional unique name for the cache. + // The Name is used to bind a name to the cache, which means you can later control the cache + // like changing the `duration` or clearing the cache with specified Name. + Name string + + // Force caches the query result whatever the result is nil or not. + // It is used to avoid Cache Penetration. + Force bool +} + // Cache sets the cache feature for the model. It caches the result of the sql, which means // if there's another same sql request, it just reads and returns the result from cache, it // but not committed and executed into the database. // -// If the parameter `duration` < 0, which means it clear the cache with given `name`. -// If the parameter `duration` = 0, which means it never expires. -// If the parameter `duration` > 0, which means it expires after `duration`. -// -// The optional parameter `name` is used to bind a name to the cache, which means you can -// later control the cache like changing the `duration` or clearing the cache with specified -// `name`. -// // Note that, the cache feature is disabled if the model is performing select statement // on a transaction. -func (m *Model) Cache(duration time.Duration, name ...string) *Model { +func (m *Model) Cache(option CacheOption) *Model { model := m.getModel() - model.cacheDuration = duration - if len(name) > 0 { - model.cacheName = name[0] - } + model.cacheOption = option model.cacheEnabled = true return model } @@ -38,9 +45,9 @@ func (m *Model) Cache(duration time.Duration, name ...string) *Model { // checkAndRemoveCache checks and removes the cache in insert/update/delete statement if // cache feature is enabled. func (m *Model) checkAndRemoveCache() { - if m.cacheEnabled && m.cacheDuration < 0 && len(m.cacheName) > 0 { - var ctx = m.GetCtx() - _, err := m.db.GetCache().Remove(ctx, m.cacheName) + if m.cacheEnabled && m.cacheOption.Duration < 0 && len(m.cacheOption.Name) > 0 { + ctx := m.GetCtx() + _, err := m.db.GetCache().Remove(ctx, m.cacheOption.Name) if err != nil { intlog.Error(ctx, err) } diff --git a/database/gdb/gdb_model_condition.go b/database/gdb/gdb_model_condition.go deleted file mode 100644 index 62204b0f4..000000000 --- a/database/gdb/gdb_model_condition.go +++ /dev/null @@ -1,457 +0,0 @@ -// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. -// -// This Source Code Form is subject to the terms of the MIT License. -// If a copy of the MIT was not distributed with this file, -// You can obtain one at https://github.com/gogf/gf. - -package gdb - -import ( - "fmt" - "github.com/gogf/gf/v2/text/gstr" - "github.com/gogf/gf/v2/util/gconv" -) - -// Where sets the condition statement for the model. The parameter `where` can be type of -// string/map/gmap/slice/struct/*struct, etc. Note that, if it's called more than one times, -// multiple conditions will be joined into where statement using "AND". -// Eg: -// Where("uid=10000") -// Where("uid", 10000) -// Where("money>? AND name like ?", 99999, "vip_%") -// Where("uid", 1).Where("name", "john") -// Where("status IN (?)", g.Slice{1,2,3}) -// Where("age IN(?,?)", 18, 50) -// Where(User{ Id : 1, UserName : "john"}) -func (m *Model) Where(where interface{}, args ...interface{}) *Model { - model := m.getModel() - if model.whereHolder == nil { - model.whereHolder = make([]ModelWhereHolder, 0) - } - model.whereHolder = append(model.whereHolder, ModelWhereHolder{ - Operator: whereHolderOperatorWhere, - Where: where, - Args: args, - }) - return model -} - -// WherePrefix performs as Where, but it adds prefix to each field in where statement. -func (m *Model) WherePrefix(prefix string, where interface{}, args ...interface{}) *Model { - model := m.getModel() - if model.whereHolder == nil { - model.whereHolder = make([]ModelWhereHolder, 0) - } - model.whereHolder = append(model.whereHolder, ModelWhereHolder{ - Operator: whereHolderOperatorWhere, - Where: where, - Args: args, - Prefix: prefix, - }) - return model -} - -// Having sets the having statement for the model. -// The parameters of this function usage are as the same as function Where. -// See Where. -func (m *Model) Having(having interface{}, args ...interface{}) *Model { - model := m.getModel() - model.having = []interface{}{ - having, args, - } - return model -} - -// WherePri does the same logic as Model.Where except that if the parameter `where` -// is a single condition like int/string/float/slice, it treats the condition as the primary -// key value. That is, if primary key is "id" and given `where` parameter as "123", the -// WherePri function treats the condition as "id=123", but Model.Where treats the condition -// as string "123". -func (m *Model) WherePri(where interface{}, args ...interface{}) *Model { - if len(args) > 0 { - return m.Where(where, args...) - } - newWhere := GetPrimaryKeyCondition(m.getPrimaryKey(), where) - return m.Where(newWhere[0], newWhere[1:]...) -} - -// Wheref builds condition string using fmt.Sprintf and arguments. -// 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 ( - placeHolderCount = gstr.Count(format, "?") - conditionStr = fmt.Sprintf(format, args[:len(args)-placeHolderCount]...) - ) - return m.Where(conditionStr, args[len(args)-placeHolderCount:]...) -} - -// WhereLT builds `column < value` statement. -func (m *Model) WhereLT(column string, value interface{}) *Model { - return m.Wheref(`%s < ?`, column, value) -} - -// WhereLTE builds `column <= value` statement. -func (m *Model) WhereLTE(column string, value interface{}) *Model { - return m.Wheref(`%s <= ?`, column, value) -} - -// WhereGT builds `column > value` statement. -func (m *Model) WhereGT(column string, value interface{}) *Model { - return m.Wheref(`%s > ?`, column, value) -} - -// WhereGTE builds `column >= value` statement. -func (m *Model) WhereGTE(column string, value interface{}) *Model { - return m.Wheref(`%s >= ?`, column, value) -} - -// WhereBetween builds `column BETWEEN min AND max` statement. -func (m *Model) WhereBetween(column string, min, max interface{}) *Model { - return m.Wheref(`%s BETWEEN ? AND ?`, m.db.GetCore().QuoteWord(column), min, max) -} - -// WhereLike builds `column LIKE like` statement. -func (m *Model) WhereLike(column string, like interface{}) *Model { - return m.Wheref(`%s LIKE ?`, m.db.GetCore().QuoteWord(column), like) -} - -// WhereIn builds `column IN (in)` statement. -func (m *Model) WhereIn(column string, in interface{}) *Model { - return m.Wheref(`%s IN (?)`, m.db.GetCore().QuoteWord(column), in) -} - -// WhereNull builds `columns[0] IS NULL AND columns[1] IS NULL ...` statement. -func (m *Model) WhereNull(columns ...string) *Model { - model := m - for _, column := range columns { - model = m.Wheref(`%s IS NULL`, m.db.GetCore().QuoteWord(column)) - } - return model -} - -// WhereNotBetween builds `column NOT BETWEEN min AND max` statement. -func (m *Model) WhereNotBetween(column string, min, max interface{}) *Model { - return m.Wheref(`%s NOT BETWEEN ? AND ?`, m.db.GetCore().QuoteWord(column), min, max) -} - -// WhereNotLike builds `column NOT LIKE like` statement. -func (m *Model) WhereNotLike(column string, like interface{}) *Model { - return m.Wheref(`%s NOT LIKE ?`, m.db.GetCore().QuoteWord(column), like) -} - -// WhereNot builds `column != value` statement. -func (m *Model) WhereNot(column string, value interface{}) *Model { - return m.Wheref(`%s != ?`, m.db.GetCore().QuoteWord(column), value) -} - -// WhereNotIn builds `column NOT IN (in)` statement. -func (m *Model) WhereNotIn(column string, in interface{}) *Model { - return m.Wheref(`%s NOT IN (?)`, m.db.GetCore().QuoteWord(column), in) -} - -// WhereNotNull builds `columns[0] IS NOT NULL AND columns[1] IS NOT NULL ...` statement. -func (m *Model) WhereNotNull(columns ...string) *Model { - model := m - for _, column := range columns { - model = m.Wheref(`%s IS NOT NULL`, m.db.GetCore().QuoteWord(column)) - } - return model -} - -// WhereOr adds "OR" condition to the where statement. -func (m *Model) WhereOr(where interface{}, args ...interface{}) *Model { - model := m.getModel() - if model.whereHolder == nil { - model.whereHolder = make([]ModelWhereHolder, 0) - } - model.whereHolder = append(model.whereHolder, ModelWhereHolder{ - Operator: whereHolderOperatorOr, - Where: where, - Args: args, - }) - return model -} - -// WhereOrPrefix performs as WhereOr, but it adds prefix to each field in where statement. -func (m *Model) WhereOrPrefix(prefix string, where interface{}, args ...interface{}) *Model { - model := m.getModel() - if model.whereHolder == nil { - model.whereHolder = make([]ModelWhereHolder, 0) - } - model.whereHolder = append(model.whereHolder, ModelWhereHolder{ - Operator: whereHolderOperatorOr, - Where: where, - Args: args, - Prefix: prefix, - }) - return model -} - -// WhereOrf builds `OR` condition string using fmt.Sprintf and arguments. -func (m *Model) WhereOrf(format string, args ...interface{}) *Model { - var ( - placeHolderCount = gstr.Count(format, "?") - conditionStr = fmt.Sprintf(format, args[:len(args)-placeHolderCount]...) - ) - return m.WhereOr(conditionStr, args[len(args)-placeHolderCount:]...) -} - -// WhereOrLT builds `column < value` statement in `OR` conditions.. -func (m *Model) WhereOrLT(column string, value interface{}) *Model { - return m.WhereOrf(`%s < ?`, column, value) -} - -// WhereOrLTE builds `column <= value` statement in `OR` conditions.. -func (m *Model) WhereOrLTE(column string, value interface{}) *Model { - return m.WhereOrf(`%s <= ?`, column, value) -} - -// WhereOrGT builds `column > value` statement in `OR` conditions.. -func (m *Model) WhereOrGT(column string, value interface{}) *Model { - return m.WhereOrf(`%s > ?`, column, value) -} - -// WhereOrGTE builds `column >= value` statement in `OR` conditions.. -func (m *Model) WhereOrGTE(column string, value interface{}) *Model { - return m.WhereOrf(`%s >= ?`, column, value) -} - -// WhereOrBetween builds `column BETWEEN min AND max` statement in `OR` conditions. -func (m *Model) WhereOrBetween(column string, min, max interface{}) *Model { - return m.WhereOrf(`%s BETWEEN ? AND ?`, m.db.GetCore().QuoteWord(column), min, max) -} - -// WhereOrLike builds `column LIKE like` statement in `OR` conditions. -func (m *Model) WhereOrLike(column string, like interface{}) *Model { - return m.WhereOrf(`%s LIKE ?`, m.db.GetCore().QuoteWord(column), like) -} - -// WhereOrIn builds `column IN (in)` statement in `OR` conditions. -func (m *Model) WhereOrIn(column string, in interface{}) *Model { - return m.WhereOrf(`%s IN (?)`, m.db.GetCore().QuoteWord(column), in) -} - -// WhereOrNull builds `columns[0] IS NULL OR columns[1] IS NULL ...` statement in `OR` conditions. -func (m *Model) WhereOrNull(columns ...string) *Model { - model := m - for _, column := range columns { - model = m.WhereOrf(`%s IS NULL`, m.db.GetCore().QuoteWord(column)) - } - return model -} - -// WhereOrNotBetween builds `column NOT BETWEEN min AND max` statement in `OR` conditions. -func (m *Model) WhereOrNotBetween(column string, min, max interface{}) *Model { - return m.WhereOrf(`%s NOT BETWEEN ? AND ?`, m.db.GetCore().QuoteWord(column), min, max) -} - -// WhereOrNotLike builds `column NOT LIKE like` statement in `OR` conditions. -func (m *Model) WhereOrNotLike(column string, like interface{}) *Model { - return m.WhereOrf(`%s NOT LIKE ?`, m.db.GetCore().QuoteWord(column), like) -} - -// WhereOrNotIn builds `column NOT IN (in)` statement. -func (m *Model) WhereOrNotIn(column string, in interface{}) *Model { - return m.WhereOrf(`%s NOT IN (?)`, m.db.GetCore().QuoteWord(column), in) -} - -// WhereOrNotNull builds `columns[0] IS NOT NULL OR columns[1] IS NOT NULL ...` statement in `OR` conditions. -func (m *Model) WhereOrNotNull(columns ...string) *Model { - model := m - for _, column := range columns { - model = m.WhereOrf(`%s IS NOT NULL`, m.db.GetCore().QuoteWord(column)) - } - return model -} - -// Limit sets the "LIMIT" statement for the model. -// The parameter `limit` can be either one or two number, if passed two number is passed, -// it then sets "LIMIT limit[0],limit[1]" statement for the model, or else it sets "LIMIT limit[0]" -// statement. -func (m *Model) Limit(limit ...int) *Model { - model := m.getModel() - switch len(limit) { - case 1: - model.limit = limit[0] - case 2: - model.start = limit[0] - model.limit = limit[1] - } - return model -} - -// Offset sets the "OFFSET" statement for the model. -// It only makes sense for some databases like SQLServer, PostgreSQL, etc. -func (m *Model) Offset(offset int) *Model { - model := m.getModel() - model.offset = offset - return model -} - -// Distinct forces the query to only return distinct results. -func (m *Model) Distinct() *Model { - model := m.getModel() - model.distinct = "DISTINCT " - return model -} - -// Page sets the paging number for the model. -// The parameter `page` is started from 1 for paging. -// Note that, it differs that the Limit function starts from 0 for "LIMIT" statement. -func (m *Model) Page(page, limit int) *Model { - model := m.getModel() - if page <= 0 { - page = 1 - } - model.start = (page - 1) * limit - model.limit = limit - return model -} - -// formatCondition formats where arguments of the model and returns a new condition sql and its arguments. -// Note that this function does not change any attribute value of the `m`. -// -// The parameter `limit1` specifies whether limits querying only one record if m.limit is not set. -func (m *Model) formatCondition(limit1 bool, isCountStatement bool) (conditionWhere string, conditionExtra string, conditionArgs []interface{}) { - var ( - autoPrefix = "" - ) - if gstr.Contains(m.tables, " JOIN ") { - autoPrefix = m.db.GetCore().QuoteWord(m.tablesInit) - } - if len(m.whereHolder) > 0 { - for _, v := range m.whereHolder { - if v.Prefix == "" { - v.Prefix = autoPrefix - } - switch v.Operator { - case whereHolderOperatorWhere: - if conditionWhere == "" { - newWhere, newArgs := formatWhere(m.db, formatWhereInput{ - Where: v.Where, - Args: v.Args, - OmitNil: m.option&optionOmitNilWhere > 0, - OmitEmpty: m.option&optionOmitEmptyWhere > 0, - Schema: m.schema, - Table: m.tables, - Prefix: v.Prefix, - }) - if len(newWhere) > 0 { - conditionWhere = newWhere - conditionArgs = newArgs - } - continue - } - fallthrough - - case whereHolderOperatorAnd: - newWhere, newArgs := formatWhere(m.db, formatWhereInput{ - Where: v.Where, - Args: v.Args, - OmitNil: m.option&optionOmitNilWhere > 0, - OmitEmpty: m.option&optionOmitEmptyWhere > 0, - Schema: m.schema, - Table: m.tables, - Prefix: v.Prefix, - }) - if len(newWhere) > 0 { - if len(conditionWhere) == 0 { - conditionWhere = newWhere - } else if conditionWhere[0] == '(' { - conditionWhere = fmt.Sprintf(`%s AND (%s)`, conditionWhere, newWhere) - } else { - conditionWhere = fmt.Sprintf(`(%s) AND (%s)`, conditionWhere, newWhere) - } - conditionArgs = append(conditionArgs, newArgs...) - } - - case whereHolderOperatorOr: - newWhere, newArgs := formatWhere(m.db, formatWhereInput{ - Where: v.Where, - Args: v.Args, - OmitNil: m.option&optionOmitNilWhere > 0, - OmitEmpty: m.option&optionOmitEmptyWhere > 0, - Schema: m.schema, - Table: m.tables, - Prefix: v.Prefix, - }) - if len(newWhere) > 0 { - if len(conditionWhere) == 0 { - conditionWhere = newWhere - } else if conditionWhere[0] == '(' { - conditionWhere = fmt.Sprintf(`%s OR (%s)`, conditionWhere, newWhere) - } else { - conditionWhere = fmt.Sprintf(`(%s) OR (%s)`, conditionWhere, newWhere) - } - conditionArgs = append(conditionArgs, newArgs...) - } - } - } - } - // Soft deletion. - softDeletingCondition := m.getConditionForSoftDeleting() - if m.rawSql != "" && conditionWhere != "" { - if gstr.ContainsI(m.rawSql, " WHERE ") { - conditionWhere = " AND " + conditionWhere - } else { - conditionWhere = " WHERE " + conditionWhere - } - } else if !m.unscoped && softDeletingCondition != "" { - if conditionWhere == "" { - conditionWhere = fmt.Sprintf(` WHERE %s`, softDeletingCondition) - } else { - conditionWhere = fmt.Sprintf(` WHERE (%s) AND %s`, conditionWhere, softDeletingCondition) - } - } else { - if conditionWhere != "" { - conditionWhere = " WHERE " + conditionWhere - } - } - - // GROUP BY. - if m.groupBy != "" { - conditionExtra += " GROUP BY " + m.groupBy - } - // HAVING. - if len(m.having) > 0 { - havingStr, havingArgs := formatWhere(m.db, formatWhereInput{ - Where: m.having[0], - Args: gconv.Interfaces(m.having[1]), - OmitNil: m.option&optionOmitNilWhere > 0, - OmitEmpty: m.option&optionOmitEmptyWhere > 0, - Schema: m.schema, - Table: m.tables, - Prefix: autoPrefix, - }) - if len(havingStr) > 0 { - conditionExtra += " HAVING " + havingStr - conditionArgs = append(conditionArgs, havingArgs...) - } - } - // ORDER BY. - if m.orderBy != "" { - conditionExtra += " ORDER BY " + m.orderBy - } - // LIMIT. - if !isCountStatement { - if m.limit != 0 { - if m.start >= 0 { - conditionExtra += fmt.Sprintf(" LIMIT %d,%d", m.start, m.limit) - } else { - conditionExtra += fmt.Sprintf(" LIMIT %d", m.limit) - } - } else if limit1 { - conditionExtra += " LIMIT 1" - } - - if m.offset >= 0 { - conditionExtra += fmt.Sprintf(" OFFSET %d", m.offset) - } - } - - if m.lockInfo != "" { - conditionExtra += " " + m.lockInfo - } - return -} diff --git a/database/gdb/gdb_model_delete.go b/database/gdb/gdb_model_delete.go index 33c396872..334338f6f 100644 --- a/database/gdb/gdb_model_delete.go +++ b/database/gdb/gdb_model_delete.go @@ -9,8 +9,8 @@ package gdb import ( "database/sql" "fmt" - "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/text/gstr" diff --git a/database/gdb/gdb_model_fields.go b/database/gdb/gdb_model_fields.go index c650d3503..a9daa9aea 100644 --- a/database/gdb/gdb_model_fields.go +++ b/database/gdb/gdb_model_fields.go @@ -8,6 +8,7 @@ package gdb import ( "fmt" + "github.com/gogf/gf/v2/container/gset" "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" @@ -20,7 +21,7 @@ import ( // Fields("id", "name", "age") // Fields([]string{"id", "name", "age"}) // Fields(map[string]interface{}{"id":1, "name":"john", "age":18}) -// Fields(User{ Id: 1, Name: "john", Age: 18}) +// Fields(User{ Id: 1, Name: "john", Age: 18}). func (m *Model) Fields(fieldNamesOrMapStruct ...interface{}) *Model { length := len(fieldNamesOrMapStruct) if length == 0 { @@ -110,7 +111,7 @@ func (m *Model) FieldCount(column string, as ...string) *Model { if len(as) > 0 && as[0] != "" { asStr = fmt.Sprintf(` AS %s`, m.db.GetCore().QuoteWord(as[0])) } - return m.appendFieldsByStr(fmt.Sprintf(`COUNT(%s)%s`, m.db.GetCore().QuoteWord(column), asStr)) + return m.appendFieldsByStr(fmt.Sprintf(`COUNT(%s)%s`, m.QuoteWord(column), asStr)) } // FieldSum formats and appends commonly used field `SUM(column)` to the select fields of model. @@ -119,7 +120,7 @@ func (m *Model) FieldSum(column string, as ...string) *Model { if len(as) > 0 && as[0] != "" { asStr = fmt.Sprintf(` AS %s`, m.db.GetCore().QuoteWord(as[0])) } - return m.appendFieldsByStr(fmt.Sprintf(`SUM(%s)%s`, m.db.GetCore().QuoteWord(column), asStr)) + return m.appendFieldsByStr(fmt.Sprintf(`SUM(%s)%s`, m.QuoteWord(column), asStr)) } // FieldMin formats and appends commonly used field `MIN(column)` to the select fields of model. @@ -128,7 +129,7 @@ func (m *Model) FieldMin(column string, as ...string) *Model { if len(as) > 0 && as[0] != "" { asStr = fmt.Sprintf(` AS %s`, m.db.GetCore().QuoteWord(as[0])) } - return m.appendFieldsByStr(fmt.Sprintf(`MIN(%s)%s`, m.db.GetCore().QuoteWord(column), asStr)) + return m.appendFieldsByStr(fmt.Sprintf(`MIN(%s)%s`, m.QuoteWord(column), asStr)) } // FieldMax formats and appends commonly used field `MAX(column)` to the select fields of model. @@ -137,7 +138,7 @@ func (m *Model) FieldMax(column string, as ...string) *Model { if len(as) > 0 && as[0] != "" { asStr = fmt.Sprintf(` AS %s`, m.db.GetCore().QuoteWord(as[0])) } - return m.appendFieldsByStr(fmt.Sprintf(`MAX(%s)%s`, m.db.GetCore().QuoteWord(column), asStr)) + return m.appendFieldsByStr(fmt.Sprintf(`MAX(%s)%s`, m.QuoteWord(column), asStr)) } // FieldAvg formats and appends commonly used field `AVG(column)` to the select fields of model. @@ -146,7 +147,7 @@ func (m *Model) FieldAvg(column string, as ...string) *Model { if len(as) > 0 && as[0] != "" { asStr = fmt.Sprintf(` AS %s`, m.db.GetCore().QuoteWord(as[0])) } - return m.appendFieldsByStr(fmt.Sprintf(`AVG(%s)%s`, m.db.GetCore().QuoteWord(column), asStr)) + return m.appendFieldsByStr(fmt.Sprintf(`AVG(%s)%s`, m.QuoteWord(column), asStr)) } func (m *Model) appendFieldsByStr(fields string) *Model { diff --git a/database/gdb/gdb_model_insert.go b/database/gdb/gdb_model_insert.go index 2549190b3..0333c2445 100644 --- a/database/gdb/gdb_model_insert.go +++ b/database/gdb/gdb_model_insert.go @@ -8,12 +8,12 @@ package gdb import ( "database/sql" - "github.com/gogf/gf/v2/container/gset" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/internal/utils" "reflect" + "github.com/gogf/gf/v2/container/gset" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/utils" "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" @@ -36,7 +36,7 @@ func (m *Model) Batch(batch int) *Model { // Data("uid", 10000) // Data("uid=? AND name=?", 10000, "john") // Data(g.Map{"uid": 10000, "name":"john"}) -// Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"}) +// Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"}). func (m *Model) Data(data ...interface{}) *Model { model := m.getModel() if len(data) > 1 { @@ -69,25 +69,29 @@ func (m *Model) Data(data ...interface{}) *Model { model.data = gutil.MapCopy(value) default: - var ( - reflectInfo = utils.OriginValueAndKind(value) - ) + reflectInfo := utils.OriginValueAndKind(value) switch reflectInfo.OriginKind { case reflect.Slice, reflect.Array: + if reflectInfo.OriginValue.Len() > 0 { + // If the `data` parameter is defined like `xxxForDao`, + // it then adds `OmitNilData` option for this condition, + // which will filter all nil parameters in `data`. + if isForDaoModel(reflectInfo.OriginValue.Index(0).Elem().Type()) { + model = model.OmitNilData() + model.option |= optionOmitNilDataInternal + } + } list := make(List, reflectInfo.OriginValue.Len()) for i := 0; i < reflectInfo.OriginValue.Len(); i++ { list[i] = ConvertDataForTableRecord(reflectInfo.OriginValue.Index(i).Interface()) } model.data = list - case reflect.Map: - model.data = ConvertDataForTableRecord(data[0]) - case reflect.Struct: // If the `data` parameter is defined like `xxxForDao`, // it then adds `OmitNilData` option for this condition, // which will filter all nil parameters in `data`. - if gstr.HasSuffix(reflect.TypeOf(value).String(), modelForDaoSuffix) { + if isForDaoModel(reflect.TypeOf(value)) { model = model.OmitNilData() } if v, ok := data[0].(iInterfaces); ok { @@ -103,6 +107,9 @@ func (m *Model) Data(data ...interface{}) *Model { model.data = ConvertDataForTableRecord(data[0]) } + case reflect.Map: + model.data = ConvertDataForTableRecord(data[0]) + default: model.data = data[0] } @@ -122,7 +129,7 @@ func (m *Model) Data(data ...interface{}) *Model { // }) // OnDuplicate(g.Map{ // "nickname": "passport", -// }) +// }). func (m *Model) OnDuplicate(onDuplicate ...interface{}) *Model { model := m.getModel() if len(onDuplicate) > 1 { @@ -142,7 +149,7 @@ func (m *Model) OnDuplicate(onDuplicate ...interface{}) *Model { // OnDuplicateEx(g.Map{ // "passport": "", // "password": "", -// }) +// }). func (m *Model) OnDuplicateEx(onDuplicateEx ...interface{}) *Model { model := m.getModel() if len(onDuplicateEx) > 1 { @@ -228,7 +235,6 @@ func (m *Model) doInsertWithOption(insertOption int) (result sql.Result, err err if err != nil { return nil, err } - // It converts any data to List type for inserting. switch value := newData.(type) { case Result: @@ -247,9 +253,7 @@ func (m *Model) doInsertWithOption(insertOption int) (result sql.Result, err err list = List{ConvertDataForTableRecord(value)} default: - var ( - reflectInfo = utils.OriginValueAndKind(newData) - ) + reflectInfo := utils.OriginValueAndKind(newData) switch reflectInfo.OriginKind { // If it's slice type, it then converts it to List type. case reflect.Slice, reflect.Array: @@ -263,9 +267,7 @@ func (m *Model) doInsertWithOption(insertOption int) (result sql.Result, err err case reflect.Struct: if v, ok := value.(iInterfaces); ok { - var ( - array = v.Interfaces() - ) + array := v.Interfaces() list = make(List, len(array)) for i := 0; i < len(array); i++ { list[i] = ConvertDataForTableRecord(array[i]) @@ -301,14 +303,13 @@ func (m *Model) doInsertWithOption(insertOption int) (result sql.Result, err err } // Format DoInsertOption, especially for "ON DUPLICATE KEY UPDATE" statement. columnNames := make([]string, 0, len(list[0])) - for k, _ := range list[0] { + for k := range list[0] { columnNames = append(columnNames, k) } doInsertOption, err := m.formatDoInsertOption(insertOption, columnNames) if err != nil { return result, err } - return m.db.DoInsert(m.GetCtx(), m.getLink(true), m.tables, list, doInsertOption) } @@ -322,18 +323,14 @@ func (m *Model) formatDoInsertOption(insertOption int, columnNames []string) (op if err != nil { return option, err } - var ( - onDuplicateExKeySet = gset.NewStrSetFrom(onDuplicateExKeys) - ) + onDuplicateExKeySet := gset.NewStrSetFrom(onDuplicateExKeys) if m.onDuplicate != nil { switch m.onDuplicate.(type) { case Raw, *Raw: option.OnDuplicateStr = gconv.String(m.onDuplicate) default: - var ( - reflectInfo = utils.OriginValueAndKind(m.onDuplicate) - ) + reflectInfo := utils.OriginValueAndKind(m.onDuplicate) switch reflectInfo.OriginKind { case reflect.String: option.OnDuplicateMap = make(map[string]interface{}) @@ -388,9 +385,7 @@ func (m *Model) formatOnDuplicateExKeys(onDuplicateEx interface{}) ([]string, er return nil, nil } - var ( - reflectInfo = utils.OriginValueAndKind(onDuplicateEx) - ) + reflectInfo := utils.OriginValueAndKind(onDuplicateEx) switch reflectInfo.OriginKind { case reflect.String: return gstr.SplitAndTrim(reflectInfo.OriginValue.String(), ","), nil diff --git a/database/gdb/gdb_model_join.go b/database/gdb/gdb_model_join.go index 2b3410e78..237397b5f 100644 --- a/database/gdb/gdb_model_join.go +++ b/database/gdb/gdb_model_join.go @@ -30,7 +30,7 @@ func isSubQuery(s string) bool { // Eg: // Model("user").LeftJoin("user_detail", "user_detail.uid=user.uid") // Model("user", "u").LeftJoin("user_detail", "ud", "ud.uid=u.uid") -// Model("user", "u").LeftJoin("SELECT xxx FROM xxx AS a", "a.uid=u.uid") +// Model("user", "u").LeftJoin("SELECT xxx FROM xxx AS a", "a.uid=u.uid"). func (m *Model) LeftJoin(table ...string) *Model { return m.doJoin("LEFT", table...) } @@ -42,7 +42,7 @@ func (m *Model) LeftJoin(table ...string) *Model { // Eg: // Model("user").RightJoin("user_detail", "user_detail.uid=user.uid") // Model("user", "u").RightJoin("user_detail", "ud", "ud.uid=u.uid") -// Model("user", "u").RightJoin("SELECT xxx FROM xxx AS a", "a.uid=u.uid") +// Model("user", "u").RightJoin("SELECT xxx FROM xxx AS a", "a.uid=u.uid"). func (m *Model) RightJoin(table ...string) *Model { return m.doJoin("RIGHT", table...) } @@ -54,7 +54,7 @@ func (m *Model) RightJoin(table ...string) *Model { // Eg: // Model("user").InnerJoin("user_detail", "user_detail.uid=user.uid") // Model("user", "u").InnerJoin("user_detail", "ud", "ud.uid=u.uid") -// Model("user", "u").InnerJoin("SELECT xxx FROM xxx AS a", "a.uid=u.uid") +// Model("user", "u").InnerJoin("SELECT xxx FROM xxx AS a", "a.uid=u.uid"). func (m *Model) InnerJoin(table ...string) *Model { return m.doJoin("INNER", table...) } @@ -63,7 +63,7 @@ func (m *Model) InnerJoin(table ...string) *Model { // // Eg: // Model("order").LeftJoinOnField("user", "user_id") -// Model("order").LeftJoinOnField("product", "product_id") +// Model("order").LeftJoinOnField("product", "product_id"). func (m *Model) LeftJoinOnField(table, field string) *Model { return m.doJoin("LEFT", table, fmt.Sprintf( `%s.%s=%s.%s`, @@ -78,7 +78,7 @@ func (m *Model) LeftJoinOnField(table, field string) *Model { // // Eg: // Model("order").InnerJoinOnField("user", "user_id") -// Model("order").InnerJoinOnField("product", "product_id") +// Model("order").InnerJoinOnField("product", "product_id"). func (m *Model) RightJoinOnField(table, field string) *Model { return m.doJoin("RIGHT", table, fmt.Sprintf( `%s.%s=%s.%s`, @@ -93,7 +93,7 @@ func (m *Model) RightJoinOnField(table, field string) *Model { // // Eg: // Model("order").InnerJoinOnField("user", "user_id") -// Model("order").InnerJoinOnField("product", "product_id") +// Model("order").InnerJoinOnField("product", "product_id"). func (m *Model) InnerJoinOnField(table, field string) *Model { return m.doJoin("INNER", table, fmt.Sprintf( `%s.%s=%s.%s`, diff --git a/database/gdb/gdb_model_option.go b/database/gdb/gdb_model_option.go index 3311f6b25..f7520b3e9 100644 --- a/database/gdb/gdb_model_option.go +++ b/database/gdb/gdb_model_option.go @@ -7,12 +7,14 @@ package gdb const ( - optionOmitNil = optionOmitNilWhere | optionOmitNilData - optionOmitEmpty = optionOmitEmptyWhere | optionOmitEmptyData - optionOmitEmptyWhere = 1 << iota // 8 - optionOmitEmptyData // 16 - optionOmitNilWhere // 32 - optionOmitNilData // 64 + optionOmitNil = optionOmitNilWhere | optionOmitNilData + optionOmitEmpty = optionOmitEmptyWhere | optionOmitEmptyData + optionOmitNilDataInternal = optionOmitNilData | optionOmitNilDataList // this option is used internally only for ForDao feature. + optionOmitEmptyWhere = 1 << iota // 8 + optionOmitEmptyData // 16 + optionOmitNilWhere // 32 + optionOmitNilData // 64 + optionOmitNilDataList // 128 ) // OmitEmpty sets optionOmitEmpty option for the model, which automatically filers @@ -30,7 +32,7 @@ func (m *Model) OmitEmpty() *Model { // Where("id", []int{}).All() -> SELECT xxx FROM xxx WHERE 0=1 // Where("name", "").All() -> SELECT xxx FROM xxx WHERE `name`='' // OmitEmpty().Where("id", []int{}).All() -> SELECT xxx FROM xxx -// OmitEmpty().("name", "").All() -> SELECT xxx FROM xxx +// OmitEmpty().("name", "").All() -> SELECT xxx FROM xxx. func (m *Model) OmitEmptyWhere() *Model { model := m.getModel() model.option = model.option | optionOmitEmptyWhere diff --git a/database/gdb/gdb_model_order_group.go b/database/gdb/gdb_model_order_group.go index e212bc070..bf8fbbc01 100644 --- a/database/gdb/gdb_model_order_group.go +++ b/database/gdb/gdb_model_order_group.go @@ -13,7 +13,7 @@ import "strings" // Eg: // Order("id desc") // Order("id", "desc") -// Order("id desc,name asc") +// Order("id desc,name asc"). func (m *Model) Order(orderBy ...string) *Model { if len(orderBy) == 0 { return m diff --git a/database/gdb/gdb_model_select.go b/database/gdb/gdb_model_select.go index 70f449d44..9e4006c61 100644 --- a/database/gdb/gdb_model_select.go +++ b/database/gdb/gdb_model_select.go @@ -8,15 +8,15 @@ package gdb import ( "fmt" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/internal/utils" "reflect" "github.com/gogf/gf/v2/container/gset" "github.com/gogf/gf/v2/container/gvar" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/internal/json" + "github.com/gogf/gf/v2/internal/utils" "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" ) @@ -206,7 +206,7 @@ func (m *Model) Array(fieldsAndWhere ...interface{}) ([]Value, error) { // err := db.Model("user").Where("id", 1).Scan(user) // // user := (*User)(nil) -// err := db.Model("user").Where("id", 1).Scan(&user) +// err := db.Model("user").Where("id", 1).Scan(&user). func (m *Model) doStruct(pointer interface{}, where ...interface{}) error { model := m // Auto selecting fields by struct attributes. @@ -242,7 +242,7 @@ func (m *Model) doStruct(pointer interface{}, where ...interface{}) error { // err := db.Model("user").Scan(&users) // // users := ([]*User)(nil) -// err := db.Model("user").Scan(&users) +// err := db.Model("user").Scan(&users). func (m *Model) doStructs(pointer interface{}, where ...interface{}) error { model := m // Auto selecting fields by struct attributes. @@ -291,11 +291,9 @@ func (m *Model) doStructs(pointer interface{}, where ...interface{}) error { // err := db.Model("user").Scan(&users) // // users := ([]*User)(nil) -// err := db.Model("user").Scan(&users) +// err := db.Model("user").Scan(&users). func (m *Model) Scan(pointer interface{}, where ...interface{}) error { - var ( - reflectInfo = utils.OriginTypeAndKind(pointer) - ) + reflectInfo := utils.OriginTypeAndKind(pointer) if reflectInfo.InputKind != reflect.Ptr { return gerror.NewCode( gcode.CodeInvalidParameter, @@ -375,7 +373,7 @@ func (m *Model) Min(column string) (float64, error) { if len(column) == 0 { return 0, nil } - value, err := m.Fields(fmt.Sprintf(`MIN(%s)`, m.db.GetCore().QuoteWord(column))).Value() + value, err := m.Fields(fmt.Sprintf(`MIN(%s)`, m.QuoteWord(column))).Value() if err != nil { return 0, err } @@ -387,7 +385,7 @@ func (m *Model) Max(column string) (float64, error) { if len(column) == 0 { return 0, nil } - value, err := m.Fields(fmt.Sprintf(`MAX(%s)`, m.db.GetCore().QuoteWord(column))).Value() + value, err := m.Fields(fmt.Sprintf(`MAX(%s)`, m.QuoteWord(column))).Value() if err != nil { return 0, err } @@ -399,7 +397,7 @@ func (m *Model) Avg(column string) (float64, error) { if len(column) == 0 { return 0, nil } - value, err := m.Fields(fmt.Sprintf(`AVG(%s)`, m.db.GetCore().QuoteWord(column))).Value() + value, err := m.Fields(fmt.Sprintf(`AVG(%s)`, m.QuoteWord(column))).Value() if err != nil { return 0, err } @@ -411,7 +409,7 @@ func (m *Model) Sum(column string) (float64, error) { if len(column) == 0 { return 0, nil } - value, err := m.Fields(fmt.Sprintf(`SUM(%s)`, m.db.GetCore().QuoteWord(column))).Value() + value, err := m.Fields(fmt.Sprintf(`SUM(%s)`, m.QuoteWord(column))).Value() if err != nil { return 0, err } @@ -428,6 +426,61 @@ func (m *Model) UnionAll(unions ...*Model) *Model { return m.db.UnionAll(unions...) } +// Limit sets the "LIMIT" statement for the model. +// The parameter `limit` can be either one or two number, if passed two number is passed, +// it then sets "LIMIT limit[0],limit[1]" statement for the model, or else it sets "LIMIT limit[0]" +// statement. +func (m *Model) Limit(limit ...int) *Model { + model := m.getModel() + switch len(limit) { + case 1: + model.limit = limit[0] + case 2: + model.start = limit[0] + model.limit = limit[1] + } + return model +} + +// Offset sets the "OFFSET" statement for the model. +// It only makes sense for some databases like SQLServer, PostgreSQL, etc. +func (m *Model) Offset(offset int) *Model { + model := m.getModel() + model.offset = offset + return model +} + +// Distinct forces the query to only return distinct results. +func (m *Model) Distinct() *Model { + model := m.getModel() + model.distinct = "DISTINCT " + return model +} + +// Page sets the paging number for the model. +// The parameter `page` is started from 1 for paging. +// Note that, it differs that the Limit function starts from 0 for "LIMIT" statement. +func (m *Model) Page(page, limit int) *Model { + model := m.getModel() + if page <= 0 { + page = 1 + } + model.start = (page - 1) * limit + model.limit = limit + return model +} + +// Having sets the having statement for the model. +// The parameters of this function usage are as the same as function Where. +// See Where. +func (m *Model) Having(having interface{}, args ...interface{}) *Model { + model := m.getModel() + model.having = []interface{}{ + having, args, + } + return model +} + // doGetAllBySql does the select statement on the database. func (m *Model) doGetAllBySql(sql string, args ...interface{}) (result Result, err error) { var ( @@ -437,7 +490,7 @@ func (m *Model) doGetAllBySql(sql string, args ...interface{}) (result Result, e ) // Retrieve from cache. if m.cacheEnabled && m.tx == nil { - cacheKey = m.cacheName + cacheKey = m.cacheOption.Name if len(cacheKey) == 0 { cacheKey = sql + ", @PARAMS:" + gconv.String(args) } @@ -461,16 +514,16 @@ func (m *Model) doGetAllBySql(sql string, args ...interface{}) (result Result, e ) // Cache the result. if cacheKey != "" && err == nil { - if m.cacheDuration < 0 { + if m.cacheOption.Duration < 0 { if _, err := cacheObj.Remove(ctx, cacheKey); err != nil { intlog.Error(m.GetCtx(), err) } } else { // In case of Cache Penetration. - if result == nil { + if result.IsEmpty() && m.cacheOption.Force { result = Result{} } - if err := cacheObj.Set(ctx, cacheKey, result, m.cacheDuration); err != nil { + if err := cacheObj.Set(ctx, cacheKey, result, m.cacheOption.Duration); err != nil { intlog.Error(m.GetCtx(), err) } } @@ -522,3 +575,150 @@ func (m *Model) getFormattedSqlAndArgs(queryType int, limit1 bool) (sqlWithHolde return sqlWithHolder, conditionArgs } } + +// formatCondition formats where arguments of the model and returns a new condition sql and its arguments. +// Note that this function does not change any attribute value of the `m`. +// +// The parameter `limit1` specifies whether limits querying only one record if m.limit is not set. +func (m *Model) formatCondition(limit1 bool, isCountStatement bool) (conditionWhere string, conditionExtra string, conditionArgs []interface{}) { + autoPrefix := "" + if gstr.Contains(m.tables, " JOIN ") { + autoPrefix = m.db.GetCore().QuoteWord( + m.db.GetCore().guessPrimaryTableName(m.tablesInit), + ) + } + if len(m.whereHolder) > 0 { + for _, v := range m.whereHolder { + if v.Prefix == "" { + v.Prefix = autoPrefix + } + switch v.Operator { + case whereHolderOperatorWhere: + if conditionWhere == "" { + newWhere, newArgs := formatWhereHolder(m.db, formatWhereHolderInput{ + Where: v.Where, + Args: v.Args, + OmitNil: m.option&optionOmitNilWhere > 0, + OmitEmpty: m.option&optionOmitEmptyWhere > 0, + Schema: m.schema, + Table: m.tables, + Prefix: v.Prefix, + }) + if len(newWhere) > 0 { + conditionWhere = newWhere + conditionArgs = newArgs + } + continue + } + fallthrough + + case whereHolderOperatorAnd: + newWhere, newArgs := formatWhereHolder(m.db, formatWhereHolderInput{ + Where: v.Where, + Args: v.Args, + OmitNil: m.option&optionOmitNilWhere > 0, + OmitEmpty: m.option&optionOmitEmptyWhere > 0, + Schema: m.schema, + Table: m.tables, + Prefix: v.Prefix, + }) + if len(newWhere) > 0 { + if len(conditionWhere) == 0 { + conditionWhere = newWhere + } else if conditionWhere[0] == '(' { + conditionWhere = fmt.Sprintf(`%s AND (%s)`, conditionWhere, newWhere) + } else { + conditionWhere = fmt.Sprintf(`(%s) AND (%s)`, conditionWhere, newWhere) + } + conditionArgs = append(conditionArgs, newArgs...) + } + + case whereHolderOperatorOr: + newWhere, newArgs := formatWhereHolder(m.db, formatWhereHolderInput{ + Where: v.Where, + Args: v.Args, + OmitNil: m.option&optionOmitNilWhere > 0, + OmitEmpty: m.option&optionOmitEmptyWhere > 0, + Schema: m.schema, + Table: m.tables, + Prefix: v.Prefix, + }) + if len(newWhere) > 0 { + if len(conditionWhere) == 0 { + conditionWhere = newWhere + } else if conditionWhere[0] == '(' { + conditionWhere = fmt.Sprintf(`%s OR (%s)`, conditionWhere, newWhere) + } else { + conditionWhere = fmt.Sprintf(`(%s) OR (%s)`, conditionWhere, newWhere) + } + conditionArgs = append(conditionArgs, newArgs...) + } + } + } + } + // Soft deletion. + softDeletingCondition := m.getConditionForSoftDeleting() + if m.rawSql != "" && conditionWhere != "" { + if gstr.ContainsI(m.rawSql, " WHERE ") { + conditionWhere = " AND " + conditionWhere + } else { + conditionWhere = " WHERE " + conditionWhere + } + } else if !m.unscoped && softDeletingCondition != "" { + if conditionWhere == "" { + conditionWhere = fmt.Sprintf(` WHERE %s`, softDeletingCondition) + } else { + conditionWhere = fmt.Sprintf(` WHERE (%s) AND %s`, conditionWhere, softDeletingCondition) + } + } else { + if conditionWhere != "" { + conditionWhere = " WHERE " + conditionWhere + } + } + + // GROUP BY. + if m.groupBy != "" { + conditionExtra += " GROUP BY " + m.groupBy + } + // HAVING. + if len(m.having) > 0 { + havingStr, havingArgs := formatWhereHolder(m.db, formatWhereHolderInput{ + Where: m.having[0], + Args: gconv.Interfaces(m.having[1]), + OmitNil: m.option&optionOmitNilWhere > 0, + OmitEmpty: m.option&optionOmitEmptyWhere > 0, + Schema: m.schema, + Table: m.tables, + Prefix: autoPrefix, + }) + if len(havingStr) > 0 { + conditionExtra += " HAVING " + havingStr + conditionArgs = append(conditionArgs, havingArgs...) + } + } + // ORDER BY. + if m.orderBy != "" { + conditionExtra += " ORDER BY " + m.orderBy + } + // LIMIT. + if !isCountStatement { + if m.limit != 0 { + if m.start >= 0 { + conditionExtra += fmt.Sprintf(" LIMIT %d,%d", m.start, m.limit) + } else { + conditionExtra += fmt.Sprintf(" LIMIT %d", m.limit) + } + } else if limit1 { + conditionExtra += " LIMIT 1" + } + + if m.offset >= 0 { + conditionExtra += fmt.Sprintf(" OFFSET %d", m.offset) + } + } + + if m.lockInfo != "" { + conditionExtra += " " + m.lockInfo + } + return +} diff --git a/database/gdb/gdb_model_time.go b/database/gdb/gdb_model_time.go index c600ea0e7..e1120fe42 100644 --- a/database/gdb/gdb_model_time.go +++ b/database/gdb/gdb_model_time.go @@ -8,6 +8,7 @@ package gdb import ( "fmt" + "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/text/gregex" "github.com/gogf/gf/v2/text/gstr" @@ -112,7 +113,7 @@ func (m *Model) getSoftFieldName(table string, keys []string) (field string) { // "user u, user_detail ud" // "user u LEFT JOIN user_detail ud ON(ud.uid=u.uid)" // "user LEFT JOIN user_detail ON(user_detail.uid=user.uid)" -// "user u LEFT JOIN user_detail ud ON(ud.uid=u.uid) LEFT JOIN user_stats us ON(us.uid=u.uid)" +// "user u LEFT JOIN user_detail ud ON(ud.uid=u.uid) LEFT JOIN user_stats us ON(us.uid=u.uid)". func (m *Model) getConditionForSoftDeleting() string { if m.unscoped { return "" diff --git a/database/gdb/gdb_model_update.go b/database/gdb/gdb_model_update.go index 976912e2d..da04b436b 100644 --- a/database/gdb/gdb_model_update.go +++ b/database/gdb/gdb_model_update.go @@ -9,11 +9,11 @@ package gdb import ( "database/sql" "fmt" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/internal/utils" "reflect" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/utils" "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" @@ -49,9 +49,7 @@ func (m *Model) Update(dataAndWhere ...interface{}) (result sql.Result, err erro ) // Automatically update the record updating time. if !m.unscoped && fieldNameUpdate != "" { - var ( - reflectInfo = utils.OriginTypeAndKind(m.data) - ) + reflectInfo := utils.OriginTypeAndKind(m.data) switch reflectInfo.OriginKind { case reflect.Map, reflect.Struct: dataMap := ConvertDataForTableRecord(m.data) diff --git a/database/gdb/gdb_model_utility.go b/database/gdb/gdb_model_utility.go index 1d0914e0a..02e307396 100644 --- a/database/gdb/gdb_model_utility.go +++ b/database/gdb/gdb_model_utility.go @@ -17,6 +17,15 @@ import ( "github.com/gogf/gf/v2/util/gutil" ) +// QuoteWord checks given string `s` a word, +// if true it quotes `s` with security chars of the database +// and returns the quoted string; or else it returns `s` without any change. +// +// The meaning of a `word` can be considered as a column name. +func (m *Model) QuoteWord(s string) string { + return m.db.GetCore().QuoteWord(s) +} + // TableFields retrieves and returns the fields information of specified table of current // schema. // @@ -46,7 +55,7 @@ func (m *Model) getModel() *Model { // mappingAndFilterToTableFields mappings and changes given field name to really table field name. // Eg: // ID -> id -// NICK_Name -> nickname +// NICK_Name -> nickname. func (m *Model) mappingAndFilterToTableFields(fields []string, filter bool) []string { fieldsMap, err := m.TableFields(m.tablesInit) if err != nil || len(fieldsMap) == 0 { @@ -57,7 +66,7 @@ func (m *Model) mappingAndFilterToTableFields(fields []string, filter bool) []st outputFieldsArray = make([]string, 0, len(inputFieldsArray)) ) fieldsKeyMap := make(map[string]interface{}, len(fieldsMap)) - for k, _ := range fieldsMap { + for k := range fieldsMap { fieldsKeyMap[k] = nil } for _, field := range inputFieldsArray { @@ -87,8 +96,12 @@ func (m *Model) filterDataForInsertOrUpdate(data interface{}) (interface{}, erro var err error switch value := data.(type) { case List: + var omitEmpty bool + if m.option&optionOmitNilDataList > 0 { + omitEmpty = true + } for k, item := range value { - value[k], err = m.doMappingAndFilterForInsertOrUpdateDataMap(item, false) + value[k], err = m.doMappingAndFilterForInsertOrUpdateDataMap(item, omitEmpty) if err != nil { return nil, err } diff --git a/database/gdb/gdb_model_where.go b/database/gdb/gdb_model_where.go new file mode 100644 index 000000000..3a123c71e --- /dev/null +++ b/database/gdb/gdb_model_where.go @@ -0,0 +1,137 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +package gdb + +import ( + "fmt" + + "github.com/gogf/gf/v2/text/gstr" +) + +// Where sets the condition statement for the model. The parameter `where` can be type of +// string/map/gmap/slice/struct/*struct, etc. Note that, if it's called more than one times, +// multiple conditions will be joined into where statement using "AND". +// Eg: +// Where("uid=10000") +// Where("uid", 10000) +// Where("money>? AND name like ?", 99999, "vip_%") +// Where("uid", 1).Where("name", "john") +// Where("status IN (?)", g.Slice{1,2,3}) +// Where("age IN(?,?)", 18, 50) +// Where(User{ Id : 1, UserName : "john"}). +func (m *Model) Where(where interface{}, args ...interface{}) *Model { + model := m.getModel() + if model.whereHolder == nil { + model.whereHolder = make([]ModelWhereHolder, 0) + } + model.whereHolder = append(model.whereHolder, ModelWhereHolder{ + Operator: whereHolderOperatorWhere, + Where: where, + Args: args, + }) + return model +} + +// WherePri does the same logic as Model.Where except that if the parameter `where` +// is a single condition like int/string/float/slice, it treats the condition as the primary +// key value. That is, if primary key is "id" and given `where` parameter as "123", the +// WherePri function treats the condition as "id=123", but Model.Where treats the condition +// as string "123". +func (m *Model) WherePri(where interface{}, args ...interface{}) *Model { + if len(args) > 0 { + return m.Where(where, args...) + } + newWhere := GetPrimaryKeyCondition(m.getPrimaryKey(), where) + return m.Where(newWhere[0], newWhere[1:]...) +} + +// Wheref builds condition string using fmt.Sprintf and arguments. +// 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. +// Eg: +// Wheref(`amount WHERE `amount`<100 and status='paid' +// Wheref(`amount<%d and status=%s`, 100, "paid") => WHERE `amount`<100 and status='paid' +func (m *Model) Wheref(format string, args ...interface{}) *Model { + var ( + placeHolderCount = gstr.Count(format, "?") + conditionStr = fmt.Sprintf(format, args[:len(args)-placeHolderCount]...) + ) + return m.Where(conditionStr, args[len(args)-placeHolderCount:]...) +} + +// WhereLT builds `column < value` statement. +func (m *Model) WhereLT(column string, value interface{}) *Model { + return m.Wheref(`%s < ?`, column, value) +} + +// WhereLTE builds `column <= value` statement. +func (m *Model) WhereLTE(column string, value interface{}) *Model { + return m.Wheref(`%s <= ?`, column, value) +} + +// WhereGT builds `column > value` statement. +func (m *Model) WhereGT(column string, value interface{}) *Model { + return m.Wheref(`%s > ?`, column, value) +} + +// WhereGTE builds `column >= value` statement. +func (m *Model) WhereGTE(column string, value interface{}) *Model { + return m.Wheref(`%s >= ?`, column, value) +} + +// WhereBetween builds `column BETWEEN min AND max` statement. +func (m *Model) WhereBetween(column string, min, max interface{}) *Model { + return m.Wheref(`%s BETWEEN ? AND ?`, m.QuoteWord(column), min, max) +} + +// WhereLike builds `column LIKE like` statement. +func (m *Model) WhereLike(column string, like interface{}) *Model { + return m.Wheref(`%s LIKE ?`, m.QuoteWord(column), like) +} + +// WhereIn builds `column IN (in)` statement. +func (m *Model) WhereIn(column string, in interface{}) *Model { + return m.Wheref(`%s IN (?)`, m.QuoteWord(column), in) +} + +// WhereNull builds `columns[0] IS NULL AND columns[1] IS NULL ...` statement. +func (m *Model) WhereNull(columns ...string) *Model { + model := m + for _, column := range columns { + model = m.Wheref(`%s IS NULL`, m.QuoteWord(column)) + } + return model +} + +// WhereNotBetween builds `column NOT BETWEEN min AND max` statement. +func (m *Model) WhereNotBetween(column string, min, max interface{}) *Model { + return m.Wheref(`%s NOT BETWEEN ? AND ?`, m.QuoteWord(column), min, max) +} + +// WhereNotLike builds `column NOT LIKE like` statement. +func (m *Model) WhereNotLike(column string, like interface{}) *Model { + return m.Wheref(`%s NOT LIKE ?`, m.QuoteWord(column), like) +} + +// WhereNot builds `column != value` statement. +func (m *Model) WhereNot(column string, value interface{}) *Model { + return m.Wheref(`%s != ?`, m.QuoteWord(column), value) +} + +// WhereNotIn builds `column NOT IN (in)` statement. +func (m *Model) WhereNotIn(column string, in interface{}) *Model { + return m.Wheref(`%s NOT IN (?)`, m.QuoteWord(column), in) +} + +// WhereNotNull builds `columns[0] IS NOT NULL AND columns[1] IS NOT NULL ...` statement. +func (m *Model) WhereNotNull(columns ...string) *Model { + model := m + for _, column := range columns { + model = m.Wheref(`%s IS NOT NULL`, m.QuoteWord(column)) + } + return model +} diff --git a/database/gdb/gdb_model_where_prefix.go b/database/gdb/gdb_model_where_prefix.go new file mode 100644 index 000000000..a8cc761db --- /dev/null +++ b/database/gdb/gdb_model_where_prefix.go @@ -0,0 +1,98 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +package gdb + +// WherePrefix performs as Where, but it adds prefix to each field in where statement. +// Eg: +// WherePrefix("order", "status", "paid") => WHERE `order`.`status`='paid' +// WherePrefix("order", struct{Status:"paid", "channel":"bank"}) => WHERE `order`.`status`='paid' AND `order`.`channel`='bank' +func (m *Model) WherePrefix(prefix string, where interface{}, args ...interface{}) *Model { + model := m.getModel() + if model.whereHolder == nil { + model.whereHolder = make([]ModelWhereHolder, 0) + } + model.whereHolder = append(model.whereHolder, ModelWhereHolder{ + Operator: whereHolderOperatorWhere, + Where: where, + Args: args, + Prefix: prefix, + }) + return model +} + +// WherePrefixLT builds `prefix.column < value` statement. +func (m *Model) WherePrefixLT(prefix string, column string, value interface{}) *Model { + return m.Wheref(`%s.%s < ?`, m.QuoteWord(prefix), m.QuoteWord(column), value) +} + +// WherePrefixLTE builds `prefix.column <= value` statement. +func (m *Model) WherePrefixLTE(prefix string, column string, value interface{}) *Model { + return m.Wheref(`%s.%s <= ?`, m.QuoteWord(prefix), m.QuoteWord(column), value) +} + +// WherePrefixGT builds `prefix.column > value` statement. +func (m *Model) WherePrefixGT(prefix string, column string, value interface{}) *Model { + return m.Wheref(`%s.%s > ?`, m.QuoteWord(prefix), m.QuoteWord(column), value) +} + +// WherePrefixGTE builds `prefix.column >= value` statement. +func (m *Model) WherePrefixGTE(prefix string, column string, value interface{}) *Model { + return m.Wheref(`%s.%s >= ?`, m.QuoteWord(prefix), m.QuoteWord(column), value) +} + +// WherePrefixBetween builds `prefix.column BETWEEN min AND max` statement. +func (m *Model) WherePrefixBetween(prefix string, column string, min, max interface{}) *Model { + return m.Wheref(`%s.%s BETWEEN ? AND ?`, m.QuoteWord(prefix), m.QuoteWord(column), min, max) +} + +// WherePrefixLike builds `prefix.column LIKE like` statement. +func (m *Model) WherePrefixLike(prefix string, column string, like interface{}) *Model { + return m.Wheref(`%s.%s LIKE ?`, m.QuoteWord(prefix), m.QuoteWord(column), like) +} + +// WherePrefixIn builds `prefix.column IN (in)` statement. +func (m *Model) WherePrefixIn(prefix string, column string, in interface{}) *Model { + return m.Wheref(`%s.%s IN (?)`, m.QuoteWord(prefix), m.QuoteWord(column), in) +} + +// WherePrefixNull builds `prefix.columns[0] IS NULL AND prefix.columns[1] IS NULL ...` statement. +func (m *Model) WherePrefixNull(prefix string, columns ...string) *Model { + model := m + for _, column := range columns { + model = m.Wheref(`%s.%s IS NULL`, m.QuoteWord(prefix), m.QuoteWord(column)) + } + return model +} + +// WherePrefixNotBetween builds `prefix.column NOT BETWEEN min AND max` statement. +func (m *Model) WherePrefixNotBetween(prefix string, column string, min, max interface{}) *Model { + return m.Wheref(`%s.%s NOT BETWEEN ? AND ?`, m.QuoteWord(prefix), m.QuoteWord(column), min, max) +} + +// WherePrefixNotLike builds `prefix.column NOT LIKE like` statement. +func (m *Model) WherePrefixNotLike(prefix string, column string, like interface{}) *Model { + return m.Wheref(`%s.%s NOT LIKE ?`, m.QuoteWord(prefix), m.QuoteWord(column), like) +} + +// WherePrefixNot builds `prefix.column != value` statement. +func (m *Model) WherePrefixNot(prefix string, column string, value interface{}) *Model { + return m.Wheref(`%s.%s != ?`, m.QuoteWord(prefix), m.QuoteWord(column), value) +} + +// WherePrefixNotIn builds `prefix.column NOT IN (in)` statement. +func (m *Model) WherePrefixNotIn(prefix string, column string, in interface{}) *Model { + return m.Wheref(`%s.%s NOT IN (?)`, m.QuoteWord(prefix), m.QuoteWord(column), in) +} + +// WherePrefixNotNull builds `prefix.columns[0] IS NOT NULL AND prefix.columns[1] IS NOT NULL ...` statement. +func (m *Model) WherePrefixNotNull(prefix string, columns ...string) *Model { + model := m + for _, column := range columns { + model = m.Wheref(`%s.%s IS NOT NULL`, m.QuoteWord(prefix), m.QuoteWord(column)) + } + return model +} diff --git a/database/gdb/gdb_model_whereor.go b/database/gdb/gdb_model_whereor.go new file mode 100644 index 000000000..3b0016f45 --- /dev/null +++ b/database/gdb/gdb_model_whereor.go @@ -0,0 +1,107 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +package gdb + +import ( + "fmt" + + "github.com/gogf/gf/v2/text/gstr" +) + +// WhereOr adds "OR" condition to the where statement. +func (m *Model) WhereOr(where interface{}, args ...interface{}) *Model { + model := m.getModel() + if model.whereHolder == nil { + model.whereHolder = make([]ModelWhereHolder, 0) + } + model.whereHolder = append(model.whereHolder, ModelWhereHolder{ + Operator: whereHolderOperatorOr, + Where: where, + Args: args, + }) + return model +} + +// WhereOrf builds `OR` condition string using fmt.Sprintf and arguments. +// Eg: +// WhereOrf(`amount WHERE xxx OR `amount`<100 and status='paid' +// WhereOrf(`amount<%d and status=%s`, 100, "paid") => WHERE xxx OR `amount`<100 and status='paid' +func (m *Model) WhereOrf(format string, args ...interface{}) *Model { + var ( + placeHolderCount = gstr.Count(format, "?") + conditionStr = fmt.Sprintf(format, args[:len(args)-placeHolderCount]...) + ) + return m.WhereOr(conditionStr, args[len(args)-placeHolderCount:]...) +} + +// WhereOrLT builds `column < value` statement in `OR` conditions.. +func (m *Model) WhereOrLT(column string, value interface{}) *Model { + return m.WhereOrf(`%s < ?`, column, value) +} + +// WhereOrLTE builds `column <= value` statement in `OR` conditions.. +func (m *Model) WhereOrLTE(column string, value interface{}) *Model { + return m.WhereOrf(`%s <= ?`, column, value) +} + +// WhereOrGT builds `column > value` statement in `OR` conditions.. +func (m *Model) WhereOrGT(column string, value interface{}) *Model { + return m.WhereOrf(`%s > ?`, column, value) +} + +// WhereOrGTE builds `column >= value` statement in `OR` conditions.. +func (m *Model) WhereOrGTE(column string, value interface{}) *Model { + return m.WhereOrf(`%s >= ?`, column, value) +} + +// WhereOrBetween builds `column BETWEEN min AND max` statement in `OR` conditions. +func (m *Model) WhereOrBetween(column string, min, max interface{}) *Model { + return m.WhereOrf(`%s BETWEEN ? AND ?`, m.QuoteWord(column), min, max) +} + +// WhereOrLike builds `column LIKE like` statement in `OR` conditions. +func (m *Model) WhereOrLike(column string, like interface{}) *Model { + return m.WhereOrf(`%s LIKE ?`, m.QuoteWord(column), like) +} + +// WhereOrIn builds `column IN (in)` statement in `OR` conditions. +func (m *Model) WhereOrIn(column string, in interface{}) *Model { + return m.WhereOrf(`%s IN (?)`, m.QuoteWord(column), in) +} + +// WhereOrNull builds `columns[0] IS NULL OR columns[1] IS NULL ...` statement in `OR` conditions. +func (m *Model) WhereOrNull(columns ...string) *Model { + model := m + for _, column := range columns { + model = m.WhereOrf(`%s IS NULL`, m.QuoteWord(column)) + } + return model +} + +// WhereOrNotBetween builds `column NOT BETWEEN min AND max` statement in `OR` conditions. +func (m *Model) WhereOrNotBetween(column string, min, max interface{}) *Model { + return m.WhereOrf(`%s NOT BETWEEN ? AND ?`, m.QuoteWord(column), min, max) +} + +// WhereOrNotLike builds `column NOT LIKE like` statement in `OR` conditions. +func (m *Model) WhereOrNotLike(column string, like interface{}) *Model { + return m.WhereOrf(`%s NOT LIKE ?`, m.QuoteWord(column), like) +} + +// WhereOrNotIn builds `column NOT IN (in)` statement. +func (m *Model) WhereOrNotIn(column string, in interface{}) *Model { + return m.WhereOrf(`%s NOT IN (?)`, m.QuoteWord(column), in) +} + +// WhereOrNotNull builds `columns[0] IS NOT NULL OR columns[1] IS NOT NULL ...` statement in `OR` conditions. +func (m *Model) WhereOrNotNull(columns ...string) *Model { + model := m + for _, column := range columns { + model = m.WhereOrf(`%s IS NOT NULL`, m.QuoteWord(column)) + } + return model +} diff --git a/database/gdb/gdb_model_whereor_prefix.go b/database/gdb/gdb_model_whereor_prefix.go new file mode 100644 index 000000000..74189a807 --- /dev/null +++ b/database/gdb/gdb_model_whereor_prefix.go @@ -0,0 +1,93 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +package gdb + +// WhereOrPrefix performs as WhereOr, but it adds prefix to each field in where statement. +// Eg: +// WhereOrPrefix("order", "status", "paid") => WHERE xxx OR (`order`.`status`='paid') +// WhereOrPrefix("order", struct{Status:"paid", "channel":"bank"}) => WHERE xxx OR (`order`.`status`='paid' AND `order`.`channel`='bank') +func (m *Model) WhereOrPrefix(prefix string, where interface{}, args ...interface{}) *Model { + model := m.getModel() + if model.whereHolder == nil { + model.whereHolder = make([]ModelWhereHolder, 0) + } + model.whereHolder = append(model.whereHolder, ModelWhereHolder{ + Operator: whereHolderOperatorOr, + Where: where, + Args: args, + Prefix: prefix, + }) + return model +} + +// WhereOrPrefixLT builds `prefix.column < value` statement in `OR` conditions.. +func (m *Model) WhereOrPrefixLT(prefix string, column string, value interface{}) *Model { + return m.WhereOrf(`%s.%s < ?`, m.QuoteWord(prefix), m.QuoteWord(column), value) +} + +// WhereOrPrefixLTE builds `prefix.column <= value` statement in `OR` conditions.. +func (m *Model) WhereOrPrefixLTE(prefix string, column string, value interface{}) *Model { + return m.WhereOrf(`%s.%s <= ?`, m.QuoteWord(prefix), m.QuoteWord(column), value) +} + +// WhereOrPrefixGT builds `prefix.column > value` statement in `OR` conditions.. +func (m *Model) WhereOrPrefixGT(prefix string, column string, value interface{}) *Model { + return m.WhereOrf(`%s.%s > ?`, m.QuoteWord(prefix), m.QuoteWord(column), value) +} + +// WhereOrPrefixGTE builds `prefix.column >= value` statement in `OR` conditions.. +func (m *Model) WhereOrPrefixGTE(prefix string, column string, value interface{}) *Model { + return m.WhereOrf(`%s.%s >= ?`, m.QuoteWord(prefix), m.QuoteWord(column), value) +} + +// WhereOrPrefixBetween builds `prefix.column BETWEEN min AND max` statement in `OR` conditions. +func (m *Model) WhereOrPrefixBetween(prefix string, column string, min, max interface{}) *Model { + return m.WhereOrf(`%s.%s BETWEEN ? AND ?`, m.QuoteWord(prefix), m.QuoteWord(column), min, max) +} + +// WhereOrPrefixLike builds `prefix.column LIKE like` statement in `OR` conditions. +func (m *Model) WhereOrPrefixLike(prefix string, column string, like interface{}) *Model { + return m.WhereOrf(`%s.%s LIKE ?`, m.QuoteWord(prefix), m.QuoteWord(column), like) +} + +// WhereOrPrefixIn builds `prefix.column IN (in)` statement in `OR` conditions. +func (m *Model) WhereOrPrefixIn(prefix string, column string, in interface{}) *Model { + return m.WhereOrf(`%s.%s IN (?)`, m.QuoteWord(prefix), m.QuoteWord(column), in) +} + +// WhereOrPrefixNull builds `prefix.columns[0] IS NULL OR prefix.columns[1] IS NULL ...` statement in `OR` conditions. +func (m *Model) WhereOrPrefixNull(prefix string, columns ...string) *Model { + model := m + for _, column := range columns { + model = m.WhereOrf(`%s.%s IS NULL`, m.QuoteWord(prefix), m.QuoteWord(column)) + } + return model +} + +// WhereOrPrefixNotBetween builds `prefix.column NOT BETWEEN min AND max` statement in `OR` conditions. +func (m *Model) WhereOrPrefixNotBetween(prefix string, column string, min, max interface{}) *Model { + return m.WhereOrf(`%s.%s NOT BETWEEN ? AND ?`, m.QuoteWord(prefix), m.QuoteWord(column), min, max) +} + +// WhereOrPrefixNotLike builds `prefix.column NOT LIKE like` statement in `OR` conditions. +func (m *Model) WhereOrPrefixNotLike(prefix string, column string, like interface{}) *Model { + return m.WhereOrf(`%s.%s NOT LIKE ?`, m.QuoteWord(prefix), m.QuoteWord(column), like) +} + +// WhereOrPrefixNotIn builds `prefix.column NOT IN (in)` statement. +func (m *Model) WhereOrPrefixNotIn(prefix string, column string, in interface{}) *Model { + return m.WhereOrf(`%s.%s NOT IN (?)`, m.QuoteWord(prefix), m.QuoteWord(column), in) +} + +// WhereOrPrefixNotNull builds `prefix.columns[0] IS NOT NULL OR prefix.columns[1] IS NOT NULL ...` statement in `OR` conditions. +func (m *Model) WhereOrPrefixNotNull(prefix string, columns ...string) *Model { + model := m + for _, column := range columns { + model = m.WhereOrf(`%s.%s IS NOT NULL`, m.QuoteWord(prefix), m.QuoteWord(column)) + } + return model +} diff --git a/database/gdb/gdb_model_with.go b/database/gdb/gdb_model_with.go index e4a7280b8..8be613401 100644 --- a/database/gdb/gdb_model_with.go +++ b/database/gdb/gdb_model_with.go @@ -9,9 +9,9 @@ package gdb import ( "database/sql" "fmt" - "github.com/gogf/gf/v2/errors/gcode" "reflect" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/structs" "github.com/gogf/gf/v2/internal/utils" @@ -229,7 +229,7 @@ func (m *Model) doWithScanStructs(pointer interface{}) error { relatedTargetValue interface{} ) // Find the value slice of related attribute from `pointer`. - for attributeName, _ := range currentStructFieldMap { + for attributeName := range currentStructFieldMap { if utils.EqualFoldWithoutChars(attributeName, relatedTargetName) { relatedTargetValue = ListItemValuesUnique(pointer, attributeName) break diff --git a/database/gdb/gdb_schema.go b/database/gdb/gdb_schema.go index d1c3242d3..4cf7c496c 100644 --- a/database/gdb/gdb_schema.go +++ b/database/gdb/gdb_schema.go @@ -32,7 +32,7 @@ func (tx *TX) Schema(schema string) *Schema { // Model creates and returns a new ORM model. // The parameter `tables` can be more than one table names, like : -// "user", "user u", "user, user_detail", "user u, user_detail ud" +// "user", "user u", "user, user_detail", "user u, user_detail ud". func (s *Schema) Model(table string) *Model { var m *Model if s.tx != nil { diff --git a/database/gdb/gdb_statement.go b/database/gdb/gdb_statement.go index 59ed63fc1..3db6dd43a 100644 --- a/database/gdb/gdb_statement.go +++ b/database/gdb/gdb_statement.go @@ -9,8 +9,8 @@ package gdb import ( "context" "database/sql" - "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/os/gtime" ) diff --git a/database/gdb/gdb_type_record.go b/database/gdb/gdb_type_record.go index 2af2eb409..2b14c5375 100644 --- a/database/gdb/gdb_type_record.go +++ b/database/gdb/gdb_type_record.go @@ -8,6 +8,7 @@ package gdb import ( "database/sql" + "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/encoding/gjson" "github.com/gogf/gf/v2/internal/empty" diff --git a/database/gdb/gdb_type_result.go b/database/gdb/gdb_type_result.go index 7b86b14e4..062381a48 100644 --- a/database/gdb/gdb_type_result.go +++ b/database/gdb/gdb_type_result.go @@ -7,10 +7,11 @@ package gdb import ( + "math" + "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/encoding/gjson" "github.com/gogf/gf/v2/util/gconv" - "math" ) // IsEmpty checks and returns whether `r` is empty. @@ -82,7 +83,7 @@ func (r Result) Array(field ...string) []Value { if len(field) > 0 && field[0] != "" { key = field[0] } else { - for k, _ := range r[0] { + for k := range r[0] { key = k break } diff --git a/database/gdb/gdb_type_result_scanlist.go b/database/gdb/gdb_type_result_scanlist.go index 0e76b6c61..95d0712ca 100644 --- a/database/gdb/gdb_type_result_scanlist.go +++ b/database/gdb/gdb_type_result_scanlist.go @@ -8,13 +8,14 @@ package gdb import ( "database/sql" + "reflect" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/structs" "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/gutil" - "reflect" ) // ScanList converts `r` to struct slice which contains other complex struct attributes. @@ -289,12 +290,10 @@ func doScanList(model *Model, result Result, structSlicePointer interface{}, bin if relationFields != "" && !relationBindToFieldNameChecked { relationFromAttrField = relationFromAttrValue.FieldByName(relationBindToFieldName) if !relationFromAttrField.IsValid() { - var ( - filedMap, _ = structs.FieldMap(structs.FieldMapInput{ - Pointer: relationFromAttrValue, - RecursiveOption: structs.RecursiveOptionEmbeddedNoTag, - }) - ) + filedMap, _ := structs.FieldMap(structs.FieldMapInput{ + Pointer: relationFromAttrValue, + RecursiveOption: structs.RecursiveOptionEmbeddedNoTag, + }) if key, _ := gutil.MapPossibleItemByKey(gconv.Map(filedMap), relationBindToFieldName); key == "" { return gerror.NewCodef( gcode.CodeInvalidParameter, diff --git a/database/gdb/gdb_z_init_test.go b/database/gdb/gdb_z_init_test.go index 9c94207e4..22b537ba3 100644 --- a/database/gdb/gdb_z_init_test.go +++ b/database/gdb/gdb_z_init_test.go @@ -9,11 +9,11 @@ package gdb_test import ( "context" "fmt" + "github.com/gogf/gf/v2/container/garray" + "github.com/gogf/gf/v2/database/gdb" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gcmd" - - "github.com/gogf/gf/v2/database/gdb" "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" ) diff --git a/database/gdb/gdb_z_mysql_basic_test.go b/database/gdb/gdb_z_mysql_basic_test.go index 85fff7d61..29fc7679f 100644 --- a/database/gdb/gdb_z_mysql_basic_test.go +++ b/database/gdb/gdb_z_mysql_basic_test.go @@ -7,10 +7,12 @@ package gdb_test import ( + "testing" + "github.com/go-sql-driver/mysql" + "github.com/gogf/gf/v2/database/gdb" "github.com/gogf/gf/v2/test/gtest" - "testing" ) func Test_Instance(t *testing.T) { diff --git a/database/gdb/gdb_z_mysql_method_test.go b/database/gdb/gdb_z_mysql_core_test.go similarity index 94% rename from database/gdb/gdb_z_mysql_method_test.go rename to database/gdb/gdb_z_mysql_core_test.go index ae8f7a383..750645e86 100644 --- a/database/gdb/gdb_z_mysql_method_test.go +++ b/database/gdb/gdb_z_mysql_core_test.go @@ -9,18 +9,17 @@ package gdb_test import ( "context" "fmt" - "github.com/gogf/gf/v2/container/garray" - "github.com/gogf/gf/v2/text/gstr" "testing" "time" + "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/database/gdb" "github.com/gogf/gf/v2/encoding/gjson" "github.com/gogf/gf/v2/encoding/gxml" - "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/text/gstr" ) func Test_DB_Ping(t *testing.T) { @@ -46,7 +45,6 @@ func Test_DB_Query(t *testing.T) { _, err = db.Query(ctx, "ERROR") t.AssertNE(err, nil) }) - } func Test_DB_Exec(t *testing.T) { @@ -57,7 +55,6 @@ func Test_DB_Exec(t *testing.T) { _, err = db.Exec(ctx, "ERROR") t.AssertNE(err, nil) }) - } func Test_DB_Prepare(t *testing.T) { @@ -274,7 +271,7 @@ func Test_DB_Upadte_KeyFieldNameMapping(t *testing.T) { } // This is no longer used as the filter feature is automatically enabled from GoFrame v1.16.0. -//func Test_DB_Insert_KeyFieldNameMapping_Error(t *testing.T) { +// func Test_DB_Insert_KeyFieldNameMapping_Error(t *testing.T) { // table := createTable() // defer dropTable(table) // @@ -297,7 +294,7 @@ func Test_DB_Upadte_KeyFieldNameMapping(t *testing.T) { // _, err := db.Insert(ctx, table, data) // t.AssertNE(err, nil) // }) -//} +// } func Test_DB_InsertIgnore(t *testing.T) { table := createInitTable() @@ -392,7 +389,6 @@ func Test_DB_BatchInsert(t *testing.T) { n, _ := result.RowsAffected() t.Assert(n, 1) }) - } func Test_DB_BatchInsert_Struct(t *testing.T) { @@ -820,7 +816,7 @@ func Test_DB_ToJson(t *testing.T) { gtest.Fatal(err) } - //ToJson + // ToJson resultJson, err := gjson.LoadContent(result.Json()) if err != nil { gtest.Fatal(err) @@ -925,12 +921,10 @@ func Test_DB_ToXml(t *testing.T) { } else { gtest.Fatal("FAIL") } - }) } func Test_DB_ToStringMap(t *testing.T) { - table := createInitTable() defer dropTable(table) _, err := db.Update(ctx, table, "create_time='2010-10-10 00:00:01'", "id=?", 1) @@ -966,7 +960,6 @@ func Test_DB_ToStringMap(t *testing.T) { } func Test_DB_ToIntMap(t *testing.T) { - table := createInitTable() defer dropTable(table) _, err := db.Update(ctx, table, "create_time='2010-10-10 00:00:01'", "id=?", 1) @@ -1035,7 +1028,6 @@ func Test_DB_ToUintMap(t *testing.T) { t.Assert(t_users[0].Password, resultUintMap[uint(id)]["password"]) t.Assert(t_users[0].NickName, resultUintMap[uint(id)]["nickname"]) t.Assert(t_users[0].CreateTime, resultUintMap[uint(id)]["create_time"]) - }) } @@ -1073,7 +1065,6 @@ func Test_DB_ToStringRecord(t *testing.T) { t.Assert(t_users[0].Password, resultStringRecord[ids]["password"].String()) t.Assert(t_users[0].NickName, resultStringRecord[ids]["nickname"].String()) t.Assert(t_users[0].CreateTime, resultStringRecord[ids]["create_time"].String()) - }) } @@ -1110,7 +1101,6 @@ func Test_DB_ToIntRecord(t *testing.T) { t.Assert(t_users[0].Password, resultIntRecord[id]["password"].String()) t.Assert(t_users[0].NickName, resultIntRecord[id]["nickname"].String()) t.Assert(t_users[0].CreateTime, resultIntRecord[id]["create_time"].String()) - }) } @@ -1302,7 +1292,6 @@ func Test_DB_Prefix(t *testing.T) { t.Assert(e, nil) t.Assert(n, TableSize) }) - } func Test_Model_InnerJoin(t *testing.T) { @@ -1421,7 +1410,7 @@ func Test_Empty_Slice_Argument(t *testing.T) { }) } -// update counter test +// update counter test. func Test_DB_UpdateCounter(t *testing.T) { tableName := "gf_update_counter_test_" + gtime.TimestampNanoStr() _, err := db.Exec(ctx, fmt.Sprintf(` @@ -1502,3 +1491,88 @@ func Test_DB_Ctx_Logger(t *testing.T) { t.AssertNil(err) }) } + +// All types testing. +func Test_Types(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + if _, err := db.Exec(ctx, fmt.Sprintf(` + CREATE TABLE IF NOT EXISTS types ( + id int(10) unsigned NOT NULL AUTO_INCREMENT, + %s blob NOT NULL, + %s binary(8) NOT NULL, + %s date NOT NULL, + %s time NOT NULL, + %s decimal(5,2) NOT NULL, + %s double NOT NULL, + %s bit(2) NOT NULL, + %s tinyint(1) NOT NULL, + %s bool NOT NULL, + PRIMARY KEY (id) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8; + `, + "`blob`", + "`binary`", + "`date`", + "`time`", + "`decimal`", + "`double`", + "`bit`", + "`tinyint`", + "`bool`")); err != nil { + gtest.Error(err) + } + defer dropTable("types") + data := g.Map{ + "id": 1, + "blob": "i love gf", + "binary": []byte("abcdefgh"), + "date": "1880-10-24", + "time": "10:00:01", + "decimal": -123.456, + "double": -123.456, + "bit": 2, + "tinyint": true, + "bool": false, + } + r, err := db.Model("types").Data(data).Insert() + t.AssertNil(err) + n, _ := r.RowsAffected() + t.Assert(n, 1) + + one, err := db.Model("types").One() + t.AssertNil(err) + t.Assert(one["id"].Int(), 1) + t.Assert(one["blob"].String(), data["blob"]) + t.Assert(one["binary"].String(), data["binary"]) + t.Assert(one["date"].String(), data["date"]) + t.Assert(one["time"].String(), `0000-01-01 10:00:01`) + t.Assert(one["decimal"].String(), -123.46) + t.Assert(one["double"].String(), data["double"]) + t.Assert(one["bit"].Int(), data["bit"]) + t.Assert(one["tinyint"].Bool(), data["tinyint"]) + + type T struct { + Id int + Blob []byte + Binary []byte + Date *gtime.Time + Time *gtime.Time + Decimal float64 + Double float64 + Bit int8 + TinyInt bool + } + var obj *T + err = db.Model("types").Scan(&obj) + t.AssertNil(err) + t.Assert(obj.Id, 1) + t.Assert(obj.Blob, data["blob"]) + t.Assert(obj.Binary, data["binary"]) + t.Assert(obj.Date.Format("Y-m-d"), data["date"]) + t.Assert(obj.Time.String(), `0000-01-01 10:00:01`) + t.Assert(obj.Decimal, -123.46) + t.Assert(obj.Double, data["double"]) + t.Assert(obj.Bit, data["bit"]) + t.Assert(obj.TinyInt, data["tinyint"]) + }) +} diff --git a/database/gdb/gdb_z_mysql_ctx_test.go b/database/gdb/gdb_z_mysql_feature_ctx_test.go similarity index 100% rename from database/gdb/gdb_z_mysql_ctx_test.go rename to database/gdb/gdb_z_mysql_feature_ctx_test.go diff --git a/database/gdb/gdb_z_mysql_model_for_dao_test.go b/database/gdb/gdb_z_mysql_feature_model_for_dao_test.go similarity index 67% rename from database/gdb/gdb_z_mysql_model_for_dao_test.go rename to database/gdb/gdb_z_mysql_feature_model_for_dao_test.go index a66f9c7d7..5d4dc7934 100644 --- a/database/gdb/gdb_z_mysql_model_for_dao_test.go +++ b/database/gdb/gdb_z_mysql_feature_model_for_dao_test.go @@ -7,8 +7,10 @@ package gdb_test import ( - "github.com/gogf/gf/v2/test/gtest" "testing" + + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/test/gtest" ) func Test_Model_Insert_Data_ForDao(t *testing.T) { @@ -43,6 +45,53 @@ func Test_Model_Insert_Data_ForDao(t *testing.T) { }) } +func Test_Model_Insert_Data_LIst_ForDao(t *testing.T) { + table := createTable() + defer dropTable(table) + + gtest.C(t, func(t *gtest.T) { + type UserForDao struct { + Id interface{} + Passport interface{} + Password interface{} + Nickname interface{} + CreateTime interface{} + } + data := g.Slice{ + UserForDao{ + Id: 1, + Passport: "user_1", + Password: "pass_1", + }, + UserForDao{ + Id: 2, + Passport: "user_2", + Password: "pass_2", + }, + } + result, err := db.Model(table).Data(data).Insert() + t.AssertNil(err) + n, _ := result.LastInsertId() + t.Assert(n, 2) + + one, err := db.Model(table).WherePri(1).One() + t.AssertNil(err) + t.Assert(one[`id`], `1`) + t.Assert(one[`passport`], `user_1`) + t.Assert(one[`password`], `pass_1`) + t.Assert(one[`nickname`], ``) + t.Assert(one[`create_time`], ``) + + one, err = db.Model(table).WherePri(2).One() + t.AssertNil(err) + t.Assert(one[`id`], `2`) + t.Assert(one[`passport`], `user_2`) + t.Assert(one[`password`], `pass_2`) + t.Assert(one[`nickname`], ``) + t.Assert(one[`create_time`], ``) + }) +} + func Test_Model_Update_Data_ForDao(t *testing.T) { table := createInitTable() defer dropTable(table) diff --git a/database/gdb/gdb_z_mysql_model_join_test.go b/database/gdb/gdb_z_mysql_feature_model_join_test.go similarity index 99% rename from database/gdb/gdb_z_mysql_model_join_test.go rename to database/gdb/gdb_z_mysql_feature_model_join_test.go index 5ffb07ae8..6044911f8 100644 --- a/database/gdb/gdb_z_mysql_model_join_test.go +++ b/database/gdb/gdb_z_mysql_feature_model_join_test.go @@ -7,10 +7,11 @@ package gdb_test import ( + "testing" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" - "testing" ) func Test_Model_LeftJoinOnField(t *testing.T) { diff --git a/database/gdb/gdb_z_mysql_model_struct_test.go b/database/gdb/gdb_z_mysql_feature_model_struct_test.go similarity index 99% rename from database/gdb/gdb_z_mysql_model_struct_test.go rename to database/gdb/gdb_z_mysql_feature_model_struct_test.go index a3bf0a543..78dda93d5 100644 --- a/database/gdb/gdb_z_mysql_model_struct_test.go +++ b/database/gdb/gdb_z_mysql_feature_model_struct_test.go @@ -8,6 +8,9 @@ package gdb_test import ( "database/sql" + "reflect" + "testing" + "github.com/gogf/gf/v2/database/gdb" "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" @@ -16,8 +19,6 @@ import ( "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" - "reflect" - "testing" ) func Test_Model_Embedded_Insert(t *testing.T) { @@ -98,7 +99,6 @@ func Test_Model_Embedded_MapToStruct(t *testing.T) { t.Assert(user.Password, data["password"]) t.Assert(user.Nickname, data["nickname"]) t.Assert(user.CreateTime, data["create_time"]) - }) } @@ -466,7 +466,7 @@ func Test_Scan_AutoFilteringByStructAttributes(t *testing.T) { Id int Passport string } - //db.SetDebug(true) + // db.SetDebug(true) gtest.C(t, func(t *gtest.T) { var user *User err := db.Model(table).OrderAsc("id").Scan(&user) @@ -549,9 +549,7 @@ func Test_Scan_JsonAttributes(t *testing.T) { Passport string } - var ( - table = "jfy_gift" - ) + table := "jfy_gift" array := gstr.SplitAndTrim(gtest.TestDataContent(`issue1380.sql`), ";") for _, v := range array { if _, err := db.Exec(ctx, v); err != nil { diff --git a/database/gdb/gdb_z_mysql_model_subquery_test.go b/database/gdb/gdb_z_mysql_feature_model_subquery_test.go similarity index 100% rename from database/gdb/gdb_z_mysql_model_subquery_test.go rename to database/gdb/gdb_z_mysql_feature_model_subquery_test.go index 1c2dcb4b0..6eb9d4129 100644 --- a/database/gdb/gdb_z_mysql_model_subquery_test.go +++ b/database/gdb/gdb_z_mysql_feature_model_subquery_test.go @@ -7,9 +7,9 @@ package gdb_test import ( - "github.com/gogf/gf/v2/frame/g" "testing" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/test/gtest" ) diff --git a/database/gdb/gdb_z_mysql_raw_type_test.go b/database/gdb/gdb_z_mysql_feature_raw_type_test.go similarity index 100% rename from database/gdb/gdb_z_mysql_raw_type_test.go rename to database/gdb/gdb_z_mysql_feature_raw_type_test.go index 9b38adf43..3ce8f556b 100644 --- a/database/gdb/gdb_z_mysql_raw_type_test.go +++ b/database/gdb/gdb_z_mysql_feature_raw_type_test.go @@ -7,10 +7,10 @@ package gdb_test import ( - "github.com/gogf/gf/v2/frame/g" "testing" "github.com/gogf/gf/v2/database/gdb" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/test/gtest" ) diff --git a/database/gdb/gdb_z_mysql_association_scanlist_test.go b/database/gdb/gdb_z_mysql_feature_scanlist_test.go similarity index 99% rename from database/gdb/gdb_z_mysql_association_scanlist_test.go rename to database/gdb/gdb_z_mysql_feature_scanlist_test.go index dee305cfc..a167e0a6d 100644 --- a/database/gdb/gdb_z_mysql_association_scanlist_test.go +++ b/database/gdb/gdb_z_mysql_feature_scanlist_test.go @@ -13,10 +13,9 @@ import ( "github.com/gogf/gf/v2/database/gdb" "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" - "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gconv" ) func Test_Table_Relation_One(t *testing.T) { @@ -1368,19 +1367,19 @@ CREATE TABLE %s ( }) t.AssertNil(err) // Detail. - //_, err = db.Insert(ctx, tableUserDetail, g.Map{ + // _, err = db.Insert(ctx, tableUserDetail, g.Map{ // "uid": i, // "address": fmt.Sprintf(`address_%d`, i), - //}) - //t.AssertNil(err) + // }) + // t.AssertNil(err) // Scores. - //for j := 1; j <= 5; j++ { + // for j := 1; j <= 5; j++ { // _, err = db.Insert(ctx, tableUserScores, g.Map{ // "uid": i, // "score": j, // }) // t.AssertNil(err) - //} + // } } }) @@ -1776,7 +1775,7 @@ CREATE TABLE %s ( t.Assert(gconv.Map(all.MapKeyValue("uid")["3"].Slice()[4])["uid"], 3) t.Assert(gconv.Map(all.MapKeyValue("uid")["3"].Slice()[4])["score"], 5) }) - db.SetDebug(true) + // Result ScanList with struct elements and pointer attributes. gtest.C(t, func(t *gtest.T) { var users []Entity diff --git a/database/gdb/gdb_z_mysql_time_maintain_test.go b/database/gdb/gdb_z_mysql_feature_time_maintain_test.go similarity index 99% rename from database/gdb/gdb_z_mysql_time_maintain_test.go rename to database/gdb/gdb_z_mysql_feature_time_maintain_test.go index 78c9886f7..77ff68a21 100644 --- a/database/gdb/gdb_z_mysql_time_maintain_test.go +++ b/database/gdb/gdb_z_mysql_feature_time_maintain_test.go @@ -8,16 +8,15 @@ package gdb_test import ( "fmt" - "github.com/gogf/gf/v2/os/gtime" "testing" "time" "github.com/gogf/gf/v2/frame/g" - + "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" ) -// CreateAt/UpdateAt/DeleteAt +// CreateAt/UpdateAt/DeleteAt. func Test_SoftCreateUpdateDeleteTime(t *testing.T) { table := "time_test_table_" + gtime.TimestampNanoStr() if _, err := db.Exec(ctx, fmt.Sprintf(` @@ -151,7 +150,7 @@ CREATE TABLE %s ( }) } -// CreatedAt/UpdatedAt/DeletedAt +// CreatedAt/UpdatedAt/DeletedAt. func Test_SoftCreatedUpdatedDeletedTime_Map(t *testing.T) { table := "time_test_table_" + gtime.TimestampNanoStr() if _, err := db.Exec(ctx, fmt.Sprintf(` @@ -285,7 +284,7 @@ CREATE TABLE %s ( }) } -// CreatedAt/UpdatedAt/DeletedAt +// CreatedAt/UpdatedAt/DeletedAt. func Test_SoftCreatedUpdatedDeletedTime_Struct(t *testing.T) { table := "time_test_table_" + gtime.TimestampNanoStr() if _, err := db.Exec(ctx, fmt.Sprintf(` @@ -566,7 +565,7 @@ CREATE TABLE %s ( defer dropTable(table2) gtest.C(t, func(t *gtest.T) { - //db.SetDebug(true) + // db.SetDebug(true) dataInsert1 := g.Map{ "id": 1, "name": "name_1", @@ -620,7 +619,7 @@ CREATE TABLE %s ( gtest.Error(err) } defer dropTable(table) - //db.SetDebug(true) + // db.SetDebug(true) // Add datas. gtest.C(t, func(t *gtest.T) { for i := 1; i <= 10; i++ { @@ -663,8 +662,8 @@ CREATE TABLE %s ( } defer dropTable(table) - //db.SetDebug(true) - //defer db.SetDebug(false) + // db.SetDebug(true) + // defer db.SetDebug(false) type Entity struct { Id uint64 `orm:"id,primary" json:"id"` diff --git a/database/gdb/gdb_z_mysql_union_test.go b/database/gdb/gdb_z_mysql_feature_union_test.go similarity index 100% rename from database/gdb/gdb_z_mysql_union_test.go rename to database/gdb/gdb_z_mysql_feature_union_test.go index fc31aa517..2626be62b 100644 --- a/database/gdb/gdb_z_mysql_union_test.go +++ b/database/gdb/gdb_z_mysql_feature_union_test.go @@ -7,9 +7,9 @@ package gdb_test import ( - "github.com/gogf/gf/v2/frame/g" "testing" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/test/gtest" ) diff --git a/database/gdb/gdb_z_mysql_association_with_test.go b/database/gdb/gdb_z_mysql_feature_with_test.go similarity index 99% rename from database/gdb/gdb_z_mysql_association_with_test.go rename to database/gdb/gdb_z_mysql_feature_with_test.go index bae1adb92..243e83d76 100644 --- a/database/gdb/gdb_z_mysql_association_with_test.go +++ b/database/gdb/gdb_z_mysql_feature_with_test.go @@ -8,13 +8,14 @@ package gdb_test import ( "fmt" + "testing" + "github.com/gogf/gf/v2/debug/gdebug" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gmeta" - "testing" ) /* @@ -1675,7 +1676,7 @@ func Test_Table_Relation_With_MultipleDepends1(t *testing.T) { gtest.C(t, func(t *gtest.T) { var tableA *TableA err := db.Model("table_a").WithAll().Scan(&tableA) - //g.Dump(tableA) + // g.Dump(tableA) t.AssertNil(err) t.AssertNE(tableA, nil) t.Assert(tableA.Id, 1) @@ -1691,7 +1692,7 @@ func Test_Table_Relation_With_MultipleDepends1(t *testing.T) { gtest.C(t, func(t *gtest.T) { var tableA []*TableA err := db.Model("table_a").WithAll().OrderAsc("id").Scan(&tableA) - //g.Dump(tableA) + // g.Dump(tableA) t.AssertNil(err) t.Assert(len(tableA), 2) t.AssertNE(tableA[0].TableB, nil) @@ -1747,7 +1748,7 @@ func Test_Table_Relation_With_MultipleDepends2(t *testing.T) { gtest.C(t, func(t *gtest.T) { var tableA *TableA err := db.Model("table_a").WithAll().Scan(&tableA) - //g.Dump(tableA) + // g.Dump(tableA) t.AssertNil(err) t.AssertNE(tableA, nil) t.Assert(tableA.Id, 1) @@ -1770,7 +1771,7 @@ func Test_Table_Relation_With_MultipleDepends2(t *testing.T) { gtest.C(t, func(t *gtest.T) { var tableA []*TableA err := db.Model("table_a").WithAll().OrderAsc("id").Scan(&tableA) - //g.Dump(tableA) + // g.Dump(tableA) t.AssertNil(err) t.Assert(len(tableA), 2) @@ -1834,7 +1835,7 @@ func Test_Table_Relation_With_MultipleDepends_Embedded(t *testing.T) { gtest.C(t, func(t *gtest.T) { var tableA *TableA err := db.Model("table_a").WithAll().Scan(&tableA) - //g.Dump(tableA) + // g.Dump(tableA) t.AssertNil(err) t.AssertNE(tableA, nil) t.Assert(tableA.Id, 1) @@ -1850,7 +1851,7 @@ func Test_Table_Relation_With_MultipleDepends_Embedded(t *testing.T) { gtest.C(t, func(t *gtest.T) { var tableA []*TableA err := db.Model("table_a").WithAll().OrderAsc("id").Scan(&tableA) - //g.Dump(tableA) + // g.Dump(tableA) t.AssertNil(err) t.Assert(len(tableA), 2) t.AssertNE(tableA[0].TableB, nil) @@ -1870,9 +1871,9 @@ func Test_Table_Relation_With_MultipleDepends_Embedded(t *testing.T) { func Test_Table_Relation_WithAll_Embedded_Meta_NameMatchingRule(t *testing.T) { var ( - tableUser = "user1" - tableUserDetail = "user_detail1" - tableUserScores = "user_scores1" + tableUser = "user100" + tableUserDetail = "user_detail100" + tableUserScores = "user_scores100" ) if _, err := db.Exec(ctx, fmt.Sprintf(` CREATE TABLE IF NOT EXISTS %s ( @@ -1909,13 +1910,13 @@ PRIMARY KEY (id) defer dropTable(tableUserScores) type UserDetail struct { - gmeta.Meta `orm:"table:user_detail1"` + gmeta.Meta `orm:"table:user_detail100"` UserID int `json:"user_id"` Address string `json:"address"` } type UserScores struct { - gmeta.Meta `orm:"table:user_scores1"` + gmeta.Meta `orm:"table:user_scores100"` ID int `json:"id"` UserID int `json:"user_id"` Score int `json:"score"` @@ -1928,7 +1929,7 @@ PRIMARY KEY (id) } type User struct { - gmeta.Meta `orm:"table:user1"` + gmeta.Meta `orm:"table:user100"` UserEmbedded UserDetail UserDetail `orm:"with:user_id=id"` UserScores []*UserScores `orm:"with:user_id=id"` @@ -1959,10 +1960,7 @@ PRIMARY KEY (id) } } - db.SetDebug(true) - defer db.SetDebug(false) - - //gtest.C(t, func(t *gtest.T) { + // gtest.C(t, func(t *gtest.T) { // var user *User // err := db.Model(tableUser).WithAll().Where("id", 3).Scan(&user) // t.AssertNil(err) @@ -1975,7 +1973,7 @@ PRIMARY KEY (id) // t.Assert(user.UserScores[0].Score, 1) // t.Assert(user.UserScores[4].UserID, 3) // t.Assert(user.UserScores[4].Score, 5) - //}) + // }) gtest.C(t, func(t *gtest.T) { var user User err := db.Model(tableUser).WithAll().Where("id", 4).Scan(&user) diff --git a/database/gdb/gdb_z_mysql_internal_test.go b/database/gdb/gdb_z_mysql_internal_test.go index ad90d3b54..2d9228a03 100644 --- a/database/gdb/gdb_z_mysql_internal_test.go +++ b/database/gdb/gdb_z_mysql_internal_test.go @@ -9,11 +9,12 @@ package gdb import ( "context" "fmt" + "testing" + "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/os/gcmd" "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" - "testing" ) const ( @@ -497,7 +498,7 @@ func Test_ScanList_NoRecreate_SliceAttribute_Ptr(t *testing.T) { }, } err = r2.ScanList(&s, "Many", "One", "pid:Id") - //fmt.Printf("%+v", err) + // fmt.Printf("%+v", err) t.AssertNil(err) t.Assert(len(s), 2) t.Assert(s[0].One.Name, "john") @@ -525,7 +526,7 @@ func Test_ScanList_NoRecreate_SliceAttribute_Ptr(t *testing.T) { }, } err = r3.ScanList(&s, "Many", "One", "pid:Id") - //fmt.Printf("%+v", err) + // fmt.Printf("%+v", err) t.AssertNil(err) t.Assert(len(s), 2) t.Assert(s[0].One.Name, "john") @@ -601,7 +602,7 @@ func Test_ScanList_NoRecreate_SliceAttribute_Struct(t *testing.T) { }, } err = r2.ScanList(&s, "Many", "One", "pid:Id") - //fmt.Printf("%+v", err) + // fmt.Printf("%+v", err) t.AssertNil(err) t.Assert(len(s), 2) t.Assert(s[0].One.Name, "john") @@ -629,7 +630,7 @@ func Test_ScanList_NoRecreate_SliceAttribute_Struct(t *testing.T) { }, } err = r3.ScanList(&s, "Many", "One", "pid:Id") - //fmt.Printf("%+v", err) + // fmt.Printf("%+v", err) t.AssertNil(err) t.Assert(len(s), 2) t.Assert(s[0].One.Name, "john") diff --git a/database/gdb/gdb_z_mysql_model_filter_test.go b/database/gdb/gdb_z_mysql_model_filter_test.go deleted file mode 100644 index 5219fd38c..000000000 --- a/database/gdb/gdb_z_mysql_model_filter_test.go +++ /dev/null @@ -1,218 +0,0 @@ -// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. -// -// This Source Code Form is subject to the terms of the MIT License. -// If a copy of the MIT was not distributed with this file, -// You can obtain one at https://github.com/gogf/gf. - -package gdb_test - -import ( - "fmt" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/test/gtest" - "testing" -) - -// Using filter dose not affect the outside value inside function. -func Test_Model_Insert_Filter(t *testing.T) { - // map - gtest.C(t, func(t *gtest.T) { - table := createTable() - defer dropTable(table) - data := g.Map{ - "id": 1, - "uid": 1, - "passport": "t1", - "password": "25d55ad283aa400af464c76d713c07ad", - "nickname": "name_1", - "create_time": gtime.Now().String(), - } - result, err := db.Model(table).Data(data).Insert() - t.AssertNil(err) - n, _ := result.LastInsertId() - t.Assert(n, 1) - - t.Assert(data["uid"], 1) - }) - // slice - gtest.C(t, func(t *gtest.T) { - table := createTable() - defer dropTable(table) - data := g.List{ - g.Map{ - "id": 1, - "uid": 1, - "passport": "t1", - "password": "25d55ad283aa400af464c76d713c07ad", - "nickname": "name_1", - "create_time": gtime.Now().String(), - }, - g.Map{ - "id": 2, - "uid": 2, - "passport": "t1", - "password": "25d55ad283aa400af464c76d713c07ad", - "nickname": "name_1", - "create_time": gtime.Now().String(), - }, - } - - result, err := db.Model(table).Data(data).Insert() - t.AssertNil(err) - n, _ := result.LastInsertId() - t.Assert(n, 2) - - t.Assert(data[0]["uid"], 1) - t.Assert(data[1]["uid"], 2) - }) -} - -func Test_Model_Embedded_Filter(t *testing.T) { - table := createTable() - defer dropTable(table) - gtest.C(t, func(t *gtest.T) { - type Base struct { - Id int - Uid int - CreateTime string - NoneExist string - } - type User struct { - Base - Passport string - Password string - Nickname string - } - result, err := db.Model(table).Data(User{ - Passport: "john-test", - Password: "123456", - Nickname: "John", - Base: Base{ - Id: 100, - Uid: 100, - CreateTime: gtime.Now().String(), - }, - }).Insert() - t.AssertNil(err) - n, _ := result.RowsAffected() - t.Assert(n, 1) - - var user *User - err = db.Model(table).Fields(user).Where("id=100").Scan(&user) - t.AssertNil(err) - t.Assert(user.Passport, "john-test") - t.Assert(user.Id, 100) - }) -} - -// This is no longer used as the filter feature is automatically enabled from GoFrame v1.16.0. -//func Test_Model_Insert_KeyFieldNameMapping_Error(t *testing.T) { -// table := createTable() -// defer dropTable(table) -// -// gtest.C(t, func(t *gtest.T) { -// type User struct { -// Id int -// Passport string -// Password string -// Nickname string -// CreateTime string -// NoneExistFiled string -// } -// data := User{ -// Id: 1, -// Passport: "user_1", -// Password: "pass_1", -// Nickname: "name_1", -// CreateTime: "2020-10-10 12:00:01", -// } -// _, err := db.Model(table).Data(data).Insert() -// t.AssertNE(err, nil) -// }) -//} - -func Test_Model_Fields_AutoFilterInJoinStatement(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - var err error - table1 := "user" - table2 := "score" - table3 := "info" - if _, err := db.Exec(ctx, fmt.Sprintf(` - CREATE TABLE IF NOT EXISTS %s ( - id int(11) NOT NULL AUTO_INCREMENT, - name varchar(500) NOT NULL DEFAULT '', - PRIMARY KEY (id) - ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; - `, table1, - )); err != nil { - t.AssertNil(err) - } - defer dropTable(table1) - _, err = db.Model(table1).Insert(g.Map{ - "id": 1, - "name": "john", - }) - t.AssertNil(err) - - if _, err := db.Exec(ctx, fmt.Sprintf(` - CREATE TABLE IF NOT EXISTS %s ( - id int(11) NOT NULL AUTO_INCREMENT, - user_id int(11) NOT NULL DEFAULT 0, - number varchar(500) NOT NULL DEFAULT '', - PRIMARY KEY (id) - ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; - `, table2, - )); err != nil { - t.AssertNil(err) - } - defer dropTable(table2) - _, err = db.Model(table2).Insert(g.Map{ - "id": 1, - "user_id": 1, - "number": "n", - }) - t.AssertNil(err) - - if _, err := db.Exec(ctx, fmt.Sprintf(` - CREATE TABLE IF NOT EXISTS %s ( - id int(11) NOT NULL AUTO_INCREMENT, - user_id int(11) NOT NULL DEFAULT 0, - description varchar(500) NOT NULL DEFAULT '', - PRIMARY KEY (id) - ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; - `, table3, - )); err != nil { - t.AssertNil(err) - } - defer dropTable(table3) - _, err = db.Model(table3).Insert(g.Map{ - "id": 1, - "user_id": 1, - "description": "brief", - }) - t.AssertNil(err) - - one, err := db.Model("user"). - Where("user.id", 1). - Fields("score.number,user.name"). - LeftJoin("score", "user.id=score.user_id"). - LeftJoin("info", "info.id=info.user_id"). - Order("user.id asc"). - One() - t.AssertNil(err) - t.Assert(len(one), 2) - t.Assert(one["name"].String(), "john") - t.Assert(one["number"].String(), "n") - - one, err = db.Model("user"). - LeftJoin("score", "user.id=score.user_id"). - LeftJoin("info", "info.id=info.user_id"). - Fields("score.number,user.name"). - One() - t.AssertNil(err) - t.Assert(len(one), 2) - t.Assert(one["name"].String(), "john") - t.Assert(one["number"].String(), "n") - }) -} diff --git a/database/gdb/gdb_z_mysql_model_basic_test.go b/database/gdb/gdb_z_mysql_model_test.go similarity index 91% rename from database/gdb/gdb_z_mysql_model_basic_test.go rename to database/gdb/gdb_z_mysql_model_test.go index c1e7496ef..783971780 100644 --- a/database/gdb/gdb_z_mysql_model_basic_test.go +++ b/database/gdb/gdb_z_mysql_model_test.go @@ -11,23 +11,21 @@ import ( "context" "database/sql" "fmt" - "github.com/gogf/gf/v2/encoding/gjson" - "github.com/gogf/gf/v2/text/gstr" "os" "testing" "time" "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/container/gmap" - "github.com/gogf/gf/v2/debug/gdebug" - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/util/gutil" - "github.com/gogf/gf/v2/database/gdb" - + "github.com/gogf/gf/v2/debug/gdebug" + "github.com/gogf/gf/v2/encoding/gjson" "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/text/gstr" + "github.com/gogf/gf/v2/util/gutil" ) func Test_Model_Insert(t *testing.T) { @@ -706,16 +704,16 @@ func Test_Model_Count(t *testing.T) { t.AssertNil(err) t.Assert(count, TableSize) }) - //gtest.C(t, func(t *gtest.T) { + // gtest.C(t, func(t *gtest.T) { // count, err := db.Model(table).Fields("id myid").Where("id>8").Count() // t.AssertNil(err) // t.Assert(count, 2) - //}) - //gtest.C(t, func(t *gtest.T) { + // }) + // gtest.C(t, func(t *gtest.T) { // count, err := db.Model(table).As("u1").LeftJoin(table, "u2", "u2.id=u1.id").Fields("u2.id u2id").Where("u1.id>8").Count() // t.AssertNil(err) // t.Assert(count, 2) - //}) + // }) } func Test_Model_Select(t *testing.T) { @@ -954,8 +952,8 @@ func Test_Model_StructsWithOrmTag(t *testing.T) { ) }) - //db.SetDebug(true) - //defer db.SetDebug(false) + // db.SetDebug(true) + // defer db.SetDebug(false) gtest.C(t, func(t *gtest.T) { type A struct { Passport string @@ -972,7 +970,6 @@ func Test_Model_StructsWithOrmTag(t *testing.T) { t.Assert(one["passport"], "user_2") t.Assert(one["password"], "pass_2") }) - } func Test_Model_Scan(t *testing.T) { @@ -1302,7 +1299,7 @@ func Test_Model_Where(t *testing.T) { // complicated where 1 gtest.C(t, func(t *gtest.T) { - //db.SetDebug(true) + // db.SetDebug(true) conditions := g.Map{ "nickname like ?": "%name%", "id between ? and ?": g.Slice{1, 3}, @@ -1317,7 +1314,7 @@ func Test_Model_Where(t *testing.T) { }) // complicated where 2 gtest.C(t, func(t *gtest.T) { - //db.SetDebug(true) + // db.SetDebug(true) conditions := g.Map{ "nickname like ?": "%name%", "id between ? and ?": g.Slice{1, 3}, @@ -1390,7 +1387,7 @@ func Test_Model_Where_ISNULL_1(t *testing.T) { defer dropTable(table) gtest.C(t, func(t *gtest.T) { - //db.SetDebug(true) + // db.SetDebug(true) result, err := db.Model(table).Data("nickname", nil).Where("id", 2).Update() t.AssertNil(err) n, _ := result.RowsAffected() @@ -1409,7 +1406,7 @@ func Test_Model_Where_ISNULL_2(t *testing.T) { // complicated one. gtest.C(t, func(t *gtest.T) { - //db.SetDebug(true) + // db.SetDebug(true) conditions := g.Map{ "nickname like ?": "%name%", "id between ? and ?": g.Slice{1, 3}, @@ -1638,7 +1635,7 @@ func Test_Model_WherePri(t *testing.T) { // complicated where 1 gtest.C(t, func(t *gtest.T) { - //db.SetDebug(true) + // db.SetDebug(true) conditions := g.Map{ "nickname like ?": "%name%", "id between ? and ?": g.Slice{1, 3}, @@ -1653,7 +1650,7 @@ func Test_Model_WherePri(t *testing.T) { }) // complicated where 2 gtest.C(t, func(t *gtest.T) { - //db.SetDebug(true) + // db.SetDebug(true) conditions := g.Map{ "nickname like ?": "%name%", "id between ? and ?": g.Slice{1, 3}, @@ -1986,7 +1983,6 @@ func Test_Model_Option_List(t *testing.T) { t.Assert(list[1]["nickname"].String(), "") t.Assert(list[1]["passport"].String(), "") t.Assert(list[1]["password"].String(), "2") - }) } @@ -2212,7 +2208,7 @@ func Test_Model_Prefix(t *testing.T) { } func Test_Model_Schema1(t *testing.T) { - //db.SetDebug(true) + // db.SetDebug(true) db.SetSchema(TestSchema1) table := fmt.Sprintf(`%s_%s`, TableName, gtime.TimestampNanoStr()) @@ -2291,7 +2287,7 @@ func Test_Model_Schema1(t *testing.T) { } func Test_Model_Schema2(t *testing.T) { - //db.SetDebug(true) + // db.SetDebug(true) db.SetSchema(TestSchema1) table := fmt.Sprintf(`%s_%s`, TableName, gtime.TimestampNanoStr()) @@ -2479,7 +2475,11 @@ func Test_Model_Cache(t *testing.T) { defer dropTable(table) gtest.C(t, func(t *gtest.T) { - one, err := db.Model(table).Cache(time.Second, "test1").WherePri(1).One() + one, err := db.Model(table).Cache(gdb.CacheOption{ + Duration: time.Second, + Name: "test1", + Force: false, + }).WherePri(1).One() t.AssertNil(err) t.Assert(one["passport"], "user_1") @@ -2489,63 +2489,107 @@ func Test_Model_Cache(t *testing.T) { t.AssertNil(err) t.Assert(n, 1) - one, err = db.Model(table).Cache(time.Second, "test1").WherePri(1).One() + one, err = db.Model(table).Cache(gdb.CacheOption{ + Duration: time.Second, + Name: "test1", + Force: false, + }).WherePri(1).One() t.AssertNil(err) t.Assert(one["passport"], "user_1") time.Sleep(time.Second * 2) - one, err = db.Model(table).Cache(time.Second, "test1").WherePri(1).One() + one, err = db.Model(table).Cache(gdb.CacheOption{ + Duration: time.Second, + Name: "test1", + Force: false, + }).WherePri(1).One() t.AssertNil(err) t.Assert(one["passport"], "user_100") }) gtest.C(t, func(t *gtest.T) { - one, err := db.Model(table).Cache(time.Second, "test2").WherePri(2).One() + one, err := db.Model(table).Cache(gdb.CacheOption{ + Duration: time.Second, + Name: "test2", + Force: false, + }).WherePri(2).One() t.AssertNil(err) t.Assert(one["passport"], "user_2") - r, err := db.Model(table).Data("passport", "user_200").Cache(-1, "test2").WherePri(2).Update() + r, err := db.Model(table).Data("passport", "user_200").Cache(gdb.CacheOption{ + Duration: -1, + Name: "test2", + Force: false, + }).WherePri(2).Update() t.AssertNil(err) n, err := r.RowsAffected() t.AssertNil(err) t.Assert(n, 1) - one, err = db.Model(table).Cache(time.Second, "test2").WherePri(2).One() + one, err = db.Model(table).Cache(gdb.CacheOption{ + Duration: time.Second, + Name: "test2", + Force: false, + }).WherePri(2).One() t.AssertNil(err) t.Assert(one["passport"], "user_200") }) // transaction. gtest.C(t, func(t *gtest.T) { // make cache for id 3 - one, err := db.Model(table).Cache(time.Second, "test3").WherePri(3).One() + one, err := db.Model(table).Cache(gdb.CacheOption{ + Duration: time.Second, + Name: "test3", + Force: false, + }).WherePri(3).One() t.AssertNil(err) t.Assert(one["passport"], "user_3") - r, err := db.Model(table).Data("passport", "user_300").Cache(time.Second, "test3").WherePri(3).Update() + r, err := db.Model(table).Data("passport", "user_300").Cache(gdb.CacheOption{ + Duration: time.Second, + Name: "test3", + Force: false, + }).WherePri(3).Update() t.AssertNil(err) n, err := r.RowsAffected() t.AssertNil(err) t.Assert(n, 1) err = db.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error { - one, err := tx.Model(table).Cache(time.Second, "test3").WherePri(3).One() + one, err := tx.Model(table).Cache(gdb.CacheOption{ + Duration: time.Second, + Name: "test3", + Force: false, + }).WherePri(3).One() t.AssertNil(err) t.Assert(one["passport"], "user_300") return nil }) t.AssertNil(err) - one, err = db.Model(table).Cache(time.Second, "test3").WherePri(3).One() + one, err = db.Model(table).Cache(gdb.CacheOption{ + Duration: time.Second, + Name: "test3", + Force: false, + }).WherePri(3).One() t.AssertNil(err) t.Assert(one["passport"], "user_3") }) gtest.C(t, func(t *gtest.T) { // make cache for id 4 - one, err := db.Model(table).Cache(time.Second, "test4").WherePri(4).One() + one, err := db.Model(table).Cache(gdb.CacheOption{ + Duration: time.Second, + Name: "test4", + Force: false, + }).WherePri(4).One() t.AssertNil(err) t.Assert(one["passport"], "user_4") - r, err := db.Model(table).Data("passport", "user_400").Cache(time.Second, "test3").WherePri(4).Update() + r, err := db.Model(table).Data("passport", "user_400").Cache(gdb.CacheOption{ + Duration: time.Second, + Name: "test3", + Force: false, + }).WherePri(4).Update() t.AssertNil(err) n, err := r.RowsAffected() t.AssertNil(err) @@ -2553,12 +2597,20 @@ func Test_Model_Cache(t *testing.T) { err = db.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error { // Cache feature disabled. - one, err := tx.Model(table).Cache(time.Second, "test4").WherePri(4).One() + one, err := tx.Model(table).Cache(gdb.CacheOption{ + Duration: time.Second, + Name: "test4", + Force: false, + }).WherePri(4).One() t.AssertNil(err) t.Assert(one["passport"], "user_400") // Update the cache. r, err := tx.Model(table).Data("passport", "user_4000"). - Cache(-1, "test4").WherePri(4).Update() + Cache(gdb.CacheOption{ + Duration: -1, + Name: "test4", + Force: false, + }).WherePri(4).Update() t.AssertNil(err) n, err := r.RowsAffected() t.AssertNil(err) @@ -2567,7 +2619,11 @@ func Test_Model_Cache(t *testing.T) { }) t.AssertNil(err) // Read from db. - one, err = db.Model(table).Cache(time.Second, "test4").WherePri(4).One() + one, err = db.Model(table).Cache(gdb.CacheOption{ + Duration: time.Second, + Name: "test4", + Force: false, + }).WherePri(4).One() t.AssertNil(err) t.Assert(one["passport"], "user_4000") }) @@ -2769,6 +2825,7 @@ func Test_Model_Fields_Struct(t *testing.T) { t.Assert(one["nickname"], "name_2") }) } + func Test_Model_NullField(t *testing.T) { table := createTable() defer dropTable(table) @@ -2896,7 +2953,7 @@ func Test_Model_Issue1002(t *testing.T) { } }) // where + time.Time arguments, +8. - //gtest.C(t, func(t *gtest.T) { + // gtest.C(t, func(t *gtest.T) { // // Change current timezone to +8 zone. // location, err := time.LoadLocation("Asia/Shanghai") // t.AssertNil(err) @@ -2917,7 +2974,7 @@ func Test_Model_Issue1002(t *testing.T) { // t.AssertNil(err) // t.Assert(v.Int(), 1) // } - //}) + // }) } func createTableForTimeZoneTest() string { @@ -3000,7 +3057,7 @@ func Test_Model_Fields_Map_Struct(t *testing.T) { PASSPORT string XXX_TYPE int } - var a = A{} + a := A{} err := db.Model(table).Fields(a).Where("id", 1).Scan(&a) t.AssertNil(err) t.Assert(a.ID, 1) @@ -3130,7 +3187,7 @@ func Test_Model_WhereOrBetween(t *testing.T) { func Test_Model_WhereOrNotBetween(t *testing.T) { table := createInitTable() defer dropTable(table) - //db.SetDebug(true) + // db.SetDebug(true) gtest.C(t, func(t *gtest.T) { result, err := db.Model(table).WhereOrNotBetween("id", 1, 4).WhereOrNotBetween("id", 3, 5).OrderDesc("id").All() t.AssertNil(err) @@ -3797,3 +3854,289 @@ func Test_Model_GTime_DefaultValue(t *testing.T) { t.AssertNil(err) }) } + +// Using filter does not affect the outside value inside function. +func Test_Model_Insert_Filter(t *testing.T) { + // map + gtest.C(t, func(t *gtest.T) { + table := createTable() + defer dropTable(table) + data := g.Map{ + "id": 1, + "uid": 1, + "passport": "t1", + "password": "25d55ad283aa400af464c76d713c07ad", + "nickname": "name_1", + "create_time": gtime.Now().String(), + } + result, err := db.Model(table).Data(data).Insert() + t.AssertNil(err) + n, _ := result.LastInsertId() + t.Assert(n, 1) + + t.Assert(data["uid"], 1) + }) + // slice + gtest.C(t, func(t *gtest.T) { + table := createTable() + defer dropTable(table) + data := g.List{ + g.Map{ + "id": 1, + "uid": 1, + "passport": "t1", + "password": "25d55ad283aa400af464c76d713c07ad", + "nickname": "name_1", + "create_time": gtime.Now().String(), + }, + g.Map{ + "id": 2, + "uid": 2, + "passport": "t1", + "password": "25d55ad283aa400af464c76d713c07ad", + "nickname": "name_1", + "create_time": gtime.Now().String(), + }, + } + + result, err := db.Model(table).Data(data).Insert() + t.AssertNil(err) + n, _ := result.LastInsertId() + t.Assert(n, 2) + + t.Assert(data[0]["uid"], 1) + t.Assert(data[1]["uid"], 2) + }) +} + +func Test_Model_Embedded_Filter(t *testing.T) { + table := createTable() + defer dropTable(table) + gtest.C(t, func(t *gtest.T) { + type Base struct { + Id int + Uid int + CreateTime string + NoneExist string + } + type User struct { + Base + Passport string + Password string + Nickname string + } + result, err := db.Model(table).Data(User{ + Passport: "john-test", + Password: "123456", + Nickname: "John", + Base: Base{ + Id: 100, + Uid: 100, + CreateTime: gtime.Now().String(), + }, + }).Insert() + t.AssertNil(err) + n, _ := result.RowsAffected() + t.Assert(n, 1) + + var user *User + err = db.Model(table).Fields(user).Where("id=100").Scan(&user) + t.AssertNil(err) + t.Assert(user.Passport, "john-test") + t.Assert(user.Id, 100) + }) +} + +// This is no longer used as the filter feature is automatically enabled from GoFrame v1.16.0. +// func Test_Model_Insert_KeyFieldNameMapping_Error(t *testing.T) { +// table := createTable() +// defer dropTable(table) +// +// gtest.C(t, func(t *gtest.T) { +// type User struct { +// Id int +// Passport string +// Password string +// Nickname string +// CreateTime string +// NoneExistFiled string +// } +// data := User{ +// Id: 1, +// Passport: "user_1", +// Password: "pass_1", +// Nickname: "name_1", +// CreateTime: "2020-10-10 12:00:01", +// } +// _, err := db.Model(table).Data(data).Insert() +// t.AssertNE(err, nil) +// }) +// } + +func Test_Model_Fields_AutoFilterInJoinStatement(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + var err error + table1 := "user" + table2 := "score" + table3 := "info" + if _, err := db.Exec(ctx, fmt.Sprintf(` + CREATE TABLE IF NOT EXISTS %s ( + id int(11) NOT NULL AUTO_INCREMENT, + name varchar(500) NOT NULL DEFAULT '', + PRIMARY KEY (id) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; + `, table1, + )); err != nil { + t.AssertNil(err) + } + defer dropTable(table1) + _, err = db.Model(table1).Insert(g.Map{ + "id": 1, + "name": "john", + }) + t.AssertNil(err) + + if _, err := db.Exec(ctx, fmt.Sprintf(` + CREATE TABLE IF NOT EXISTS %s ( + id int(11) NOT NULL AUTO_INCREMENT, + user_id int(11) NOT NULL DEFAULT 0, + number varchar(500) NOT NULL DEFAULT '', + PRIMARY KEY (id) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; + `, table2, + )); err != nil { + t.AssertNil(err) + } + defer dropTable(table2) + _, err = db.Model(table2).Insert(g.Map{ + "id": 1, + "user_id": 1, + "number": "n", + }) + t.AssertNil(err) + + if _, err := db.Exec(ctx, fmt.Sprintf(` + CREATE TABLE IF NOT EXISTS %s ( + id int(11) NOT NULL AUTO_INCREMENT, + user_id int(11) NOT NULL DEFAULT 0, + description varchar(500) NOT NULL DEFAULT '', + PRIMARY KEY (id) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; + `, table3, + )); err != nil { + t.AssertNil(err) + } + defer dropTable(table3) + _, err = db.Model(table3).Insert(g.Map{ + "id": 1, + "user_id": 1, + "description": "brief", + }) + t.AssertNil(err) + + one, err := db.Model("user"). + Where("user.id", 1). + Fields("score.number,user.name"). + LeftJoin("score", "user.id=score.user_id"). + LeftJoin("info", "info.id=info.user_id"). + Order("user.id asc"). + One() + t.AssertNil(err) + t.Assert(len(one), 2) + t.Assert(one["name"].String(), "john") + t.Assert(one["number"].String(), "n") + + one, err = db.Model("user"). + LeftJoin("score", "user.id=score.user_id"). + LeftJoin("info", "info.id=info.user_id"). + Fields("score.number,user.name"). + One() + t.AssertNil(err) + t.Assert(len(one), 2) + t.Assert(one["name"].String(), "john") + t.Assert(one["number"].String(), "n") + }) +} + +func Test_Model_WherePrefix(t *testing.T) { + var ( + table1 = gtime.TimestampNanoStr() + "_table1" + table2 = gtime.TimestampNanoStr() + "_table2" + ) + createInitTable(table1) + defer dropTable(table1) + createInitTable(table2) + defer dropTable(table2) + + gtest.C(t, func(t *gtest.T) { + r, err := db.Model(table1). + FieldsPrefix(table1, "*"). + LeftJoinOnField(table2, "id"). + WherePrefix(table2, g.Map{ + "id": g.Slice{1, 2}, + }). + Order("id asc").All() + t.AssertNil(err) + t.Assert(len(r), 2) + t.Assert(r[0]["id"], "1") + t.Assert(r[1]["id"], "2") + }) +} + +func Test_Model_WhereOrPrefix(t *testing.T) { + var ( + table1 = gtime.TimestampNanoStr() + "_table1" + table2 = gtime.TimestampNanoStr() + "_table2" + ) + createInitTable(table1) + defer dropTable(table1) + createInitTable(table2) + defer dropTable(table2) + + gtest.C(t, func(t *gtest.T) { + r, err := db.Model(table1). + FieldsPrefix(table1, "*"). + LeftJoinOnField(table2, "id"). + WhereOrPrefix(table1, g.Map{ + "id": g.Slice{1, 2}, + }). + WhereOrPrefix(table2, g.Map{ + "id": g.Slice{8, 9}, + }). + Order("id asc").All() + t.AssertNil(err) + t.Assert(len(r), 4) + t.Assert(r[0]["id"], "1") + t.Assert(r[1]["id"], "2") + t.Assert(r[2]["id"], "8") + t.Assert(r[3]["id"], "9") + }) +} + +func Test_Model_WherePrefixLike(t *testing.T) { + var ( + table1 = gtime.TimestampNanoStr() + "_table1" + table2 = gtime.TimestampNanoStr() + "_table2" + ) + createInitTable(table1) + defer dropTable(table1) + createInitTable(table2) + defer dropTable(table2) + + gtest.C(t, func(t *gtest.T) { + r, err := db.Model(table1). + FieldsPrefix(table1, "*"). + LeftJoinOnField(table2, "id"). + WherePrefix(table1, g.Map{ + "id": g.Slice{1, 2, 3}, + }). + WherePrefix(table2, g.Map{ + "id": g.Slice{3, 4, 5}, + }). + WherePrefixLike(table2, "nickname", "name%"). + Order("id asc").All() + t.AssertNil(err) + t.Assert(len(r), 1) + t.Assert(r[0]["id"], "3") + }) +} diff --git a/database/gdb/gdb_z_mysql_model_where_test.go b/database/gdb/gdb_z_mysql_model_where_test.go deleted file mode 100644 index 796d23ffc..000000000 --- a/database/gdb/gdb_z_mysql_model_where_test.go +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. -// -// This Source Code Form is subject to the terms of the MIT License. -// If a copy of the MIT was not distributed with this file, -// You can obtain one at https://github.com/gogf/gf. - -package gdb_test - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/test/gtest" - "testing" -) - -func Test_Model_WherePrefix(t *testing.T) { - var ( - table1 = gtime.TimestampNanoStr() + "_table1" - table2 = gtime.TimestampNanoStr() + "_table2" - ) - createInitTable(table1) - defer dropTable(table1) - createInitTable(table2) - defer dropTable(table2) - - gtest.C(t, func(t *gtest.T) { - r, err := db.Model(table1). - FieldsPrefix(table1, "*"). - LeftJoinOnField(table2, "id"). - WherePrefix(table2, g.Map{ - "id": g.Slice{1, 2}, - }). - Order("id asc").All() - t.AssertNil(err) - t.Assert(len(r), 2) - t.Assert(r[0]["id"], "1") - t.Assert(r[1]["id"], "2") - }) -} - -func Test_Model_WhereOrPrefix(t *testing.T) { - var ( - table1 = gtime.TimestampNanoStr() + "_table1" - table2 = gtime.TimestampNanoStr() + "_table2" - ) - createInitTable(table1) - defer dropTable(table1) - createInitTable(table2) - defer dropTable(table2) - - gtest.C(t, func(t *gtest.T) { - r, err := db.Model(table1). - FieldsPrefix(table1, "*"). - LeftJoinOnField(table2, "id"). - WhereOrPrefix(table1, g.Map{ - "id": g.Slice{1, 2}, - }). - WhereOrPrefix(table2, g.Map{ - "id": g.Slice{8, 9}, - }). - Order("id asc").All() - t.AssertNil(err) - t.Assert(len(r), 4) - t.Assert(r[0]["id"], "1") - t.Assert(r[1]["id"], "2") - t.Assert(r[2]["id"], "8") - t.Assert(r[3]["id"], "9") - - }) -} diff --git a/database/gdb/gdb_z_mysql_transaction_test.go b/database/gdb/gdb_z_mysql_transaction_test.go index d9c8d9690..41a7d5fc1 100644 --- a/database/gdb/gdb_z_mysql_transaction_test.go +++ b/database/gdb/gdb_z_mysql_transaction_test.go @@ -9,13 +9,12 @@ package gdb_test import ( "context" "fmt" - "github.com/gogf/gf/v2/os/gctx" "testing" "github.com/gogf/gf/v2/database/gdb" "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/os/gctx" "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" ) @@ -145,7 +144,6 @@ func Test_TX_Insert(t *testing.T) { if err := tx.Commit(); err != nil { gtest.Error(err) } - }) } @@ -416,7 +414,6 @@ func Test_TX_GetValue(t *testing.T) { gtest.Error(err) } }) - } func Test_TX_GetCount(t *testing.T) { @@ -955,8 +952,8 @@ func Test_Transaction_Nested_TX_Transaction_UseDB(t *testing.T) { table := createTable() defer dropTable(table) - //db.SetDebug(true) - //defer db.SetDebug(false) + // db.SetDebug(true) + // defer db.SetDebug(false) gtest.C(t, func(t *gtest.T) { var ( diff --git a/database/gdb/gdb_z_mysql_types_test.go b/database/gdb/gdb_z_mysql_types_test.go deleted file mode 100644 index 12126617f..000000000 --- a/database/gdb/gdb_z_mysql_types_test.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. -// -// This Source Code Form is subject to the terms of the MIT License. -// If a copy of the MIT was not distributed with this file, -// You can obtain one at https://github.com/gogf/gf. - -package gdb_test - -import ( - "fmt" - "github.com/gogf/gf/v2/os/gtime" - "testing" - - "github.com/gogf/gf/v2/frame/g" - - "github.com/gogf/gf/v2/test/gtest" -) - -// All types testing. -func Test_Types(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - if _, err := db.Exec(ctx, fmt.Sprintf(` - CREATE TABLE IF NOT EXISTS types ( - id int(10) unsigned NOT NULL AUTO_INCREMENT, - %s blob NOT NULL, - %s binary(8) NOT NULL, - %s date NOT NULL, - %s time NOT NULL, - %s decimal(5,2) NOT NULL, - %s double NOT NULL, - %s bit(2) NOT NULL, - %s tinyint(1) NOT NULL, - %s bool NOT NULL, - PRIMARY KEY (id) - ) ENGINE=InnoDB DEFAULT CHARSET=utf8; - `, - "`blob`", - "`binary`", - "`date`", - "`time`", - "`decimal`", - "`double`", - "`bit`", - "`tinyint`", - "`bool`")); err != nil { - gtest.Error(err) - } - defer dropTable("types") - data := g.Map{ - "id": 1, - "blob": "i love gf", - "binary": []byte("abcdefgh"), - "date": "1880-10-24", - "time": "10:00:01", - "decimal": -123.456, - "double": -123.456, - "bit": 2, - "tinyint": true, - "bool": false, - } - r, err := db.Model("types").Data(data).Insert() - t.AssertNil(err) - n, _ := r.RowsAffected() - t.Assert(n, 1) - - one, err := db.Model("types").One() - t.AssertNil(err) - t.Assert(one["id"].Int(), 1) - t.Assert(one["blob"].String(), data["blob"]) - t.Assert(one["binary"].String(), data["binary"]) - t.Assert(one["date"].String(), data["date"]) - t.Assert(one["time"].String(), `0000-01-01 10:00:01`) - t.Assert(one["decimal"].String(), -123.46) - t.Assert(one["double"].String(), data["double"]) - t.Assert(one["bit"].Int(), data["bit"]) - t.Assert(one["tinyint"].Bool(), data["tinyint"]) - - type T struct { - Id int - Blob []byte - Binary []byte - Date *gtime.Time - Time *gtime.Time - Decimal float64 - Double float64 - Bit int8 - TinyInt bool - } - var obj *T - err = db.Model("types").Scan(&obj) - t.AssertNil(err) - t.Assert(obj.Id, 1) - t.Assert(obj.Blob, data["blob"]) - t.Assert(obj.Binary, data["binary"]) - t.Assert(obj.Date.Format("Y-m-d"), data["date"]) - t.Assert(obj.Time.String(), `0000-01-01 10:00:01`) - t.Assert(obj.Decimal, -123.46) - t.Assert(obj.Double, data["double"]) - t.Assert(obj.Bit, data["bit"]) - t.Assert(obj.TinyInt, data["tinyint"]) - }) -} diff --git a/database/gdb/gdb_z_oracle_internal_test.go b/database/gdb/gdb_z_oracle_internal_test.go deleted file mode 100644 index c31084757..000000000 --- a/database/gdb/gdb_z_oracle_internal_test.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. -// -// This Source Code Form is subject to the terms of the MIT License. -// If a copy of the MIT was not distributed with this file, -// You can obtain one at https://github.com/gogf/gf. - -package gdb - -import ( - "github.com/gogf/gf/v2/test/gtest" - "testing" -) - -func Test_Oracle_parseSql(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - o := new(DriverOracle) - sql := `UPDATE user SET name='john'` - newSql := o.parseSql(sql) - t.Assert(newSql, sql) - }) - - gtest.C(t, func(t *gtest.T) { - o := new(DriverOracle) - sql := `SELECT * FROM user` - newSql := o.parseSql(sql) - t.Assert(newSql, sql) - }) - - gtest.C(t, func(t *gtest.T) { - o := new(DriverOracle) - sql := `SELECT * FROM user LIMIT 0, 10` - newSql := o.parseSql(sql) - t.Assert(newSql, `SELECT * FROM (SELECT GFORM.*, ROWNUM ROWNUM_ FROM (SELECT * FROM user ) GFORM WHERE ROWNUM <= 10) WHERE ROWNUM_ >= 0`) - }) - - gtest.C(t, func(t *gtest.T) { - o := new(DriverOracle) - sql := `SELECT * FROM user LIMIT 1` - newSql := o.parseSql(sql) - t.Assert(newSql, `SELECT * FROM (SELECT GFORM.*, ROWNUM ROWNUM_ FROM (SELECT * FROM user ) GFORM WHERE ROWNUM <= 1) WHERE ROWNUM_ >= 0`) - }) - - gtest.C(t, func(t *gtest.T) { - o := new(DriverOracle) - sql := `SELECT ENAME FROM USER_INFO WHERE ID=2 LIMIT 1` - newSql := o.parseSql(sql) - t.Assert(newSql, `SELECT * FROM (SELECT GFORM.*, ROWNUM ROWNUM_ FROM (SELECT ENAME FROM USER_INFO WHERE ID=2 ) GFORM WHERE ROWNUM <= 1) WHERE ROWNUM_ >= 0`) - }) -} diff --git a/database/gredis/gredis_adapter.go b/database/gredis/gredis_adapter.go index 1d2061211..99531e4be 100644 --- a/database/gredis/gredis_adapter.go +++ b/database/gredis/gredis_adapter.go @@ -8,6 +8,7 @@ package gredis import ( "context" + "github.com/gogf/gf/v2/container/gvar" ) diff --git a/database/gredis/gredis_adapter_goredis.go b/database/gredis/gredis_adapter_goredis.go index 50ed5a92c..ed5c3feae 100644 --- a/database/gredis/gredis_adapter_goredis.go +++ b/database/gredis/gredis_adapter_goredis.go @@ -8,9 +8,11 @@ package gredis import ( "context" - "github.com/go-redis/redis/v8" - "github.com/gogf/gf/v2/text/gstr" "time" + + "github.com/go-redis/redis/v8" + + "github.com/gogf/gf/v2/text/gstr" ) // AdapterGoRedis is an implement of Adapter using go-redis. diff --git a/database/gredis/gredis_adapter_goredis_conn.go b/database/gredis/gredis_adapter_goredis_conn.go index 836eadb9c..a4a1bd243 100644 --- a/database/gredis/gredis_adapter_goredis_conn.go +++ b/database/gredis/gredis_adapter_goredis_conn.go @@ -8,7 +8,9 @@ package gredis import ( "context" + "github.com/go-redis/redis/v8" + "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" diff --git a/database/gredis/gredis_config.go b/database/gredis/gredis_config.go index 6b75e84f4..e3431609e 100644 --- a/database/gredis/gredis_config.go +++ b/database/gredis/gredis_config.go @@ -9,12 +9,12 @@ package gredis import ( "context" "crypto/tls" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/internal/intlog" "time" "github.com/gogf/gf/v2/container/gmap" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/util/gconv" ) diff --git a/database/gredis/gredis_instance.go b/database/gredis/gredis_instance.go index 915099726..2582ac3df 100644 --- a/database/gredis/gredis_instance.go +++ b/database/gredis/gredis_instance.go @@ -8,6 +8,7 @@ package gredis import ( "context" + "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/internal/intlog" ) diff --git a/database/gredis/gredis_redis.go b/database/gredis/gredis_redis.go index 9d56a9cc3..9ade61f5a 100644 --- a/database/gredis/gredis_redis.go +++ b/database/gredis/gredis_redis.go @@ -8,6 +8,7 @@ package gredis import ( "context" + "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" diff --git a/database/gredis/gredis_redis_conn.go b/database/gredis/gredis_redis_conn.go index 9a330fba9..78396c737 100644 --- a/database/gredis/gredis_redis_conn.go +++ b/database/gredis/gredis_redis_conn.go @@ -8,11 +8,12 @@ package gredis import ( "context" + "reflect" + "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/utils" "github.com/gogf/gf/v2/os/gtime" - "reflect" ) // RedisConn is a connection of redis client. diff --git a/database/gredis/gredis_redis_tracing.go b/database/gredis/gredis_redis_tracing.go index 974c82515..2fd5fb2b3 100644 --- a/database/gredis/gredis_redis_tracing.go +++ b/database/gredis/gredis_redis_tracing.go @@ -9,13 +9,15 @@ package gredis import ( "context" "fmt" - "github.com/gogf/gf/v2" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/net/gtrace" + "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/trace" + + "github.com/gogf/gf/v2" + "github.com/gogf/gf/v2/internal/json" + "github.com/gogf/gf/v2/net/gtrace" ) // tracingItem holds the information for redis tracing. diff --git a/database/gredis/gredis_z_example_test.go b/database/gredis/gredis_z_example_test.go index 4baa5b8f6..d5043a8c4 100644 --- a/database/gredis/gredis_z_example_test.go +++ b/database/gredis/gredis_z_example_test.go @@ -9,6 +9,7 @@ package gredis_test import ( "context" "fmt" + "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/util/gutil" diff --git a/database/gredis/gredis_z_unit_config_test.go b/database/gredis/gredis_z_unit_config_test.go index e00a3c1a0..7a0995b19 100644 --- a/database/gredis/gredis_z_unit_config_test.go +++ b/database/gredis/gredis_z_unit_config_test.go @@ -7,11 +7,12 @@ package gredis_test import ( + "testing" + "time" + "github.com/gogf/gf/v2/database/gredis" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/test/gtest" - "testing" - "time" ) func Test_ConfigFromMap(t *testing.T) { diff --git a/database/gredis/gredis_z_unit_conn_test.go b/database/gredis/gredis_z_unit_conn_test.go index 28925214d..f3f6b1bd0 100644 --- a/database/gredis/gredis_z_unit_conn_test.go +++ b/database/gredis/gredis_z_unit_conn_test.go @@ -8,9 +8,10 @@ package gredis_test import ( "context" + "testing" + "github.com/gogf/gf/v2/database/gredis" "github.com/gogf/gf/v2/test/gtest" - "testing" ) var ( diff --git a/database/gredis/gredis_z_unit_test.go b/database/gredis/gredis_z_unit_test.go index 4e8cfc493..dfa5daa68 100644 --- a/database/gredis/gredis_z_unit_test.go +++ b/database/gredis/gredis_z_unit_test.go @@ -7,18 +7,17 @@ package gredis_test import ( - "github.com/gogf/gf/v2/container/gvar" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/guid" - "github.com/gogf/gf/v2/util/gutil" "testing" "time" - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/util/gconv" - + "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/database/gredis" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gconv" + "github.com/gogf/gf/v2/util/guid" + "github.com/gogf/gf/v2/util/gutil" ) var ( diff --git a/debug/gdebug/gdebug_caller.go b/debug/gdebug/gdebug_caller.go index d084b8c58..70bb1a28f 100644 --- a/debug/gdebug/gdebug_caller.go +++ b/debug/gdebug/gdebug_caller.go @@ -8,13 +8,14 @@ package gdebug import ( "fmt" - "github.com/gogf/gf/v2/internal/utils" "os" "os/exec" "path/filepath" "reflect" "runtime" "strings" + + "github.com/gogf/gf/v2/internal/utils" ) const ( diff --git a/debug/gdebug/gdebug_stack.go b/debug/gdebug/gdebug_stack.go index 5bafbcdd9..2a70b542e 100644 --- a/debug/gdebug/gdebug_stack.go +++ b/debug/gdebug/gdebug_stack.go @@ -9,9 +9,10 @@ package gdebug import ( "bytes" "fmt" - "github.com/gogf/gf/v2/internal/utils" "runtime" "strings" + + "github.com/gogf/gf/v2/internal/utils" ) // PrintStack prints to standard error the stack trace returned by runtime.Stack. diff --git a/debug/gdebug/gdebug_version.go b/debug/gdebug/gdebug_version.go index 708a326e3..55fb56393 100644 --- a/debug/gdebug/gdebug_version.go +++ b/debug/gdebug/gdebug_version.go @@ -7,10 +7,11 @@ package gdebug import ( - "github.com/gogf/gf/v2/crypto/gmd5" - "github.com/gogf/gf/v2/encoding/ghash" "io/ioutil" "strconv" + + "github.com/gogf/gf/v2/crypto/gmd5" + "github.com/gogf/gf/v2/encoding/ghash" ) // BinVersion returns the version of current running binary. diff --git a/encoding/gbase64/gbase64.go b/encoding/gbase64/gbase64.go index 6222f4289..6308947f1 100644 --- a/encoding/gbase64/gbase64.go +++ b/encoding/gbase64/gbase64.go @@ -29,7 +29,7 @@ func EncodeToString(src []byte) string { return string(Encode(src)) } -// EncryptFile encodes file content of `path` using BASE64 algorithms. +// EncodeFile encodes file content of `path` using BASE64 algorithms. func EncodeFile(path string) ([]byte, error) { content, err := ioutil.ReadFile(path) if err != nil { @@ -99,7 +99,7 @@ func MustDecodeString(data string) []byte { return result } -// DecodeString decodes string with BASE64 algorithm. +// DecodeToString decodes string with BASE64 algorithm. func DecodeToString(data string) (string, error) { b, err := DecodeString(data) return string(b), err diff --git a/encoding/gbase64/gbase64_test.go b/encoding/gbase64/gbase64_z_unit_test.go similarity index 100% rename from encoding/gbase64/gbase64_test.go rename to encoding/gbase64/gbase64_z_unit_test.go index 90e923628..d77921e63 100644 --- a/encoding/gbase64/gbase64_test.go +++ b/encoding/gbase64/gbase64_z_unit_test.go @@ -7,9 +7,9 @@ package gbase64_test import ( - "github.com/gogf/gf/v2/debug/gdebug" "testing" + "github.com/gogf/gf/v2/debug/gdebug" "github.com/gogf/gf/v2/encoding/gbase64" "github.com/gogf/gf/v2/test/gtest" ) diff --git a/encoding/gbinary/gbinary_bit.go b/encoding/gbinary/gbinary_bit.go index 536fb4030..3e93dcab6 100644 --- a/encoding/gbinary/gbinary_bit.go +++ b/encoding/gbinary/gbinary_bit.go @@ -8,15 +8,16 @@ package gbinary // NOTE: THIS IS AN EXPERIMENTAL FEATURE! -// 二进制位(0|1) +// Bit Binary bit (0 | 1) type Bit int8 -// 默认编码 +// EncodeBits does encode bits return bits Default coding func EncodeBits(bits []Bit, i int, l int) []Bit { return EncodeBitsWithUint(bits, uint(i), l) } -// 将ui按位合并到bits数组中,并占length长度位(注意:uis数组中存放的是二进制的0|1数字) +// EncodeBitsWithUint . Merge ui bitwise into the bits array and occupy the length bits +// (Note: binary 0 | 1 digits are stored in the uis array) func EncodeBitsWithUint(bits []Bit, ui uint, l int) []Bit { a := make([]Bit, l) for i := l - 1; i >= 0; i-- { @@ -25,12 +26,12 @@ func EncodeBitsWithUint(bits []Bit, ui uint, l int) []Bit { } if bits != nil { return append(bits, a...) - } else { - return a } + return a } -// 将bits转换为[]byte,从左至右进行编码,不足1 byte按0往末尾补充 +// EncodeBitsToBytes . does encode bits to bytes +// Convert bits to [] byte, encode from left to right, and add less than 1 byte from 0 to the end. func EncodeBitsToBytes(bits []Bit) []byte { if len(bits)%8 != 0 { for i := 0; i < len(bits)%8; i++ { @@ -44,7 +45,8 @@ func EncodeBitsToBytes(bits []Bit) []byte { return b } -// 解析为int +// DecodeBits .does decode bits to int +// Resolve to int func DecodeBits(bits []Bit) int { v := 0 for _, i := range bits { @@ -53,7 +55,7 @@ func DecodeBits(bits []Bit) int { return v } -// 解析为uint +// DecodeBitsToUint .Resolve to uint func DecodeBitsToUint(bits []Bit) uint { v := uint(0) for _, i := range bits { @@ -62,7 +64,7 @@ func DecodeBitsToUint(bits []Bit) uint { return v } -// 解析[]byte为字位数组[]uint8 +// DecodeBytesToBits .Parsing [] byte into character array [] uint8 func DecodeBytesToBits(bs []byte) []Bit { bits := make([]Bit, 0) for _, b := range bs { diff --git a/encoding/gbinary/gbinary_z_be_test.go b/encoding/gbinary/gbinary_z_unit_be_test.go similarity index 100% rename from encoding/gbinary/gbinary_z_be_test.go rename to encoding/gbinary/gbinary_z_unit_be_test.go diff --git a/encoding/gbinary/gbinary_z_le_test.go b/encoding/gbinary/gbinary_z_unit_le_test.go similarity index 100% rename from encoding/gbinary/gbinary_z_le_test.go rename to encoding/gbinary/gbinary_z_unit_le_test.go diff --git a/encoding/gbinary/gbinary_z_test.go b/encoding/gbinary/gbinary_z_unit_test.go similarity index 100% rename from encoding/gbinary/gbinary_z_test.go rename to encoding/gbinary/gbinary_z_unit_test.go diff --git a/encoding/gcharset/gcharset.go b/encoding/gcharset/gcharset.go index 676821195..bd283bc56 100644 --- a/encoding/gcharset/gcharset.go +++ b/encoding/gcharset/gcharset.go @@ -22,14 +22,15 @@ package gcharset import ( "bytes" "context" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/internal/intlog" "io/ioutil" "golang.org/x/text/encoding" "golang.org/x/text/encoding/ianaindex" "golang.org/x/text/transform" + + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/intlog" ) var ( diff --git a/encoding/gcharset/gcharset_test.go b/encoding/gcharset/gcharset_z_unit_test.go similarity index 100% rename from encoding/gcharset/gcharset_test.go rename to encoding/gcharset/gcharset_z_unit_test.go diff --git a/encoding/gcompress/gcompress_gzip.go b/encoding/gcompress/gcompress_gzip.go index b7b44a49f..0ce292534 100644 --- a/encoding/gcompress/gcompress_gzip.go +++ b/encoding/gcompress/gcompress_gzip.go @@ -9,8 +9,9 @@ package gcompress import ( "bytes" "compress/gzip" - "github.com/gogf/gf/v2/os/gfile" "io" + + "github.com/gogf/gf/v2/os/gfile" ) // Gzip compresses `data` using gzip algorithm. @@ -91,7 +92,7 @@ func UnGzip(data []byte) ([]byte, error) { return buf.Bytes(), nil } -// UnGzip decompresses file `src` to `dst` using gzip algorithm. +// UnGzipFile decompresses file `src` to `dst` using gzip algorithm. func UnGzipFile(src, dst string) error { srcFile, err := gfile.Open(src) if err != nil { diff --git a/encoding/gcompress/gcompress_z_unit_gzip_test.go b/encoding/gcompress/gcompress_z_unit_gzip_test.go index 319b92a0d..19e6d6698 100644 --- a/encoding/gcompress/gcompress_z_unit_gzip_test.go +++ b/encoding/gcompress/gcompress_z_unit_gzip_test.go @@ -7,12 +7,12 @@ package gcompress_test import ( - "github.com/gogf/gf/v2/debug/gdebug" - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/os/gtime" "testing" + "github.com/gogf/gf/v2/debug/gdebug" "github.com/gogf/gf/v2/encoding/gcompress" + "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" ) diff --git a/encoding/gcompress/gcompress_z_unit_zip_test.go b/encoding/gcompress/gcompress_z_unit_zip_test.go index c82428c6e..0cd3348d6 100644 --- a/encoding/gcompress/gcompress_z_unit_zip_test.go +++ b/encoding/gcompress/gcompress_z_unit_zip_test.go @@ -8,12 +8,12 @@ package gcompress_test import ( "bytes" + "testing" + "github.com/gogf/gf/v2/debug/gdebug" "github.com/gogf/gf/v2/encoding/gcompress" "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/gtime" - "testing" - "github.com/gogf/gf/v2/test/gtest" ) diff --git a/encoding/gcompress/gcompress_zip.go b/encoding/gcompress/gcompress_zip.go index 74a255de7..a9ee32bf0 100644 --- a/encoding/gcompress/gcompress_zip.go +++ b/encoding/gcompress/gcompress_zip.go @@ -10,13 +10,14 @@ import ( "archive/zip" "bytes" "context" - "github.com/gogf/gf/v2/internal/intlog" - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/text/gstr" "io" "os" "path/filepath" "strings" + + "github.com/gogf/gf/v2/internal/intlog" + "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/text/gstr" ) // ZipPath compresses `paths` to `dest` using zip compressing algorithm. diff --git a/encoding/ghash/ghash_bench_test.go b/encoding/ghash/ghash_z_bench_test.go similarity index 100% rename from encoding/ghash/ghash_bench_test.go rename to encoding/ghash/ghash_z_bench_test.go diff --git a/encoding/ghash/ghash_z_unit_basic_test.go b/encoding/ghash/ghash_z_unit_test.go similarity index 100% rename from encoding/ghash/ghash_z_unit_basic_test.go rename to encoding/ghash/ghash_z_unit_test.go diff --git a/encoding/ghtml/ghtml_test.go b/encoding/ghtml/ghtml_z_unit_test.go similarity index 100% rename from encoding/ghtml/ghtml_test.go rename to encoding/ghtml/ghtml_z_unit_test.go index 9d3af14a1..0c70e2a85 100644 --- a/encoding/ghtml/ghtml_test.go +++ b/encoding/ghtml/ghtml_z_unit_test.go @@ -7,10 +7,10 @@ package ghtml_test import ( - "github.com/gogf/gf/v2/frame/g" "testing" "github.com/gogf/gf/v2/encoding/ghtml" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/test/gtest" ) diff --git a/encoding/gini/gini.go b/encoding/gini/gini.go index 55b5325cf..733d9385f 100644 --- a/encoding/gini/gini.go +++ b/encoding/gini/gini.go @@ -11,11 +11,12 @@ import ( "bufio" "bytes" "fmt" + "io" + "strings" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/json" - "io" - "strings" ) // Decode converts INI format to map. diff --git a/encoding/gini/gini_test.go b/encoding/gini/gini_z_unit_test.go similarity index 99% rename from encoding/gini/gini_test.go rename to encoding/gini/gini_z_unit_test.go index e080d8900..2a3239bce 100644 --- a/encoding/gini/gini_test.go +++ b/encoding/gini/gini_z_unit_test.go @@ -7,10 +7,11 @@ package gini_test import ( + "testing" + "github.com/gogf/gf/v2/encoding/gini" "github.com/gogf/gf/v2/encoding/gjson" "github.com/gogf/gf/v2/test/gtest" - "testing" ) var iniContent = ` diff --git a/encoding/gjson/gjson.go b/encoding/gjson/gjson.go index 392dfb2bd..622d45793 100644 --- a/encoding/gjson/gjson.go +++ b/encoding/gjson/gjson.go @@ -8,12 +8,12 @@ package gjson import ( - "github.com/gogf/gf/v2/internal/utils" "reflect" "strconv" "strings" "github.com/gogf/gf/v2/internal/rwmutex" + "github.com/gogf/gf/v2/internal/utils" "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" ) diff --git a/encoding/gjson/gjson_api.go b/encoding/gjson/gjson_api.go index b08a13947..c08c75d15 100644 --- a/encoding/gjson/gjson_api.go +++ b/encoding/gjson/gjson_api.go @@ -8,11 +8,11 @@ package gjson import ( "fmt" + + "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/util/gutil" - - "github.com/gogf/gf/v2/container/gvar" ) // Interface returns the json value. diff --git a/encoding/gjson/gjson_api_new_load.go b/encoding/gjson/gjson_api_new_load.go index 3bbc6d912..78eb38c25 100644 --- a/encoding/gjson/gjson_api_new_load.go +++ b/encoding/gjson/gjson_api_new_load.go @@ -8,18 +8,17 @@ package gjson import ( "bytes" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/internal/utils" "reflect" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/encoding/gini" "github.com/gogf/gf/v2/encoding/gtoml" "github.com/gogf/gf/v2/encoding/gxml" "github.com/gogf/gf/v2/encoding/gyaml" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/rwmutex" + "github.com/gogf/gf/v2/internal/utils" "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/text/gregex" "github.com/gogf/gf/v2/util/gconv" @@ -178,7 +177,7 @@ func LoadContentType(dataType string, data interface{}, safe ...bool) (*Json, er if len(content) == 0 { return New(nil, safe...), nil } - //ignore UTF8-BOM + // ignore UTF8-BOM if content[0] == 0xEF && content[1] == 0xBB && content[2] == 0xBF { content = content[3:] } @@ -217,7 +216,7 @@ func loadContentTypeWithOptions(dataType string, data interface{}, options Optio if len(content) == 0 { return NewWithOptions(nil, options), nil } - //ignore UTF8-BOM + // ignore UTF8-BOM if content[0] == 0xEF && content[1] == 0xBB && content[2] == 0xBF { content = content[3:] } diff --git a/encoding/gjson/gjson_stdlib_json_util.go b/encoding/gjson/gjson_stdlib_json_util.go index 33d7c7481..097d9cff2 100644 --- a/encoding/gjson/gjson_stdlib_json_util.go +++ b/encoding/gjson/gjson_stdlib_json_util.go @@ -8,6 +8,7 @@ package gjson import ( "bytes" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/util/gconv" ) @@ -43,7 +44,7 @@ func DecodeTo(data interface{}, v interface{}) error { // Do not use number, it converts float64 to json.Number type, // which actually a string type. It causes converting issue for other data formats, // for example: yaml. - //decoder.UseNumber() + // decoder.UseNumber() return decoder.Decode(v) } diff --git a/encoding/gjson/gjson_z_example_conversion_test.go b/encoding/gjson/gjson_z_example_conversion_test.go index 9c3ec2f90..4fbfa05a6 100644 --- a/encoding/gjson/gjson_z_example_conversion_test.go +++ b/encoding/gjson/gjson_z_example_conversion_test.go @@ -8,6 +8,7 @@ package gjson_test import ( "fmt" + "github.com/gogf/gf/v2/encoding/gjson" ) diff --git a/encoding/gjson/gjson_z_example_dataset_test.go b/encoding/gjson/gjson_z_example_dataset_test.go index 779dc4493..a15ef4c80 100644 --- a/encoding/gjson/gjson_z_example_dataset_test.go +++ b/encoding/gjson/gjson_z_example_dataset_test.go @@ -8,6 +8,7 @@ package gjson_test import ( "fmt" + "github.com/gogf/gf/v2/encoding/gjson" ) diff --git a/encoding/gjson/gjson_z_example_load_test.go b/encoding/gjson/gjson_z_example_load_test.go index 4a304a846..84deb1fee 100644 --- a/encoding/gjson/gjson_z_example_load_test.go +++ b/encoding/gjson/gjson_z_example_load_test.go @@ -8,6 +8,7 @@ package gjson_test import ( "fmt" + "github.com/gogf/gf/v2/debug/gdebug" "github.com/gogf/gf/v2/encoding/gjson" ) diff --git a/encoding/gjson/gjson_z_example_new_test.go b/encoding/gjson/gjson_z_example_new_test.go index 9aee73f85..644e567c4 100644 --- a/encoding/gjson/gjson_z_example_new_test.go +++ b/encoding/gjson/gjson_z_example_new_test.go @@ -8,6 +8,7 @@ package gjson_test import ( "fmt" + "github.com/gogf/gf/v2/encoding/gjson" ) diff --git a/encoding/gjson/gjson_z_example_pattern_test.go b/encoding/gjson/gjson_z_example_pattern_test.go index 6a8b8b49c..e6bc4aa91 100644 --- a/encoding/gjson/gjson_z_example_pattern_test.go +++ b/encoding/gjson/gjson_z_example_pattern_test.go @@ -8,6 +8,7 @@ package gjson_test import ( "fmt" + "github.com/gogf/gf/v2/encoding/gjson" ) diff --git a/encoding/gjson/gjson_z_unit_json_test.go b/encoding/gjson/gjson_z_unit_feature_json_test.go similarity index 99% rename from encoding/gjson/gjson_z_unit_json_test.go rename to encoding/gjson/gjson_z_unit_feature_json_test.go index aaf5f00bd..7a9b0429e 100644 --- a/encoding/gjson/gjson_z_unit_json_test.go +++ b/encoding/gjson/gjson_z_unit_feature_json_test.go @@ -7,11 +7,12 @@ package gjson_test import ( + "testing" + "github.com/gogf/gf/v2/encoding/gjson" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/text/gstr" - "testing" ) func Test_ToJson(t *testing.T) { diff --git a/encoding/gjson/gjson_z_unit_load_test.go b/encoding/gjson/gjson_z_unit_feature_load_test.go similarity index 100% rename from encoding/gjson/gjson_z_unit_load_test.go rename to encoding/gjson/gjson_z_unit_feature_load_test.go diff --git a/encoding/gjson/gjson_z_unit_new_test.go b/encoding/gjson/gjson_z_unit_feature_new_test.go similarity index 100% rename from encoding/gjson/gjson_z_unit_new_test.go rename to encoding/gjson/gjson_z_unit_feature_new_test.go diff --git a/encoding/gjson/gjson_z_unit_set_test.go b/encoding/gjson/gjson_z_unit_feature_set_test.go similarity index 100% rename from encoding/gjson/gjson_z_unit_set_test.go rename to encoding/gjson/gjson_z_unit_feature_set_test.go index 6b1b340c1..c1d22926c 100644 --- a/encoding/gjson/gjson_z_unit_set_test.go +++ b/encoding/gjson/gjson_z_unit_feature_set_test.go @@ -8,12 +8,12 @@ package gjson_test import ( "bytes" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/test/gtest" - "github.com/gogf/gf/v2/text/gstr" "testing" "github.com/gogf/gf/v2/encoding/gjson" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/text/gstr" ) func Test_Set1(t *testing.T) { diff --git a/encoding/gjson/gjson_z_unit_struct_test.go b/encoding/gjson/gjson_z_unit_feature_struct_test.go similarity index 99% rename from encoding/gjson/gjson_z_unit_struct_test.go rename to encoding/gjson/gjson_z_unit_feature_struct_test.go index 0cc00d3c7..f6e2b7415 100644 --- a/encoding/gjson/gjson_z_unit_struct_test.go +++ b/encoding/gjson/gjson_z_unit_feature_struct_test.go @@ -7,9 +7,10 @@ package gjson_test import ( + "testing" + "github.com/gogf/gf/v2/encoding/gjson" "github.com/gogf/gf/v2/test/gtest" - "testing" ) func Test_GetScan(t *testing.T) { diff --git a/encoding/gjson/gjson_z_unit_implements_test.go b/encoding/gjson/gjson_z_unit_implements_test.go index a38eec1a9..a29f8244a 100644 --- a/encoding/gjson/gjson_z_unit_implements_test.go +++ b/encoding/gjson/gjson_z_unit_implements_test.go @@ -7,13 +7,13 @@ package gjson_test import ( - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/util/gconv" "testing" "github.com/gogf/gf/v2/encoding/gjson" "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gconv" ) func TestJson_UnmarshalJSON(t *testing.T) { diff --git a/encoding/gjson/gjson_z_unit_internal_test.go b/encoding/gjson/gjson_z_unit_internal_test.go index b195fc342..853b839c0 100644 --- a/encoding/gjson/gjson_z_unit_internal_test.go +++ b/encoding/gjson/gjson_z_unit_internal_test.go @@ -7,8 +7,9 @@ package gjson import ( - "github.com/gogf/gf/v2/test/gtest" "testing" + + "github.com/gogf/gf/v2/test/gtest" ) func Test_checkDataType(t *testing.T) { @@ -80,11 +81,11 @@ dd = 11 "gf.gvalid.rule.not-in" = "The :attribute value is not in acceptable range" "gf.gvalid.rule.regex" = "The :attribute value is invalid" `) - //fmt.Println(gregex.IsMatch(`^[\s\t\n\r]*[\w\-]+\s*:\s*".+"`, data)) - //fmt.Println(gregex.IsMatch(`^[\s\t\n\r]*[\w\-]+\s*:\s*\w+`, data)) - //fmt.Println(gregex.IsMatch(`[\s\t\n\r]+[\w\-]+\s*:\s*".+"`, data)) - //fmt.Println(gregex.IsMatch(`[\n\r]+[\w\-\s\t]+\s*:\s*\w+`, data)) - //fmt.Println(gregex.MatchString(`[\n\r]+[\w\-\s\t]+\s*:\s*\w+`, string(data))) + // fmt.Println(gregex.IsMatch(`^[\s\t\n\r]*[\w\-]+\s*:\s*".+"`, data)) + // fmt.Println(gregex.IsMatch(`^[\s\t\n\r]*[\w\-]+\s*:\s*\w+`, data)) + // fmt.Println(gregex.IsMatch(`[\s\t\n\r]+[\w\-]+\s*:\s*".+"`, data)) + // fmt.Println(gregex.IsMatch(`[\n\r]+[\w\-\s\t]+\s*:\s*\w+`, data)) + // fmt.Println(gregex.MatchString(`[\n\r]+[\w\-\s\t]+\s*:\s*\w+`, string(data))) t.Assert(checkDataType(data), "toml") }) diff --git a/encoding/gjson/gjson_z_unit_basic_test.go b/encoding/gjson/gjson_z_unit_test.go similarity index 99% rename from encoding/gjson/gjson_z_unit_basic_test.go rename to encoding/gjson/gjson_z_unit_test.go index 88c47cd48..dfdc2cc55 100644 --- a/encoding/gjson/gjson_z_unit_basic_test.go +++ b/encoding/gjson/gjson_z_unit_test.go @@ -7,9 +7,9 @@ package gjson_test import ( - "github.com/gogf/gf/v2/container/gmap" "testing" + "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/encoding/gjson" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/test/gtest" @@ -372,7 +372,7 @@ func Test_Convert2(t *testing.T) { err := j.Var().Scan(&name) t.Assert(err, nil) t.Assert(name.Name, "gf") - //j.Dump() + // j.Dump() t.Assert(err, nil) j = gjson.New(`{"person":{"name":"gf"}}`) @@ -381,7 +381,7 @@ func Test_Convert2(t *testing.T) { t.Assert(name.Name, "gf") j = gjson.New(`{"name":"gf""}`) - //j.Dump() + // j.Dump() t.Assert(err, nil) j = gjson.New(`[1,2,3]`) diff --git a/encoding/gtoml/gtoml.go b/encoding/gtoml/gtoml.go index d04d14897..fe636f610 100644 --- a/encoding/gtoml/gtoml.go +++ b/encoding/gtoml/gtoml.go @@ -9,9 +9,10 @@ package gtoml import ( "bytes" - "github.com/gogf/gf/v2/internal/json" "github.com/BurntSushi/toml" + + "github.com/gogf/gf/v2/internal/json" ) func Encode(v interface{}) ([]byte, error) { diff --git a/encoding/gtoml/gtoml_test.go b/encoding/gtoml/gtoml_z_unit_test.go similarity index 99% rename from encoding/gtoml/gtoml_test.go rename to encoding/gtoml/gtoml_z_unit_test.go index a133b1d38..9a051e074 100644 --- a/encoding/gtoml/gtoml_test.go +++ b/encoding/gtoml/gtoml_z_unit_test.go @@ -6,10 +6,11 @@ package gtoml_test import ( + "testing" + "github.com/gogf/gf/v2/encoding/gjson" "github.com/gogf/gf/v2/encoding/gtoml" "github.com/gogf/gf/v2/test/gtest" - "testing" ) var tomlStr string = ` diff --git a/encoding/gurl/url.go b/encoding/gurl/url.go index 2e3d2d508..031c4e194 100644 --- a/encoding/gurl/url.go +++ b/encoding/gurl/url.go @@ -27,25 +27,27 @@ func Decode(str string) (string, error) { return url.QueryUnescape(str) } +// RawEncode does encode the given string according // URL-encode according to RFC 3986. // See http://php.net/manual/en/function.rawurlencode.php. func RawEncode(str string) string { return strings.Replace(url.QueryEscape(str), "+", "%20", -1) } +// RawDecode does decode the given string // Decode URL-encoded strings. // See http://php.net/manual/en/function.rawurldecode.php. func RawDecode(str string) (string, error) { return url.QueryUnescape(strings.Replace(str, "%20", "+", -1)) } -// Generate URL-encoded query string. +// BuildQuery Generate URL-encoded query string. // See http://php.net/manual/en/function.http-build-query.php. func BuildQuery(queryData url.Values) string { return queryData.Encode() } -// Parse a URL and return its components. +// ParseURL Parse a URL and return its components. // -1: all; 1: scheme; 2: host; 4: port; 8: user; 16: pass; 32: path; 64: query; 128: fragment. // See http://php.net/manual/en/function.parse-url.php. func ParseURL(str string, component int) (map[string]string, error) { diff --git a/encoding/gurl/url_test.go b/encoding/gurl/url_z_unit_test.go similarity index 100% rename from encoding/gurl/url_test.go rename to encoding/gurl/url_z_unit_test.go diff --git a/encoding/gxml/gxml.go b/encoding/gxml/gxml.go index 9dc9a5780..f1c61d441 100644 --- a/encoding/gxml/gxml.go +++ b/encoding/gxml/gxml.go @@ -11,6 +11,7 @@ import ( "strings" "github.com/clbanning/mxj/v2" + "github.com/gogf/gf/v2/encoding/gcharset" "github.com/gogf/gf/v2/text/gregex" ) @@ -63,9 +64,8 @@ func ToJson(content []byte) ([]byte, error) { mv, err := mxj.NewMapXml(res) if err == nil { return mv.Json() - } else { - return nil, err } + return nil, err } // convert does convert the encoding of given XML content from XML root tag into UTF-8 encoding content. diff --git a/encoding/gxml/gxml_test.go b/encoding/gxml/gxml_z_unit_test.go similarity index 98% rename from encoding/gxml/gxml_test.go rename to encoding/gxml/gxml_z_unit_test.go index 6d4b18c62..35a80e32a 100644 --- a/encoding/gxml/gxml_test.go +++ b/encoding/gxml/gxml_z_unit_test.go @@ -8,11 +8,11 @@ package gxml_test import ( "bytes" - "github.com/gogf/gf/v2/encoding/gjson" "strings" "testing" "github.com/gogf/gf/v2/encoding/gcharset" + "github.com/gogf/gf/v2/encoding/gjson" "github.com/gogf/gf/v2/encoding/gxml" "github.com/gogf/gf/v2/test/gtest" ) @@ -146,7 +146,7 @@ func Test_Encode(t *testing.T) { if err != nil { t.Errorf("encode error.") } - //t.Logf("%s\n", string(xmlStr)) + // t.Logf("%s\n", string(xmlStr)) res := `true100.92123hello world` if string(xmlStr) != res { @@ -169,7 +169,7 @@ func Test_EncodeIndent(t *testing.T) { t.Errorf("encodeWithIndent error.") } - //t.Logf("%s\n", string(xmlStr)) + // t.Logf("%s\n", string(xmlStr)) } diff --git a/encoding/gyaml/gyaml.go b/encoding/gyaml/gyaml.go index 3dfe52879..143834dc0 100644 --- a/encoding/gyaml/gyaml.go +++ b/encoding/gyaml/gyaml.go @@ -8,10 +8,10 @@ package gyaml import ( - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/internal/json" "gopkg.in/yaml.v3" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/util/gconv" ) diff --git a/encoding/gyaml/gyaml_test.go b/encoding/gyaml/gyaml_z_unit_test.go similarity index 99% rename from encoding/gyaml/gyaml_test.go rename to encoding/gyaml/gyaml_z_unit_test.go index 5e9983d41..2e4c8c666 100644 --- a/encoding/gyaml/gyaml_test.go +++ b/encoding/gyaml/gyaml_z_unit_test.go @@ -7,13 +7,12 @@ package gyaml_test import ( - "github.com/gogf/gf/v2/encoding/gjson" - "github.com/gogf/gf/v2/internal/json" "testing" - "github.com/gogf/gf/v2/frame/g" - + "github.com/gogf/gf/v2/encoding/gjson" "github.com/gogf/gf/v2/encoding/gyaml" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" ) diff --git a/errors/gcode/gcode_test.go b/errors/gcode/gcode_z_unit_test.go similarity index 100% rename from errors/gcode/gcode_test.go rename to errors/gcode/gcode_z_unit_test.go index 0ce6e34bc..b8690455f 100644 --- a/errors/gcode/gcode_test.go +++ b/errors/gcode/gcode_z_unit_test.go @@ -7,9 +7,9 @@ package gcode_test import ( - "github.com/gogf/gf/v2/errors/gcode" "testing" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/test/gtest" ) diff --git a/errors/gerror/gerror.go b/errors/gerror/gerror.go index b5eb012f3..85b80b465 100644 --- a/errors/gerror/gerror.go +++ b/errors/gerror/gerror.go @@ -6,12 +6,13 @@ // Package gerror provides simple functions to manipulate errors. // -// 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. +// 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 ( "fmt" + "github.com/gogf/gf/v2/errors/gcode" ) diff --git a/errors/gerror/gerror_error.go b/errors/gerror/gerror_error.go index 5de926eda..55111edab 100644 --- a/errors/gerror/gerror_error.go +++ b/errors/gerror/gerror_error.go @@ -10,18 +10,19 @@ import ( "bytes" "errors" "fmt" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/internal/utils" "io" "runtime" "strings" + + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/internal/utils" ) // Error is custom error for additional features. type Error struct { error error // Wrapped error. stack stack // Stack array, which records the stack information when this error is created or wrapped. - text string // Error text, which is created by New* functions. + text string // Custom Error text when Error is created, might be empty when its code is not nil. code gcode.Code // Error code if necessary. } @@ -31,8 +32,7 @@ const ( ) var ( - // goRootForFilter is used for stack filtering purpose. - // Mainly for development environment. + // goRootForFilter is used for stack filtering in development environment purpose. goRootForFilter = runtime.GOROOT() ) @@ -107,18 +107,18 @@ func (err *Error) Format(s fmt.State, verb rune) { switch { case s.Flag('-'): if err.text != "" { - io.WriteString(s, err.text) + _, _ = io.WriteString(s, err.text) } else { - io.WriteString(s, err.Error()) + _, _ = io.WriteString(s, err.Error()) } case s.Flag('+'): if verb == 's' { - io.WriteString(s, err.Stack()) + _, _ = io.WriteString(s, err.Stack()) } else { - io.WriteString(s, err.Error()+"\n"+err.Stack()) + _, _ = io.WriteString(s, err.Error()+"\n"+err.Stack()) } default: - io.WriteString(s, err.Error()) + _, _ = io.WriteString(s, err.Error()) } } } @@ -176,6 +176,14 @@ func (err *Error) Next() error { return err.error } +// SetCode updates the internal code with given code. +func (err *Error) SetCode(code gcode.Code) { + if err == nil { + return + } + err.code = code +} + // MarshalJSON implements the interface MarshalJSON for json.Marshal. // Note that do not use pointer as its receiver here. func (err *Error) MarshalJSON() ([]byte, error) { diff --git a/errors/gerror/gerror_z_bench_test.go b/errors/gerror/gerror_z_bench_test.go index db0cab491..5046b8a4d 100644 --- a/errors/gerror/gerror_z_bench_test.go +++ b/errors/gerror/gerror_z_bench_test.go @@ -8,9 +8,10 @@ package gerror_test import ( "errors" + "testing" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" - "testing" ) var ( diff --git a/errors/gerror/gerror_z_example_test.go b/errors/gerror/gerror_z_example_test.go index 7423855ea..e43338e9c 100644 --- a/errors/gerror/gerror_z_example_test.go +++ b/errors/gerror/gerror_z_example_test.go @@ -9,6 +9,7 @@ package gerror_test import ( "errors" "fmt" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" ) diff --git a/errors/gerror/gerror_z_unit_test.go b/errors/gerror/gerror_z_unit_test.go index cba6e72be..f4aa6b2df 100644 --- a/errors/gerror/gerror_z_unit_test.go +++ b/errors/gerror/gerror_z_unit_test.go @@ -9,11 +9,11 @@ package gerror_test import ( "errors" "fmt" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/internal/json" "testing" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" ) @@ -209,13 +209,13 @@ func Test_Stack(t *testing.T) { err = gerror.Wrap(err, "2") err = gerror.Wrap(err, "3") t.AssertNE(err, nil) - //fmt.Printf("%+v", err) + // fmt.Printf("%+v", err) }) gtest.C(t, func(t *gtest.T) { err := gerror.New("1") t.AssertNE(fmt.Sprintf("%+v", err), "1") - //fmt.Printf("%+v", err) + // fmt.Printf("%+v", err) }) gtest.C(t, func(t *gtest.T) { @@ -223,7 +223,7 @@ func Test_Stack(t *testing.T) { err = gerror.Wrap(err, "2") err = gerror.Wrap(err, "3") t.AssertNE(err, nil) - //fmt.Printf("%+v", err) + // fmt.Printf("%+v", err) }) } @@ -311,6 +311,18 @@ func Test_Code(t *testing.T) { }) } +func Test_SetCode(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + err := gerror.New("123") + t.Assert(gerror.Code(err), -1) + t.Assert(err.Error(), "123") + + err.(*gerror.Error).SetCode(gcode.CodeValidationFailed) + t.Assert(gerror.Code(err), gcode.CodeValidationFailed) + t.Assert(err.Error(), "123") + }) +} + func Test_Json(t *testing.T) { gtest.C(t, func(t *gtest.T) { err := gerror.Wrap(gerror.New("1"), "2") diff --git a/frame/g/g.go b/frame/g/g.go index 9cad10f3b..e2e6d2f3f 100644 --- a/frame/g/g.go +++ b/frame/g/g.go @@ -8,6 +8,7 @@ package g import ( "context" + "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/util/gmeta" ) diff --git a/frame/g/g_func.go b/frame/g/g_func.go index 0c4887dfc..4d90b9f79 100644 --- a/frame/g/g_func.go +++ b/frame/g/g_func.go @@ -8,6 +8,7 @@ package g import ( "context" + "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/internal/empty" "github.com/gogf/gf/v2/net/ghttp" diff --git a/frame/gins/gins_database.go b/frame/gins/gins_database.go index a1d57e99d..e807188fc 100644 --- a/frame/gins/gins_database.go +++ b/frame/gins/gins_database.go @@ -9,16 +9,16 @@ package gins import ( "context" "fmt" + + "github.com/gogf/gf/v2/database/gdb" "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/os/gcfg" - "github.com/gogf/gf/v2/text/gstr" - "github.com/gogf/gf/v2/util/gutil" - - "github.com/gogf/gf/v2/database/gdb" "github.com/gogf/gf/v2/text/gregex" + "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" + "github.com/gogf/gf/v2/util/gutil" ) const ( diff --git a/frame/gins/gins_log.go b/frame/gins/gins_log.go index cbe175d58..a1a3938f0 100644 --- a/frame/gins/gins_log.go +++ b/frame/gins/gins_log.go @@ -9,6 +9,7 @@ package gins import ( "context" "fmt" + "github.com/gogf/gf/v2/os/glog" "github.com/gogf/gf/v2/util/gutil" ) diff --git a/frame/gins/gins_redis.go b/frame/gins/gins_redis.go index 9bc4afcfa..6d67b59ac 100644 --- a/frame/gins/gins_redis.go +++ b/frame/gins/gins_redis.go @@ -9,6 +9,7 @@ package gins import ( "context" "fmt" + "github.com/gogf/gf/v2/database/gredis" "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" diff --git a/frame/gins/gins_server.go b/frame/gins/gins_server.go index 91b0fe38f..4c176d373 100644 --- a/frame/gins/gins_server.go +++ b/frame/gins/gins_server.go @@ -9,6 +9,7 @@ package gins import ( "context" "fmt" + "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/util/gconv" @@ -60,7 +61,7 @@ func Server(name ...interface{}) *ghttp.Server { } } else { // The configuration is not necessary, so it just prints internal logs. - intlog.Printf(ctx, `missing configuration for HTTP server "%s"`, instanceName) + intlog.Printf(ctx, `missing configuration from configuration component for HTTP server "%s"`, instanceName) } // Server logger configuration checks. diff --git a/frame/gins/gins_view.go b/frame/gins/gins_view.go index bc62d19aa..b9e3b0e6a 100644 --- a/frame/gins/gins_view.go +++ b/frame/gins/gins_view.go @@ -9,6 +9,7 @@ package gins import ( "context" "fmt" + "github.com/gogf/gf/v2/os/gview" "github.com/gogf/gf/v2/util/gutil" ) diff --git a/frame/gins/gins_z_unit_config_test.go b/frame/gins/gins_z_unit_config_test.go index 38099d311..848cbd92a 100644 --- a/frame/gins/gins_z_unit_config_test.go +++ b/frame/gins/gins_z_unit_config_test.go @@ -9,13 +9,12 @@ package gins_test import ( "context" "fmt" - "github.com/gogf/gf/v2/debug/gdebug" - "github.com/gogf/gf/v2/frame/gins" "testing" "time" + "github.com/gogf/gf/v2/debug/gdebug" + "github.com/gogf/gf/v2/frame/gins" "github.com/gogf/gf/v2/os/gcfg" - "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" diff --git a/frame/gins/gins_z_unit_database_test.go b/frame/gins/gins_z_unit_database_test.go index edd76427c..622e10fed 100644 --- a/frame/gins/gins_z_unit_database_test.go +++ b/frame/gins/gins_z_unit_database_test.go @@ -7,14 +7,14 @@ package gins_test import ( - "github.com/gogf/gf/v2/debug/gdebug" - "github.com/gogf/gf/v2/frame/gins" - "github.com/gogf/gf/v2/os/gcfg" - "github.com/gogf/gf/v2/os/gtime" "testing" "time" + "github.com/gogf/gf/v2/debug/gdebug" + "github.com/gogf/gf/v2/frame/gins" + "github.com/gogf/gf/v2/os/gcfg" "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" ) @@ -41,7 +41,7 @@ func Test_Database(t *testing.T) { // for gfsnotify callbacks to refresh cache of config file time.Sleep(500 * time.Millisecond) - //fmt.Println("gins Test_Database", Config().Get("test")) + // fmt.Println("gins Test_Database", Config().Get("test")) dbDefault := gins.Database() dbTest := gins.Database("test") diff --git a/frame/gins/gins_z_unit_redis_test.go b/frame/gins/gins_z_unit_redis_test.go index cc2bfa417..f69936622 100644 --- a/frame/gins/gins_z_unit_redis_test.go +++ b/frame/gins/gins_z_unit_redis_test.go @@ -7,14 +7,14 @@ package gins_test import ( - "github.com/gogf/gf/v2/debug/gdebug" - "github.com/gogf/gf/v2/frame/gins" - "github.com/gogf/gf/v2/os/gcfg" - "github.com/gogf/gf/v2/os/gtime" "testing" "time" + "github.com/gogf/gf/v2/debug/gdebug" + "github.com/gogf/gf/v2/frame/gins" + "github.com/gogf/gf/v2/os/gcfg" "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" ) @@ -42,7 +42,7 @@ func Test_Redis(t *testing.T) { // for gfsnotify callbacks to refresh cache of config file time.Sleep(500 * time.Millisecond) - //fmt.Println("gins Test_Redis", Config().Get("test")) + // fmt.Println("gins Test_Redis", Config().Get("test")) var ( redisDefault = gins.Redis() diff --git a/frame/gins/gins_z_unit_basic_test.go b/frame/gins/gins_z_unit_test.go similarity index 100% rename from frame/gins/gins_z_unit_basic_test.go rename to frame/gins/gins_z_unit_test.go index c6ef3b01f..f6a674e70 100644 --- a/frame/gins/gins_z_unit_basic_test.go +++ b/frame/gins/gins_z_unit_test.go @@ -7,9 +7,9 @@ package gins_test import ( - "github.com/gogf/gf/v2/frame/gins" "testing" + "github.com/gogf/gf/v2/frame/gins" "github.com/gogf/gf/v2/test/gtest" ) diff --git a/frame/gins/gins_z_unit_view_test.go b/frame/gins/gins_z_unit_view_test.go index c77f64fb0..f14c10f70 100644 --- a/frame/gins/gins_z_unit_view_test.go +++ b/frame/gins/gins_z_unit_view_test.go @@ -9,10 +9,10 @@ package gins import ( "context" "fmt" - "github.com/gogf/gf/v2/debug/gdebug" - "github.com/gogf/gf/v2/os/gcfg" "testing" + "github.com/gogf/gf/v2/debug/gdebug" + "github.com/gogf/gf/v2/os/gcfg" "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" diff --git a/go.mod b/go.mod index 002be54d1..9f792ae5e 100644 --- a/go.mod +++ b/go.mod @@ -5,16 +5,16 @@ go 1.14 require ( github.com/BurntSushi/toml v0.4.1 github.com/clbanning/mxj/v2 v2.5.5 - github.com/fatih/color v1.12.0 + github.com/fatih/color v1.13.0 github.com/fsnotify/fsnotify v1.5.1 - github.com/go-redis/redis/v8 v8.11.3 + github.com/go-redis/redis/v8 v8.11.4 github.com/go-sql-driver/mysql v1.6.0 github.com/gorilla/websocket v1.4.2 github.com/grokify/html-strip-tags-go v0.0.1 github.com/olekukonko/tablewriter v0.0.5 - go.opentelemetry.io/otel v1.0.0 - go.opentelemetry.io/otel/trace v1.0.0 - golang.org/x/net v0.0.0-20210520170846-37e1c6afe023 - golang.org/x/text v0.3.6 + go.opentelemetry.io/otel v1.2.0 + go.opentelemetry.io/otel/trace v1.2.0 + golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2 + golang.org/x/text v0.3.8-0.20211105212822-18b340fc7af2 gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b ) diff --git a/go.sum b/go.sum index af0926c5d..285db7672 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,7 @@ github.com/BurntSushi/toml v0.4.1 h1:GaI7EiDXDRfa8VshkTj7Fym7ha+y8/XxIgD2okUIjLw= github.com/BurntSushi/toml v0.4.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= -github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= -github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE= +github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/clbanning/mxj/v2 v2.5.5 h1:oT81vUeEiQQ/DcHbzSytRngP6Ky9O+L+0Bw0zSJag9E= github.com/clbanning/mxj/v2 v2.5.5/go.mod h1:hNiWqW14h+kc+MdF9C6/YoRfjEJoR3ou6tn/Qo+ve2s= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -9,14 +9,14 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= -github.com/fatih/color v1.12.0 h1:mRhaKNwANqRgUBGKmnI5ZxEk7QXmjQeCcuYFMX2bfcc= -github.com/fatih/color v1.12.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM= +github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w= +github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= 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-redis/redis/v8 v8.11.3 h1:GCjoYp8c+yQTJfc0n69iwSiHjvuAdruxl7elnZCxgt8= -github.com/go-redis/redis/v8 v8.11.3/go.mod h1:xNJ9xDG09FsIPwh3bWdk+0oDWHbtF9rPN0F/oD9XeKc= +github.com/go-redis/redis/v8 v8.11.4 h1:kHoYkfZP6+pe04aFTnhDH6GDROa5yJdHJVNxV3F46Tg= +github.com/go-redis/redis/v8 v8.11.4/go.mod h1:2Z2wHZXdQpCDXEGzqMockDpNyYvi2l4Pxt6RJr792+w= 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/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= @@ -41,10 +41,11 @@ github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/ad github.com/grokify/html-strip-tags-go v0.0.1 h1:0fThFwLbW7P/kOiTBs03FsJSV9RM2M/Q/MOnCQxKMo0= github.com/grokify/html-strip-tags-go v0.0.1/go.mod h1:2Su6romC5/1VXOQMaWL2yb618ARB8iVo6/DR99A6d78= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/mattn/go-colorable v0.1.8 h1:c1ghPdyEDarC70ftn0y+A/Ee++9zz8ljHG1b13eJ0s8= -github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= -github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= +github.com/mattn/go-colorable v0.1.9 h1:sqDoxXbdeALODt0DAeJCVp38ps9ZogZEAXjus69YV3U= +github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y= +github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= @@ -58,8 +59,8 @@ github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc= github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= -github.com/onsi/gomega v1.15.0 h1:WjP/FQ/sk43MRmnEcT+MlDw2TFvkrXlprrPST/IudjU= -github.com/onsi/gomega v1.15.0/go.mod h1:cIuvLEne0aoVhAgh/O6ac0Op8WWw9H6eYCriF+tEHG0= +github.com/onsi/gomega v1.16.0 h1:6gjqkI8iiRHMvdccRJM8rVKjCWk6ZIm6FTm3ddIe4/c= +github.com/onsi/gomega v1.16.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -67,25 +68,29 @@ github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5 github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -go.opentelemetry.io/otel v1.0.0 h1:qTTn6x71GVBvoafHK/yaRUmFzI4LcONZD0/kXxl5PHI= -go.opentelemetry.io/otel v1.0.0/go.mod h1:AjRVh9A5/5DE7S+mZtTR6t8vpKKryam+0lREnfmS4cg= -go.opentelemetry.io/otel/trace v1.0.0 h1:TSBr8GTEtKevYMG/2d21M989r5WJYVimhTHBKVEZuh4= -go.opentelemetry.io/otel/trace v1.0.0/go.mod h1:PXTWqayeFUlJV1YDNhsJYB184+IvAH814St6o6ajzIs= +github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +go.opentelemetry.io/otel v1.2.0 h1:YOQDvxO1FayUcT9MIhJhgMyNO1WqoduiyvQHzGN0kUQ= +go.opentelemetry.io/otel v1.2.0/go.mod h1:aT17Fk0Z1Nor9e0uisf98LrntPGMnk4frBO9+dkf69I= +go.opentelemetry.io/otel/trace v1.2.0 h1:Ys3iqbqZhcf28hHzrm5WAquMkDHNZTUkw7KHbuNjej0= +go.opentelemetry.io/otel/trace v1.2.0/go.mod h1:N5FLswTubnxKxOJHM7XZC074qpeEdLy3CgAVsdMucK0= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= -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/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2 h1:CIJ76btIcR3eFI5EgSo6k1qKw9KJexJuRLI9G7Hp5wE= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -99,16 +104,19 @@ golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 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/sys v0.0.0-20210809222454-d867a43fc93e h1:WUoyKPm6nCo1BnNUvPGnFG3T5DUVem42yDJZZ4CNxMA= +golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.8-0.20211105212822-18b340fc7af2 h1:GLw7MR8AfAG2GmGcmVgObFOHXYypgGjnGno25RDwn3Y= +golang.org/x/text v0.3.8-0.20211105212822-18b340fc7af2/go.mod h1:EFNZuWvGYxIRUEX+K8UmCFwYmZjqcrnq15ZuVldZkZ0= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -133,7 +141,6 @@ gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/i18n/gi18n/gi18n_manager.go b/i18n/gi18n/gi18n_manager.go index 81bc954f0..b632734af 100644 --- a/i18n/gi18n/gi18n_manager.go +++ b/i18n/gi18n/gi18n_manager.go @@ -9,22 +9,18 @@ package gi18n import ( "context" "fmt" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/internal/intlog" "strings" "sync" - "github.com/gogf/gf/v2/os/gfsnotify" - - "github.com/gogf/gf/v2/text/gregex" - - "github.com/gogf/gf/v2/util/gconv" - "github.com/gogf/gf/v2/encoding/gjson" - + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/os/gfsnotify" "github.com/gogf/gf/v2/os/gres" + "github.com/gogf/gf/v2/text/gregex" + "github.com/gogf/gf/v2/util/gconv" ) // Manager for i18n contents, it is concurrent safe, supporting hot reload. diff --git a/i18n/gi18n/gi18n_unit_test.go b/i18n/gi18n/gi18n_z_unit_test.go similarity index 99% rename from i18n/gi18n/gi18n_unit_test.go rename to i18n/gi18n/gi18n_z_unit_test.go index 7ea3d21b2..c7d5cf22b 100644 --- a/i18n/gi18n/gi18n_unit_test.go +++ b/i18n/gi18n/gi18n_z_unit_test.go @@ -10,21 +10,15 @@ import ( "context" "testing" - "github.com/gogf/gf/v2/os/gres" - - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/util/gconv" - - "github.com/gogf/gf/v2/frame/g" - - "github.com/gogf/gf/v2/i18n/gi18n" - "github.com/gogf/gf/v2/debug/gdebug" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/i18n/gi18n" "github.com/gogf/gf/v2/os/gfile" - - "github.com/gogf/gf/v2/test/gtest" - + "github.com/gogf/gf/v2/os/gres" _ "github.com/gogf/gf/v2/os/gres/testdata/data" + "github.com/gogf/gf/v2/os/gtime" + "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gconv" ) func Test_Basic(t *testing.T) { diff --git a/internal/empty/empty_test.go b/internal/empty/empty_z_unit_test.go similarity index 100% rename from internal/empty/empty_test.go rename to internal/empty/empty_z_unit_test.go diff --git a/internal/intlog/intlog.go b/internal/intlog/intlog.go index e49f6d2c5..602e16000 100644 --- a/internal/intlog/intlog.go +++ b/internal/intlog/intlog.go @@ -11,11 +11,13 @@ import ( "bytes" "context" "fmt" - "github.com/gogf/gf/v2/debug/gdebug" - "github.com/gogf/gf/v2/internal/utils" - "go.opentelemetry.io/otel/trace" "path/filepath" "time" + + "go.opentelemetry.io/otel/trace" + + "github.com/gogf/gf/v2/debug/gdebug" + "github.com/gogf/gf/v2/internal/utils" ) const ( diff --git a/internal/utils/utils_is.go b/internal/utils/utils_is.go index b525df226..b9655b633 100644 --- a/internal/utils/utils_is.go +++ b/internal/utils/utils_is.go @@ -7,13 +7,14 @@ package utils import ( - "github.com/gogf/gf/v2/internal/empty" "reflect" + + "github.com/gogf/gf/v2/internal/empty" ) // IsNil checks whether `value` is nil. func IsNil(value interface{}) bool { - return value == nil + return empty.IsNil(value) } // IsEmpty checks whether `value` is empty. diff --git a/internal/utils/utils_list.go b/internal/utils/utils_list.go new file mode 100644 index 000000000..355ad9f8e --- /dev/null +++ b/internal/utils/utils_list.go @@ -0,0 +1,37 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +package utils + +import "fmt" + +// ListToMapByKey converts `list` to a map[string]interface{} of which key is specified by `key`. +// Note that the item value may be type of slice. +func ListToMapByKey(list []map[string]interface{}, key string) map[string]interface{} { + var ( + s = "" + m = make(map[string]interface{}) + tempMap = make(map[string][]interface{}) + hasMultiValues bool + ) + for _, item := range list { + if k, ok := item[key]; ok { + s = fmt.Sprintf(`%v`, k) + tempMap[s] = append(tempMap[s], item) + if len(tempMap[s]) > 1 { + hasMultiValues = true + } + } + } + for k, v := range tempMap { + if hasMultiValues { + m[k] = v + } else { + m[k] = v[0] + } + } + return m +} diff --git a/internal/utils/utils_map.go b/internal/utils/utils_map.go new file mode 100644 index 000000000..6cb1b6067 --- /dev/null +++ b/internal/utils/utils_map.go @@ -0,0 +1,26 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +package utils + +// MapPossibleItemByKey tries to find the possible key-value pair for given key ignoring cases and symbols. +// +// Note that this function might be of low performance. +func MapPossibleItemByKey(data map[string]interface{}, key string) (foundKey string, foundValue interface{}) { + if len(data) == 0 { + return + } + if v, ok := data[key]; ok { + return key, v + } + // Loop checking. + for k, v := range data { + if EqualFoldWithoutChars(k, key) { + return k, v + } + } + return "", nil +} diff --git a/internal/utils/utils_z_bench_test.go b/internal/utils/utils_z_bench_test.go index fa6c0fcd9..4ad988c28 100644 --- a/internal/utils/utils_z_bench_test.go +++ b/internal/utils/utils_z_bench_test.go @@ -7,9 +7,10 @@ package utils_test import ( - "github.com/gogf/gf/v2/internal/utils" "regexp" "testing" + + "github.com/gogf/gf/v2/internal/utils" ) var ( diff --git a/internal/utils/utils_z_is_test.go b/internal/utils/utils_z_unit_is_test.go similarity index 99% rename from internal/utils/utils_z_is_test.go rename to internal/utils/utils_z_unit_is_test.go index 5b06a70e2..46ac53f3a 100644 --- a/internal/utils/utils_z_is_test.go +++ b/internal/utils/utils_z_unit_is_test.go @@ -7,10 +7,11 @@ package utils_test import ( + "testing" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/internal/utils" "github.com/gogf/gf/v2/test/gtest" - "testing" ) func TestVar_IsNil(t *testing.T) { diff --git a/internal/utils/utils_z_test.go b/internal/utils/utils_z_unit_test.go similarity index 99% rename from internal/utils/utils_z_test.go rename to internal/utils/utils_z_unit_test.go index 27e1892a8..5201e80e1 100644 --- a/internal/utils/utils_z_test.go +++ b/internal/utils/utils_z_unit_test.go @@ -7,11 +7,12 @@ package utils_test import ( - "github.com/gogf/gf/v2/internal/utils" - "github.com/gogf/gf/v2/test/gtest" "io/ioutil" "reflect" "testing" + + "github.com/gogf/gf/v2/internal/utils" + "github.com/gogf/gf/v2/test/gtest" ) func Test_ReadCloser(t *testing.T) { diff --git a/net/ghttp/ghttp.go b/net/ghttp/ghttp.go index 3700112df..0b60cf717 100644 --- a/net/ghttp/ghttp.go +++ b/net/ghttp/ghttp.go @@ -8,15 +8,16 @@ package ghttp import ( + "net/http" + "reflect" + "time" + "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/container/gtype" "github.com/gogf/gf/v2/os/gcache" "github.com/gogf/gf/v2/os/gsession" "github.com/gogf/gf/v2/protocol/goai" "github.com/gorilla/websocket" - "net/http" - "reflect" - "time" ) type ( diff --git a/net/ghttp/ghttp_client_websocket.go b/net/ghttp/ghttp_client_websocket.go index 1f1f228f7..cf99c29e1 100644 --- a/net/ghttp/ghttp_client_websocket.go +++ b/net/ghttp/ghttp_client_websocket.go @@ -7,9 +7,10 @@ package ghttp import ( - "github.com/gorilla/websocket" "net/http" "time" + + "github.com/gorilla/websocket" ) // WebSocketClient wraps the underlying websocket client connection diff --git a/net/ghttp/ghttp_middleware_tracing.go b/net/ghttp/ghttp_middleware_tracing.go index 8826edf15..8f885bf1b 100644 --- a/net/ghttp/ghttp_middleware_tracing.go +++ b/net/ghttp/ghttp_middleware_tracing.go @@ -11,6 +11,12 @@ import ( "io/ioutil" "net/http" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/propagation" + "go.opentelemetry.io/otel/trace" + "github.com/gogf/gf/v2" "github.com/gogf/gf/v2/internal/utils" "github.com/gogf/gf/v2/net/ghttp/internal/client" @@ -18,11 +24,6 @@ import ( "github.com/gogf/gf/v2/net/gtrace" "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/codes" - "go.opentelemetry.io/otel/propagation" - "go.opentelemetry.io/otel/trace" ) const ( @@ -80,13 +81,7 @@ func MiddlewareServerTracing(r *Request) { span.SetStatus(codes.Error, fmt.Sprintf(`%+v`, err)) } // Response content logging. - var resBodyContent string - resBodyContent = r.Response.BufferString() - resBodyContent = gstr.StrLimit( - r.Response.BufferString(), - gtrace.MaxContentLogSize(), - "...", - ) + var resBodyContent = gstr.StrLimit(r.Response.BufferString(), gtrace.MaxContentLogSize(), "...") span.AddEvent(tracingEventHttpResponse, trace.WithAttributes( attribute.String(tracingEventHttpResponseHeaders, gconv.String(httputil.HeaderToMap(r.Response.Header()))), diff --git a/net/ghttp/ghttp_request.go b/net/ghttp/ghttp_request.go index 302d05f5d..cb4a9d085 100644 --- a/net/ghttp/ghttp_request.go +++ b/net/ghttp/ghttp_request.go @@ -16,11 +16,10 @@ import ( "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/os/gres" "github.com/gogf/gf/v2/os/gsession" - "github.com/gogf/gf/v2/os/gview" - "github.com/gogf/gf/v2/util/guid" - "github.com/gogf/gf/v2/os/gtime" + "github.com/gogf/gf/v2/os/gview" "github.com/gogf/gf/v2/text/gregex" + "github.com/gogf/gf/v2/util/guid" ) // Request is the context object for a request. diff --git a/net/ghttp/ghttp_request_middleware.go b/net/ghttp/ghttp_request_middleware.go index 23bf8fc9a..3572d8d40 100644 --- a/net/ghttp/ghttp_request_middleware.go +++ b/net/ghttp/ghttp_request_middleware.go @@ -7,11 +7,11 @@ package ghttp import ( - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" "net/http" "reflect" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/util/gutil" ) diff --git a/net/ghttp/ghttp_request_param.go b/net/ghttp/ghttp_request_param.go index c8ba8cbea..819bcbabe 100644 --- a/net/ghttp/ghttp_request_param.go +++ b/net/ghttp/ghttp_request_param.go @@ -9,6 +9,11 @@ package ghttp import ( "bytes" "fmt" + "io/ioutil" + "mime/multipart" + "reflect" + "strings" + "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/encoding/gjson" "github.com/gogf/gf/v2/encoding/gurl" @@ -21,10 +26,6 @@ import ( "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/gvalid" - "io/ioutil" - "mime/multipart" - "reflect" - "strings" ) const ( diff --git a/net/ghttp/ghttp_request_param_ctx.go b/net/ghttp/ghttp_request_param_ctx.go index e208e64b3..7c4760b56 100644 --- a/net/ghttp/ghttp_request_param_ctx.go +++ b/net/ghttp/ghttp_request_param_ctx.go @@ -8,6 +8,7 @@ package ghttp import ( "context" + "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/os/gctx" ) diff --git a/net/ghttp/ghttp_request_param_file.go b/net/ghttp/ghttp_request_param_file.go index 9c78b9551..9918c5c68 100644 --- a/net/ghttp/ghttp_request_param_file.go +++ b/net/ghttp/ghttp_request_param_file.go @@ -8,16 +8,17 @@ package ghttp import ( "context" + "io" + "mime/multipart" + "strconv" + "strings" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/util/grand" - "io" - "mime/multipart" - "strconv" - "strings" ) // UploadFile wraps the multipart uploading file with more and convenient features. diff --git a/net/ghttp/ghttp_request_param_page.go b/net/ghttp/ghttp_request_param_page.go index 49c4f6461..8feda30eb 100644 --- a/net/ghttp/ghttp_request_param_page.go +++ b/net/ghttp/ghttp_request_param_page.go @@ -8,6 +8,7 @@ package ghttp import ( "fmt" + "github.com/gogf/gf/v2/text/gregex" "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gpage" diff --git a/net/ghttp/ghttp_request_param_query.go b/net/ghttp/ghttp_request_param_query.go index dc943f1f8..70ed03f1d 100644 --- a/net/ghttp/ghttp_request_param_query.go +++ b/net/ghttp/ghttp_request_param_query.go @@ -8,7 +8,6 @@ package ghttp import ( "github.com/gogf/gf/v2/container/gvar" - "github.com/gogf/gf/v2/util/gconv" ) diff --git a/net/ghttp/ghttp_response.go b/net/ghttp/ghttp_response.go index 52975343d..533a40472 100644 --- a/net/ghttp/ghttp_response.go +++ b/net/ghttp/ghttp_response.go @@ -12,9 +12,8 @@ import ( "fmt" "net/http" - "github.com/gogf/gf/v2/os/gres" - "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/os/gres" ) // Response is the http response manager. @@ -63,9 +62,10 @@ func (r *Response) ServeFile(path string, allowIndex ...bool) { // ServeFileDownload serves file downloading to the response. func (r *Response) ServeFileDownload(path string, name ...string) { var ( - serveFile *staticFile + serveFile *staticFile + downloadName = "" ) - downloadName := "" + if len(name) > 0 { downloadName = name[0] } diff --git a/net/ghttp/ghttp_response_cors.go b/net/ghttp/ghttp_response_cors.go index e74eb761c..f7dbfe107 100644 --- a/net/ghttp/ghttp_response_cors.go +++ b/net/ghttp/ghttp_response_cors.go @@ -8,10 +8,11 @@ package ghttp import ( - "github.com/gogf/gf/v2/text/gstr" - "github.com/gogf/gf/v2/util/gconv" "net/http" "net/url" + + "github.com/gogf/gf/v2/text/gstr" + "github.com/gogf/gf/v2/util/gconv" ) // CORSOptions is the options for CORS feature. @@ -105,7 +106,7 @@ func (r *Response) CORS(options CORSOptions) { } } -// CORSAllowed checks whether the current request origin is allowed cross-domain. +// CORSAllowedOrigin CORSAllowed checks whether the current request origin is allowed cross-domain. func (r *Response) CORSAllowedOrigin(options CORSOptions) bool { if options.AllowDomain == nil { return true diff --git a/net/ghttp/ghttp_response_view.go b/net/ghttp/ghttp_response_view.go index 4d0aa4ac2..bfc8c6287 100644 --- a/net/ghttp/ghttp_response_view.go +++ b/net/ghttp/ghttp_response_view.go @@ -18,42 +18,42 @@ import ( // WriteTpl parses and responses given template file. // The parameter `params` specifies the template variables for parsing. func (r *Response) WriteTpl(tpl string, params ...gview.Params) error { - if b, err := r.ParseTpl(tpl, params...); err != nil { + b, err := r.ParseTpl(tpl, params...) + if err != nil { if !gmode.IsProduct() { r.Write("Template Parsing Error: " + err.Error()) } return err - } else { - r.Write(b) } + r.Write(b) return nil } // WriteTplDefault parses and responses the default template file. // The parameter `params` specifies the template variables for parsing. func (r *Response) WriteTplDefault(params ...gview.Params) error { - if b, err := r.ParseTplDefault(params...); err != nil { + b, err := r.ParseTplDefault(params...) + if err != nil { if !gmode.IsProduct() { r.Write("Template Parsing Error: " + err.Error()) } return err - } else { - r.Write(b) } + r.Write(b) return nil } // WriteTplContent parses and responses the template content. // The parameter `params` specifies the template variables for parsing. func (r *Response) WriteTplContent(content string, params ...gview.Params) error { - if b, err := r.ParseTplContent(content, params...); err != nil { + b, err := r.ParseTplContent(content, params...) + if err != nil { if !gmode.IsProduct() { r.Write("Template Parsing Error: " + err.Error()) } return err - } else { - r.Write(b) } + r.Write(b) return nil } diff --git a/net/ghttp/ghttp_response_write.go b/net/ghttp/ghttp_response_write.go index e8fb37b9d..038628b98 100644 --- a/net/ghttp/ghttp_response_write.go +++ b/net/ghttp/ghttp_response_write.go @@ -9,10 +9,11 @@ package ghttp import ( "fmt" + "net/http" + "github.com/gogf/gf/v2/encoding/gjson" "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/util/gconv" - "net/http" ) // Write writes `content` to the response buffer. @@ -130,7 +131,7 @@ func (r *Response) WriteJsonExit(content interface{}) error { return nil } -// WriteJson writes `content` to the response with JSONP format. +// WriteJsonP writes `content` to the response with JSONP format. // // Note that there should be a "callback" parameter in the request for JSONP format. func (r *Response) WriteJsonP(content interface{}) error { @@ -145,7 +146,7 @@ func (r *Response) WriteJsonP(content interface{}) error { if b, err := json.Marshal(content); err != nil { return err } else { - //r.Header().Set("Content-Type", "application/json") + // r.Header().Set("Content-Type", "application/json") if callback := r.Request.Get("callback").String(); callback != "" { buffer := []byte(callback) buffer = append(buffer, byte('(')) diff --git a/net/ghttp/ghttp_response_writer.go b/net/ghttp/ghttp_response_writer.go index 7d87981ff..5a8781a02 100644 --- a/net/ghttp/ghttp_response_writer.go +++ b/net/ghttp/ghttp_response_writer.go @@ -50,7 +50,7 @@ func (w *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { return w.writer.(http.Hijacker).Hijack() } -// OutputBuffer outputs the buffer to client and clears the buffer. +// Flush outputs the buffer to client and clears the buffer. func (w *ResponseWriter) Flush() { if w.hijacked { return diff --git a/net/ghttp/ghttp_server.go b/net/ghttp/ghttp_server.go index e2d860a9e..7738d9a85 100644 --- a/net/ghttp/ghttp_server.go +++ b/net/ghttp/ghttp_server.go @@ -10,32 +10,32 @@ import ( "bytes" "context" "fmt" - "github.com/gogf/gf/v2/debug/gdebug" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/internal/intlog" - "github.com/gogf/gf/v2/net/ghttp/internal/swaggerui" - "github.com/gogf/gf/v2/protocol/goai" - "github.com/gogf/gf/v2/text/gstr" "net/http" "os" "runtime" "strings" "time" - "github.com/gogf/gf/v2/os/gsession" + "github.com/olekukonko/tablewriter" "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/container/gtype" + "github.com/gogf/gf/v2/debug/gdebug" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/intlog" + "github.com/gogf/gf/v2/net/ghttp/internal/swaggerui" "github.com/gogf/gf/v2/os/gcache" "github.com/gogf/gf/v2/os/genv" "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/glog" "github.com/gogf/gf/v2/os/gproc" + "github.com/gogf/gf/v2/os/gsession" "github.com/gogf/gf/v2/os/gtimer" + "github.com/gogf/gf/v2/protocol/goai" "github.com/gogf/gf/v2/text/gregex" + "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" - "github.com/olekukonko/tablewriter" ) func init() { diff --git a/net/ghttp/ghttp_server_admin.go b/net/ghttp/ghttp_server_admin.go index f8e00350d..e84d8d886 100644 --- a/net/ghttp/ghttp_server_admin.go +++ b/net/ghttp/ghttp_server_admin.go @@ -8,10 +8,10 @@ package ghttp import ( "context" - "github.com/gogf/gf/v2/os/gfile" "strings" "time" + "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/gproc" "github.com/gogf/gf/v2/os/gtimer" "github.com/gogf/gf/v2/os/gview" diff --git a/net/ghttp/ghttp_server_admin_process.go b/net/ghttp/ghttp_server_admin_process.go index 02702d56e..240aca38b 100644 --- a/net/ghttp/ghttp_server_admin_process.go +++ b/net/ghttp/ghttp_server_admin_process.go @@ -10,10 +10,6 @@ import ( "bytes" "context" "fmt" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/internal/intlog" - "github.com/gogf/gf/v2/text/gstr" "os" "runtime" "strings" @@ -22,10 +18,14 @@ import ( "github.com/gogf/gf/v2/container/gtype" "github.com/gogf/gf/v2/encoding/gjson" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/os/glog" "github.com/gogf/gf/v2/os/gproc" "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/os/gtimer" + "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" ) diff --git a/net/ghttp/ghttp_server_admin_unix.go b/net/ghttp/ghttp_server_admin_unix.go index 43063d2b9..771e063d9 100644 --- a/net/ghttp/ghttp_server_admin_unix.go +++ b/net/ghttp/ghttp_server_admin_unix.go @@ -4,16 +4,18 @@ // If a copy of the MIT was not distributed with this file, // You can obtain one at https://github.com/gogf/gf. +//go:build !windows // +build !windows package ghttp import ( "context" - "github.com/gogf/gf/v2/internal/intlog" "os" "os/signal" "syscall" + + "github.com/gogf/gf/v2/internal/intlog" ) // procSignalChan is the channel for listening the signal. diff --git a/net/ghttp/ghttp_server_config.go b/net/ghttp/ghttp_server_config.go index 7fa9f01de..7d3944718 100644 --- a/net/ghttp/ghttp_server_config.go +++ b/net/ghttp/ghttp_server_config.go @@ -9,21 +9,18 @@ package ghttp import ( "context" "crypto/tls" - "github.com/gogf/gf/v2/internal/intlog" - "github.com/gogf/gf/v2/os/gres" - "github.com/gogf/gf/v2/util/gutil" "net/http" "strconv" "time" - "github.com/gogf/gf/v2/util/gconv" - - "github.com/gogf/gf/v2/os/gsession" - - "github.com/gogf/gf/v2/os/gview" - + "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/glog" + "github.com/gogf/gf/v2/os/gres" + "github.com/gogf/gf/v2/os/gsession" + "github.com/gogf/gf/v2/os/gview" + "github.com/gogf/gf/v2/util/gconv" + "github.com/gogf/gf/v2/util/gutil" ) const ( diff --git a/net/ghttp/ghttp_server_cookie.go b/net/ghttp/ghttp_server_cookie.go index 764421396..8275593d9 100644 --- a/net/ghttp/ghttp_server_cookie.go +++ b/net/ghttp/ghttp_server_cookie.go @@ -7,9 +7,10 @@ package ghttp import ( - "github.com/gogf/gf/v2/container/gvar" "net/http" "time" + + "github.com/gogf/gf/v2/container/gvar" ) // Cookie for HTTP COOKIE management. @@ -47,9 +48,9 @@ func (c *Cookie) init() { c.data = make(map[string]*cookieItem) c.response = c.request.Response // DO NOT ADD ANY DEFAULT COOKIE DOMAIN! - //if c.request.Server.GetCookieDomain() == "" { + // if c.request.Server.GetCookieDomain() == "" { // c.request.Server.GetCookieDomain() = c.request.GetHost() - //} + // } for _, v := range c.request.Cookies() { c.data[v.Name] = &cookieItem{ Cookie: v, diff --git a/net/ghttp/ghttp_server_domain.go b/net/ghttp/ghttp_server_domain.go index e160c0687..74a77c4a1 100644 --- a/net/ghttp/ghttp_server_domain.go +++ b/net/ghttp/ghttp_server_domain.go @@ -35,9 +35,15 @@ func (d *Domain) BindHandler(pattern string, handler interface{}) { } } -func (d *Domain) doBindHandler(ctx context.Context, pattern string, funcInfo handlerFuncInfo, middleware []HandlerFunc, source string) { +func (d *Domain) doBindHandler(ctx context.Context, in doBindHandlerInput) { for domain, _ := range d.domains { - d.server.doBindHandler(ctx, pattern+"@"+domain, funcInfo, middleware, source) + d.server.doBindHandler(ctx, doBindHandlerInput{ + Prefix: in.Prefix, + Pattern: in.Pattern + "@" + domain, + FuncInfo: in.FuncInfo, + Middleware: in.Middleware, + Source: in.Source, + }) } } @@ -47,9 +53,16 @@ func (d *Domain) BindObject(pattern string, obj interface{}, methods ...string) } } -func (d *Domain) doBindObject(ctx context.Context, pattern string, obj interface{}, methods string, middleware []HandlerFunc, source string) { +func (d *Domain) doBindObject(ctx context.Context, in doBindObjectInput) { for domain, _ := range d.domains { - d.server.doBindObject(ctx, pattern+"@"+domain, obj, methods, middleware, source) + d.server.doBindObject(ctx, doBindObjectInput{ + Prefix: in.Prefix, + Pattern: in.Pattern + "@" + domain, + Object: in.Object, + Method: in.Method, + Middleware: in.Middleware, + Source: in.Source, + }) } } @@ -59,13 +72,16 @@ func (d *Domain) BindObjectMethod(pattern string, obj interface{}, method string } } -func (d *Domain) doBindObjectMethod( - ctx context.Context, - pattern string, obj interface{}, method string, - middleware []HandlerFunc, source string, -) { +func (d *Domain) doBindObjectMethod(ctx context.Context, in doBindObjectMethodInput) { for domain, _ := range d.domains { - d.server.doBindObjectMethod(ctx, pattern+"@"+domain, obj, method, middleware, source) + d.server.doBindObjectMethod(ctx, doBindObjectMethodInput{ + Prefix: in.Prefix, + Pattern: in.Pattern + "@" + domain, + Object: in.Object, + Method: in.Method, + Middleware: in.Middleware, + Source: in.Source, + }) } } @@ -75,9 +91,16 @@ func (d *Domain) BindObjectRest(pattern string, obj interface{}) { } } -func (d *Domain) doBindObjectRest(ctx context.Context, pattern string, obj interface{}, middleware []HandlerFunc, source string) { +func (d *Domain) doBindObjectRest(ctx context.Context, in doBindObjectInput) { for domain, _ := range d.domains { - d.server.doBindObjectRest(ctx, pattern+"@"+domain, obj, middleware, source) + d.server.doBindObjectRest(ctx, doBindObjectInput{ + Prefix: in.Prefix, + Pattern: in.Pattern + "@" + domain, + Object: in.Object, + Method: in.Method, + Middleware: in.Middleware, + Source: in.Source, + }) } } @@ -87,9 +110,15 @@ func (d *Domain) BindHookHandler(pattern string, hook string, handler HandlerFun } } -func (d *Domain) doBindHookHandler(ctx context.Context, pattern string, hook string, handler HandlerFunc, source string) { +func (d *Domain) doBindHookHandler(ctx context.Context, in doBindHookHandlerInput) { for domain, _ := range d.domains { - d.server.doBindHookHandler(ctx, pattern+"@"+domain, hook, handler, source) + d.server.doBindHookHandler(ctx, doBindHookHandlerInput{ + Prefix: in.Prefix, + Pattern: in.Pattern + "@" + domain, + HookName: in.HookName, + Handler: in.Handler, + Source: in.Source, + }) } } diff --git a/net/ghttp/ghttp_server_error_logger.go b/net/ghttp/ghttp_server_error_logger.go index 5d2ca380d..7bc89a079 100644 --- a/net/ghttp/ghttp_server_error_logger.go +++ b/net/ghttp/ghttp_server_error_logger.go @@ -9,6 +9,7 @@ package ghttp import ( "bytes" "context" + "github.com/gogf/gf/v2/os/glog" ) diff --git a/net/ghttp/ghttp_server_graceful.go b/net/ghttp/ghttp_server_graceful.go index 66aed18b3..898043933 100644 --- a/net/ghttp/ghttp_server_graceful.go +++ b/net/ghttp/ghttp_server_graceful.go @@ -9,15 +9,16 @@ package ghttp import ( "context" "crypto/tls" + "log" + "net" + "net/http" + "os" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/os/gproc" "github.com/gogf/gf/v2/os/gres" "github.com/gogf/gf/v2/text/gstr" - "log" - "net" - "net/http" - "os" ) // gracefulServer wraps the net/http.Server with graceful reload/restart feature. diff --git a/net/ghttp/ghttp_server_handler.go b/net/ghttp/ghttp_server_handler.go index c52286631..b8e8e2359 100644 --- a/net/ghttp/ghttp_server_handler.go +++ b/net/ghttp/ghttp_server_handler.go @@ -7,23 +7,20 @@ package ghttp import ( - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/internal/intlog" "net/http" "os" "sort" "strings" - "github.com/gogf/gf/v2/text/gstr" - - "github.com/gogf/gf/v2/errors/gerror" - - "github.com/gogf/gf/v2/os/gres" - "github.com/gogf/gf/v2/encoding/ghtml" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/os/gres" "github.com/gogf/gf/v2/os/gspath" "github.com/gogf/gf/v2/os/gtime" + "github.com/gogf/gf/v2/text/gstr" ) // ServeHTTP is the default handler for http request. diff --git a/net/ghttp/ghttp_server_log.go b/net/ghttp/ghttp_server_log.go index 6c5ad5ae7..80b29cd78 100644 --- a/net/ghttp/ghttp_server_log.go +++ b/net/ghttp/ghttp_server_log.go @@ -8,6 +8,7 @@ package ghttp import ( "fmt" + "github.com/gogf/gf/v2/errors/gerror" ) diff --git a/net/ghttp/ghttp_server_openapi.go b/net/ghttp/ghttp_server_openapi.go index 85076e8c9..c03175174 100644 --- a/net/ghttp/ghttp_server_openapi.go +++ b/net/ghttp/ghttp_server_openapi.go @@ -8,6 +8,7 @@ package ghttp import ( "context" + "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/protocol/goai" "github.com/gogf/gf/v2/text/gstr" diff --git a/net/ghttp/ghttp_server_pprof.go b/net/ghttp/ghttp_server_pprof.go index e466bda67..e3dd34369 100644 --- a/net/ghttp/ghttp_server_pprof.go +++ b/net/ghttp/ghttp_server_pprof.go @@ -7,11 +7,11 @@ package ghttp import ( - "github.com/gogf/gf/v2/internal/intlog" netpprof "net/http/pprof" runpprof "runtime/pprof" "strings" + "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/os/gview" ) diff --git a/net/ghttp/ghttp_server_router.go b/net/ghttp/ghttp_server_router.go index ac6b361ca..ecdcc5304 100644 --- a/net/ghttp/ghttp_server_router.go +++ b/net/ghttp/ghttp_server_router.go @@ -9,16 +9,18 @@ package ghttp import ( "context" "fmt" - "github.com/gogf/gf/v2/container/gtype" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" + "reflect" "strings" - "github.com/gogf/gf/v2/debug/gdebug" - "github.com/gogf/gf/v2/container/glist" + "github.com/gogf/gf/v2/container/gtype" + "github.com/gogf/gf/v2/debug/gdebug" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/protocol/goai" "github.com/gogf/gf/v2/text/gregex" "github.com/gogf/gf/v2/text/gstr" + "github.com/gogf/gf/v2/util/gmeta" ) const ( @@ -63,11 +65,22 @@ func (s *Server) parsePattern(pattern string) (domain, method, path string, err return } +type setHandlerInput struct { + Prefix string + Pattern string + HandlerItem *handlerItem +} + // setHandler creates router item with given handler and pattern and registers the handler to the router tree. // The router tree can be treated as a multilayer hash table, please refer to the comment in following codes. // This function is called during server starts up, which cares little about the performance. What really cares // is the well-designed router storage structure for router searching when the request is under serving. -func (s *Server) setHandler(ctx context.Context, pattern string, handler *handlerItem) { +func (s *Server) setHandler(ctx context.Context, in setHandlerInput) { + var ( + prefix = in.Prefix + pattern = in.Pattern + handler = in.HandlerItem + ) handler.Id = handlerIdGenerator.Add(1) if handler.Source == "" { _, file, line := gdebug.CallerWithFilter(stackFilterKey) @@ -78,6 +91,28 @@ func (s *Server) setHandler(ctx context.Context, pattern string, handler *handle s.Logger().Fatalf(ctx, `invalid pattern "%s", %+v`, pattern, err) return } + + // Change the registered route according meta info from its request structure. + if handler.Info.Type != nil && handler.Info.Type.NumIn() == 2 { + var ( + objectReq = reflect.New(handler.Info.Type.In(1)) + ) + if v := gmeta.Get(objectReq, goai.TagNamePath); !v.IsEmpty() { + uri = v.String() + } + if v := gmeta.Get(objectReq, goai.TagNameMethod); !v.IsEmpty() { + method = v.String() + } + if v := gmeta.Get(objectReq, goai.TagNameDomain); !v.IsEmpty() { + domain = v.String() + } + } + + // Prefix for URI feature. + if prefix != "" { + uri = prefix + "/" + strings.TrimLeft(uri, "/") + } + if len(uri) == 0 || uri[0] != '/' { s.Logger().Fatalf(ctx, `invalid pattern "%s", URI should lead with '/'`, pattern) return @@ -177,7 +212,7 @@ func (s *Server) setHandler(ctx context.Context, pattern string, handler *handle for e := l.Front(); e != nil; e = e.Next() { item = e.Value.(*handlerItem) // Checks the priority whether inserting the route item before current item, - // which means it has more higher priority. + // which means it has higher priority. if s.compareRouterPriority(handler, item) { l.InsertBefore(e, handler) pushed = true @@ -211,11 +246,11 @@ func (s *Server) setHandler(ctx context.Context, pattern string, handler *handle // compareRouterPriority compares the priority between `newItem` and `oldItem`. It returns true // if `newItem`'s priority is higher than `oldItem`, else it returns false. The higher priority -// item will be insert into the router list before the other one. +// item will be inserted into the router list before the other one. // // Comparison rules: // 1. The middleware has the most high priority. -// 2. URI: The deeper the higher (simply check the count of char '/' in the URI). +// 2. URI: The deeper, the higher (simply check the count of char '/' in the URI). // 3. Route type: {xxx} > :xxx > *xxx. func (s *Server) compareRouterPriority(newItem *handlerItem, oldItem *handlerItem) bool { // If they're all type of middleware, the priority is according their registered sequence. @@ -226,7 +261,7 @@ func (s *Server) compareRouterPriority(newItem *handlerItem, oldItem *handlerIte if newItem.Type == HandlerTypeMiddleware && oldItem.Type != HandlerTypeMiddleware { return true } - // URI: The deeper the higher (simply check the count of char '/' in the URI). + // URI: The deeper, the higher (simply check the count of char '/' in the URI). if newItem.Router.Priority > oldItem.Router.Priority { return true } diff --git a/net/ghttp/ghttp_server_router_group.go b/net/ghttp/ghttp_server_router_group.go index 4f88fde2f..f08283b55 100644 --- a/net/ghttp/ghttp_server_router_group.go +++ b/net/ghttp/ghttp_server_router_group.go @@ -9,12 +9,11 @@ package ghttp import ( "context" "fmt" - "github.com/gogf/gf/v2/debug/gdebug" "reflect" - "strings" + "github.com/gogf/gf/v2/debug/gdebug" + "github.com/gogf/gf/v2/internal/utils" "github.com/gogf/gf/v2/text/gstr" - "github.com/gogf/gf/v2/util/gconv" ) @@ -28,9 +27,6 @@ type ( middleware []HandlerFunc // Middleware array. } - // GroupItem is item for router group. - GroupItem = []interface{} - // preBindItem is item for lazy registering feature of router group. preBindItem is not really registered // to server when route function of the group called but is lazily registered when server starts. preBindItem struct { @@ -104,16 +100,17 @@ func (d *Domain) Group(prefix string, groups ...func(group *RouterGroup)) *Route if prefix == "/" { prefix = "" } - group := &RouterGroup{ + routerGroup := &RouterGroup{ domain: d, + server: d.server, prefix: prefix, } if len(groups) > 0 { - for _, v := range groups { - v(group) + for _, nestedGroup := range groups { + nestedGroup(routerGroup) } } - return group + return routerGroup } // Group creates and returns a sub-group of current router group. @@ -153,34 +150,26 @@ func (g *RouterGroup) Clone() *RouterGroup { } // Bind does batch route registering feature for router group. -func (g *RouterGroup) Bind(items []GroupItem) *RouterGroup { +func (g *RouterGroup) Bind(handlerOrObject ...interface{}) *RouterGroup { var ( ctx = context.TODO() group = g.Clone() ) - for _, item := range items { - if len(item) < 3 { - g.server.Logger().Fatalf(ctx, "invalid router item: %s", item) - } - bindType := gstr.ToUpper(gconv.String(item[0])) - switch bindType { - case groupBindTypeRest: - group.preBindToLocalArray(groupBindTypeRest, gconv.String(item[0])+":"+gconv.String(item[1]), item[2]) - - case groupBindTypeMiddleware: - group.preBindToLocalArray(groupBindTypeMiddleware, gconv.String(item[0])+":"+gconv.String(item[1]), item[2]) + for _, v := range handlerOrObject { + var ( + item = v + originValueAndKind = utils.OriginValueAndKind(item) + ) + switch originValueAndKind.OriginKind { + case reflect.Func, reflect.Struct: + group = group.preBindToLocalArray( + groupBindTypeHandler, + "/", + item, + ) default: - if strings.EqualFold(bindType, "ALL") { - bindType = "" - } else { - bindType += ":" - } - if len(item) > 3 { - group.preBindToLocalArray(groupBindTypeHandler, bindType+gconv.String(item[1]), item[2], item[3]) - } else { - group.preBindToLocalArray(groupBindTypeHandler, bindType+gconv.String(item[1]), item[2]) - } + g.server.Logger().Fatalf(ctx, "invalid bind parameter type: %v", originValueAndKind.InputValue.Type()) } } return group @@ -188,7 +177,12 @@ func (g *RouterGroup) Bind(items []GroupItem) *RouterGroup { // ALL registers a http handler to given route pattern and all http methods. func (g *RouterGroup) ALL(pattern string, object interface{}, params ...interface{}) *RouterGroup { - return g.Clone().preBindToLocalArray(groupBindTypeHandler, defaultMethod+":"+pattern, object, params...) + return g.Clone().preBindToLocalArray( + groupBindTypeHandler, + defaultMethod+":"+pattern, + object, + params..., + ) } // ALLMap registers http handlers for http methods using map. @@ -312,10 +306,10 @@ func (g *RouterGroup) doBindRoutersToServer(ctx context.Context, item *preBindIt domain = "" } if bindType == groupBindTypeRest { - pattern = prefix + "/" + strings.TrimLeft(path, "/") + pattern = path } else { pattern = g.server.serveHandlerKey( - method, prefix+"/"+strings.TrimLeft(path, "/"), domain, + method, path, domain, ) } } @@ -337,57 +331,95 @@ func (g *RouterGroup) doBindRoutersToServer(ctx context.Context, item *preBindIt g.server.Logger().Fatal(ctx, err.Error()) return g } - if g.server != nil { - g.server.doBindHandler(ctx, pattern, funcInfo, g.middleware, source) + in := doBindHandlerInput{ + Prefix: prefix, + Pattern: pattern, + FuncInfo: funcInfo, + Middleware: g.middleware, + Source: source, + } + if g.domain != nil { + g.domain.doBindHandler(ctx, in) } else { - g.domain.doBindHandler(ctx, pattern, funcInfo, g.middleware, source) + g.server.doBindHandler(ctx, in) } } else { if len(extras) > 0 { - if g.server != nil { - if gstr.Contains(extras[0], ",") { - g.server.doBindObject( - ctx, pattern, object, extras[0], g.middleware, source, - ) + if gstr.Contains(extras[0], ",") { + in := doBindObjectInput{ + Prefix: prefix, + Pattern: pattern, + Object: object, + Method: extras[0], + Middleware: g.middleware, + Source: source, + } + if g.domain != nil { + g.domain.doBindObject(ctx, in) } else { - g.server.doBindObjectMethod( - ctx, pattern, object, extras[0], g.middleware, source, - ) + g.server.doBindObject(ctx, in) } } else { - if gstr.Contains(extras[0], ",") { - g.domain.doBindObject( - ctx, pattern, object, extras[0], g.middleware, source, - ) + in := doBindObjectMethodInput{ + Prefix: prefix, + Pattern: pattern, + Object: object, + Method: extras[0], + Middleware: g.middleware, + Source: source, + } + if g.domain != nil { + g.domain.doBindObjectMethod(ctx, in) } else { - g.domain.doBindObjectMethod( - ctx, pattern, object, extras[0], g.middleware, source, - ) + g.server.doBindObjectMethod(ctx, in) } } } else { + in := doBindObjectInput{ + Prefix: prefix, + Pattern: pattern, + Object: object, + Method: "", + Middleware: g.middleware, + Source: source, + } // At last, it treats the `object` as Object registering type. - if g.server != nil { - g.server.doBindObject(ctx, pattern, object, "", g.middleware, source) + if g.domain != nil { + g.domain.doBindObject(ctx, in) } else { - g.domain.doBindObject(ctx, pattern, object, "", g.middleware, source) + g.server.doBindObject(ctx, in) } } } case groupBindTypeRest: - if g.server != nil { - g.server.doBindObjectRest(ctx, pattern, object, g.middleware, source) + in := doBindObjectInput{ + Prefix: prefix, + Pattern: pattern, + Object: object, + Method: "", + Middleware: g.middleware, + Source: source, + } + if g.domain != nil { + g.domain.doBindObjectRest(ctx, in) } else { - g.domain.doBindObjectRest(ctx, pattern, object, g.middleware, source) + g.server.doBindObjectRest(ctx, in) } case groupBindTypeHook: - if h, ok := object.(HandlerFunc); ok { - if g.server != nil { - g.server.doBindHookHandler(ctx, pattern, extras[0], h, source) + if handler, ok := object.(HandlerFunc); ok { + in := doBindHookHandlerInput{ + Prefix: prefix, + Pattern: pattern, + HookName: extras[0], + Handler: handler, + Source: source, + } + if g.domain != nil { + g.domain.doBindHookHandler(ctx, in) } else { - g.domain.doBindHookHandler(ctx, pattern, extras[0], h, source) + g.server.doBindHookHandler(ctx, in) } } else { g.server.Logger().Fatalf(ctx, "invalid hook handler for pattern: %s", pattern) diff --git a/net/ghttp/ghttp_server_router_hook.go b/net/ghttp/ghttp_server_router_hook.go index 2138af086..467319a53 100644 --- a/net/ghttp/ghttp_server_router_hook.go +++ b/net/ghttp/ghttp_server_router_hook.go @@ -8,27 +8,49 @@ package ghttp import ( "context" - "github.com/gogf/gf/v2/debug/gdebug" "net/http" "reflect" + + "github.com/gogf/gf/v2/debug/gdebug" ) // BindHookHandler registers handler for specified hook. func (s *Server) BindHookHandler(pattern string, hook string, handler HandlerFunc) { - s.doBindHookHandler(context.TODO(), pattern, hook, handler, "") + s.doBindHookHandler(context.TODO(), doBindHookHandlerInput{ + Prefix: "", + Pattern: pattern, + HookName: hook, + Handler: handler, + Source: "", + }) } -func (s *Server) doBindHookHandler(ctx context.Context, pattern string, hook string, handler HandlerFunc, source string) { - s.setHandler(ctx, pattern, &handlerItem{ - Type: HandlerTypeHook, - Name: gdebug.FuncPath(handler), - Info: handlerFuncInfo{ - Func: handler, - Type: reflect.TypeOf(handler), +type doBindHookHandlerInput struct { + Prefix string + Pattern string + HookName string + Handler HandlerFunc + Source string +} + +func (s *Server) doBindHookHandler(ctx context.Context, in doBindHookHandlerInput) { + s.setHandler( + ctx, + setHandlerInput{ + Prefix: in.Prefix, + Pattern: in.Pattern, + HandlerItem: &handlerItem{ + Type: HandlerTypeHook, + Name: gdebug.FuncPath(in.Handler), + Info: handlerFuncInfo{ + Func: in.Handler, + Type: reflect.TypeOf(in.Handler), + }, + HookName: in.HookName, + Source: in.Source, + }, }, - HookName: hook, - Source: source, - }) + ) } func (s *Server) BindHookHandlerByMap(pattern string, hookMap map[string]HandlerFunc) { diff --git a/net/ghttp/ghttp_server_router_middleware.go b/net/ghttp/ghttp_server_router_middleware.go index 2e4c99f0b..74a3d483a 100644 --- a/net/ghttp/ghttp_server_router_middleware.go +++ b/net/ghttp/ghttp_server_router_middleware.go @@ -8,8 +8,9 @@ package ghttp import ( "context" - "github.com/gogf/gf/v2/debug/gdebug" "reflect" + + "github.com/gogf/gf/v2/debug/gdebug" ) const ( @@ -26,12 +27,16 @@ func (s *Server) BindMiddleware(pattern string, handlers ...HandlerFunc) { ctx = context.TODO() ) for _, handler := range handlers { - s.setHandler(ctx, pattern, &handlerItem{ - Type: HandlerTypeMiddleware, - Name: gdebug.FuncPath(handler), - Info: handlerFuncInfo{ - Func: handler, - Type: reflect.TypeOf(handler), + s.setHandler(ctx, setHandlerInput{ + Prefix: "", + Pattern: pattern, + HandlerItem: &handlerItem{ + Type: HandlerTypeMiddleware, + Name: gdebug.FuncPath(handler), + Info: handlerFuncInfo{ + Func: handler, + Type: reflect.TypeOf(handler), + }, }, }) } @@ -45,12 +50,16 @@ func (s *Server) BindMiddlewareDefault(handlers ...HandlerFunc) { ctx = context.TODO() ) for _, handler := range handlers { - s.setHandler(ctx, defaultMiddlewarePattern, &handlerItem{ - Type: HandlerTypeMiddleware, - Name: gdebug.FuncPath(handler), - Info: handlerFuncInfo{ - Func: handler, - Type: reflect.TypeOf(handler), + s.setHandler(ctx, setHandlerInput{ + Prefix: "", + Pattern: defaultMiddlewarePattern, + HandlerItem: &handlerItem{ + Type: HandlerTypeMiddleware, + Name: gdebug.FuncPath(handler), + Info: handlerFuncInfo{ + Func: handler, + Type: reflect.TypeOf(handler), + }, }, }) } diff --git a/net/ghttp/ghttp_server_router_serve.go b/net/ghttp/ghttp_server_router_serve.go index baa5302ca..5083c2fb4 100644 --- a/net/ghttp/ghttp_server_router_serve.go +++ b/net/ghttp/ghttp_server_router_serve.go @@ -8,13 +8,13 @@ package ghttp import ( "fmt" + "strings" + + "github.com/gogf/gf/v2/container/glist" "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/internal/json" - "strings" - - "github.com/gogf/gf/v2/container/glist" "github.com/gogf/gf/v2/text/gregex" ) diff --git a/net/ghttp/ghttp_server_service_handler.go b/net/ghttp/ghttp_server_service_handler.go index 0c87469e9..57b675396 100644 --- a/net/ghttp/ghttp_server_service_handler.go +++ b/net/ghttp/ghttp_server_service_handler.go @@ -9,19 +9,20 @@ package ghttp import ( "bytes" "context" - "github.com/gogf/gf/v2/debug/gdebug" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" "reflect" "strings" + "github.com/gogf/gf/v2/debug/gdebug" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/text/gstr" ) // BindHandler registers a handler function to server with given pattern. -// The parameter `handler` can be type of: -// func(*ghttp.Request) -// func(context.Context, Request)(Response, error) +// +// Note that the parameter `handler` can be type of: +// 1. func(*ghttp.Request) +// 2. func(context.Context, BizRequest)(BizResponse, error) func (s *Server) BindHandler(pattern string, handler interface{}) { var ( ctx = context.TODO() @@ -30,26 +31,49 @@ func (s *Server) BindHandler(pattern string, handler interface{}) { if err != nil { s.Logger().Fatalf(ctx, `%+v`, err) } - s.doBindHandler(ctx, pattern, funcInfo, nil, "") + s.doBindHandler(ctx, doBindHandlerInput{ + Prefix: "", + Pattern: pattern, + FuncInfo: funcInfo, + Middleware: nil, + Source: "", + }) +} + +type doBindHandlerInput struct { + Prefix string + Pattern string + FuncInfo handlerFuncInfo + Middleware []HandlerFunc + Source string } // doBindHandler registers a handler function to server with given pattern. +// // The parameter `pattern` is like: // /user/list, put:/user, delete:/user, post:/user@goframe.org -func (s *Server) doBindHandler(ctx context.Context, pattern string, funcInfo handlerFuncInfo, middleware []HandlerFunc, source string) { - s.setHandler(ctx, pattern, &handlerItem{ - Name: gdebug.FuncPath(funcInfo.Func), - Type: HandlerTypeHandler, - Info: funcInfo, - Middleware: middleware, - Source: source, +func (s *Server) doBindHandler(ctx context.Context, in doBindHandlerInput) { + s.setHandler(ctx, setHandlerInput{ + Prefix: in.Prefix, + Pattern: in.Pattern, + HandlerItem: &handlerItem{ + Name: gdebug.FuncPath(in.FuncInfo.Func), + Type: HandlerTypeHandler, + Info: in.FuncInfo, + Middleware: in.Middleware, + Source: in.Source, + }, }) } // bindHandlerByMap registers handlers to server using map. -func (s *Server) bindHandlerByMap(ctx context.Context, m map[string]*handlerItem) { - for p, h := range m { - s.setHandler(ctx, p, h) +func (s *Server) bindHandlerByMap(ctx context.Context, prefix string, m map[string]*handlerItem) { + for pattern, handler := range m { + s.setHandler(ctx, setHandlerInput{ + Prefix: prefix, + Pattern: pattern, + HandlerItem: handler, + }) } } @@ -162,6 +186,7 @@ func (s *Server) checkAndCreateFuncInfo(f interface{}, pkgPath, structName, meth return } + // The request struct should be named as `xxxReq`. if !gstr.HasSuffix(reflectType.In(1).String(), `Req`) { err = gerror.NewCodef( gcode.CodeInvalidParameter, @@ -171,6 +196,7 @@ func (s *Server) checkAndCreateFuncInfo(f interface{}, pkgPath, structName, meth return } + // The response struct should be named as `xxxRes`. if !gstr.HasSuffix(reflectType.Out(0).String(), `Res`) { err = gerror.NewCodef( gcode.CodeInvalidParameter, diff --git a/net/ghttp/ghttp_server_service_object.go b/net/ghttp/ghttp_server_service_object.go index eea76edcd..13e141fab 100644 --- a/net/ghttp/ghttp_server_service_object.go +++ b/net/ghttp/ghttp_server_service_object.go @@ -21,8 +21,6 @@ import ( // // The optional parameter `method` is used to specify the method to be registered, which // supports multiple method names, multiple methods are separated by char ',', case-sensitive. -// -// Note that the route method should be defined as ghttp.HandlerFunc. func (s *Server) BindObject(pattern string, object interface{}, method ...string) { var ( bindMethod = "" @@ -30,97 +28,124 @@ func (s *Server) BindObject(pattern string, object interface{}, method ...string if len(method) > 0 { bindMethod = method[0] } - s.doBindObject(context.TODO(), pattern, object, bindMethod, nil, "") + s.doBindObject(context.TODO(), doBindObjectInput{ + Prefix: "", + Pattern: pattern, + Object: object, + Method: bindMethod, + Middleware: nil, + Source: "", + }) } // BindObjectMethod registers specified method of object to server routes with given pattern. // // The optional parameter `method` is used to specify the method to be registered, which // does not supports multiple method names but only one, case-sensitive. -// -// Note that the route method should be defined as ghttp.HandlerFunc. func (s *Server) BindObjectMethod(pattern string, object interface{}, method string) { - s.doBindObjectMethod(context.TODO(), pattern, object, method, nil, "") + s.doBindObjectMethod(context.TODO(), doBindObjectMethodInput{ + Prefix: "", + Pattern: pattern, + Object: object, + Method: method, + Middleware: nil, + Source: "", + }) } // BindObjectRest registers object in REST API styles to server with specified pattern. -// Note that the route method should be defined as ghttp.HandlerFunc. func (s *Server) BindObjectRest(pattern string, object interface{}) { - s.doBindObjectRest(context.TODO(), pattern, object, nil, "") + s.doBindObjectRest(context.TODO(), doBindObjectInput{ + Prefix: "", + Pattern: pattern, + Object: object, + Method: "", + Middleware: nil, + Source: "", + }) } -func (s *Server) doBindObject(ctx context.Context, pattern string, object interface{}, method string, middleware []HandlerFunc, source string) { +type doBindObjectInput struct { + Prefix string + Pattern string + Object interface{} + Method string + Middleware []HandlerFunc + Source string +} + +func (s *Server) doBindObject(ctx context.Context, in doBindObjectInput) { // Convert input method to map for convenience and high performance searching purpose. var ( methodMap map[string]bool ) - if len(method) > 0 { + if len(in.Method) > 0 { methodMap = make(map[string]bool) - for _, v := range strings.Split(method, ",") { + for _, v := range strings.Split(in.Method, ",") { methodMap[strings.TrimSpace(v)] = true } } // If the `method` in `pattern` is `defaultMethod`, // it removes for convenience for next statement control. - domain, method, path, err := s.parsePattern(pattern) + domain, method, path, err := s.parsePattern(in.Pattern) if err != nil { s.Logger().Fatalf(ctx, `%+v`, err) return } if strings.EqualFold(method, defaultMethod) { - pattern = s.serveHandlerKey("", path, domain) + in.Pattern = s.serveHandlerKey("", path, domain) } var ( - m = make(map[string]*handlerItem) - v = reflect.ValueOf(object) - t = v.Type() - initFunc func(*Request) - shutFunc func(*Request) + handlerMap = make(map[string]*handlerItem) + reflectValue = reflect.ValueOf(in.Object) + reflectType = reflectValue.Type() + initFunc func(*Request) + shutFunc func(*Request) ) // If given `object` is not pointer, it then creates a temporary one, // of which the value is `v`. - if v.Kind() == reflect.Struct { - newValue := reflect.New(t) - newValue.Elem().Set(v) - v = newValue - t = v.Type() + if reflectValue.Kind() == reflect.Struct { + newValue := reflect.New(reflectType) + newValue.Elem().Set(reflectValue) + reflectValue = newValue + reflectType = reflectValue.Type() } - structName := t.Elem().Name() - if v.MethodByName("Init").IsValid() { - initFunc = v.MethodByName("Init").Interface().(func(*Request)) + structName := reflectType.Elem().Name() + if reflectValue.MethodByName("Init").IsValid() { + initFunc = reflectValue.MethodByName("Init").Interface().(func(*Request)) } - if v.MethodByName("Shut").IsValid() { - shutFunc = v.MethodByName("Shut").Interface().(func(*Request)) + if reflectValue.MethodByName("Shut").IsValid() { + shutFunc = reflectValue.MethodByName("Shut").Interface().(func(*Request)) } - pkgPath := t.Elem().PkgPath() + pkgPath := reflectType.Elem().PkgPath() pkgName := gfile.Basename(pkgPath) - for i := 0; i < v.NumMethod(); i++ { - methodName := t.Method(i).Name + for i := 0; i < reflectValue.NumMethod(); i++ { + methodName := reflectType.Method(i).Name if methodMap != nil && !methodMap[methodName] { continue } if methodName == "Init" || methodName == "Shut" { continue } - objName := gstr.Replace(t.String(), fmt.Sprintf(`%s.`, pkgName), "") + objName := gstr.Replace(reflectType.String(), fmt.Sprintf(`%s.`, pkgName), "") if objName[0] == '*' { objName = fmt.Sprintf(`(%s)`, objName) } - funcInfo, err := s.checkAndCreateFuncInfo(v.Method(i).Interface(), pkgPath, objName, methodName) + funcInfo, err := s.checkAndCreateFuncInfo(reflectValue.Method(i).Interface(), pkgPath, objName, methodName) if err != nil { s.Logger().Fatalf(ctx, `%+v`, err) } - key := s.mergeBuildInNameToPattern(pattern, structName, methodName, true) - m[key] = &handlerItem{ + key := s.mergeBuildInNameToPattern(in.Pattern, structName, methodName, true) + handlerMap[key] = &handlerItem{ Name: fmt.Sprintf(`%s.%s.%s`, pkgPath, objName, methodName), Type: HandlerTypeObject, Info: funcInfo, InitFunc: initFunc, ShutFunc: shutFunc, - Middleware: middleware, - Source: source, + Middleware: in.Middleware, + Source: in.Source, } // If there's "Index" method, then an additional route is automatically added // to match the main URI, for example: @@ -129,61 +154,70 @@ func (s *Server) doBindObject(ctx context.Context, pattern string, object interf // // Note that if there's built-in variables in pattern, this route will not be added // automatically. - if strings.EqualFold(methodName, "Index") && !gregex.IsMatchString(`\{\.\w+\}`, pattern) { + if strings.EqualFold(methodName, "Index") && !gregex.IsMatchString(`\{\.\w+\}`, in.Pattern) { p := gstr.PosRI(key, "/index") k := key[0:p] + key[p+6:] if len(k) == 0 || k[0] == '@' { k = "/" + k } - m[k] = &handlerItem{ + handlerMap[k] = &handlerItem{ Name: fmt.Sprintf(`%s.%s.%s`, pkgPath, objName, methodName), Type: HandlerTypeObject, Info: funcInfo, InitFunc: initFunc, ShutFunc: shutFunc, - Middleware: middleware, - Source: source, + Middleware: in.Middleware, + Source: in.Source, } } } - s.bindHandlerByMap(ctx, m) + s.bindHandlerByMap(ctx, in.Prefix, handlerMap) } -func (s *Server) doBindObjectMethod(ctx context.Context, pattern string, object interface{}, method string, middleware []HandlerFunc, source string) { +type doBindObjectMethodInput struct { + Prefix string + Pattern string + Object interface{} + Method string + Middleware []HandlerFunc + Source string +} + +func (s *Server) doBindObjectMethod(ctx context.Context, in doBindObjectMethodInput) { var ( - m = make(map[string]*handlerItem) - v = reflect.ValueOf(object) - t = v.Type() - initFunc func(*Request) - shutFunc func(*Request) + handlerMap = make(map[string]*handlerItem) + reflectValue = reflect.ValueOf(in.Object) + reflectType = reflectValue.Type() + initFunc func(*Request) + shutFunc func(*Request) ) // If given `object` is not pointer, it then creates a temporary one, // of which the value is `v`. - if v.Kind() == reflect.Struct { - newValue := reflect.New(t) - newValue.Elem().Set(v) - v = newValue - t = v.Type() + if reflectValue.Kind() == reflect.Struct { + newValue := reflect.New(reflectType) + newValue.Elem().Set(reflectValue) + reflectValue = newValue + reflectType = reflectValue.Type() } var ( - structName = t.Elem().Name() - methodName = strings.TrimSpace(method) - methodValue = v.MethodByName(methodName) + structName = reflectType.Elem().Name() + methodName = strings.TrimSpace(in.Method) + methodValue = reflectValue.MethodByName(methodName) ) if !methodValue.IsValid() { s.Logger().Fatalf(ctx, "invalid method name: %s", methodName) return } - if v.MethodByName("Init").IsValid() { - initFunc = v.MethodByName("Init").Interface().(func(*Request)) + if reflectValue.MethodByName("Init").IsValid() { + initFunc = reflectValue.MethodByName("Init").Interface().(func(*Request)) } - if v.MethodByName("Shut").IsValid() { - shutFunc = v.MethodByName("Shut").Interface().(func(*Request)) + if reflectValue.MethodByName("Shut").IsValid() { + shutFunc = reflectValue.MethodByName("Shut").Interface().(func(*Request)) } var ( - pkgPath = t.Elem().PkgPath() + pkgPath = reflectType.Elem().PkgPath() pkgName = gfile.Basename(pkgPath) - objName = gstr.Replace(t.String(), fmt.Sprintf(`%s.`, pkgName), "") + objName = gstr.Replace(reflectType.String(), fmt.Sprintf(`%s.`, pkgName), "") ) if objName[0] == '*' { objName = fmt.Sprintf(`(%s)`, objName) @@ -194,70 +228,75 @@ func (s *Server) doBindObjectMethod(ctx context.Context, pattern string, object s.Logger().Fatalf(ctx, `%+v`, err) } - key := s.mergeBuildInNameToPattern(pattern, structName, methodName, false) - m[key] = &handlerItem{ + key := s.mergeBuildInNameToPattern(in.Pattern, structName, methodName, false) + handlerMap[key] = &handlerItem{ Name: fmt.Sprintf(`%s.%s.%s`, pkgPath, objName, methodName), Type: HandlerTypeObject, Info: funcInfo, InitFunc: initFunc, ShutFunc: shutFunc, - Middleware: middleware, - Source: source, + Middleware: in.Middleware, + Source: in.Source, } - s.bindHandlerByMap(ctx, m) + s.bindHandlerByMap(ctx, in.Prefix, handlerMap) } -func (s *Server) doBindObjectRest(ctx context.Context, pattern string, object interface{}, middleware []HandlerFunc, source string) { +func (s *Server) doBindObjectRest(ctx context.Context, in doBindObjectInput) { var ( - m = make(map[string]*handlerItem) - v = reflect.ValueOf(object) - t = v.Type() - initFunc func(*Request) - shutFunc func(*Request) + handlerMap = make(map[string]*handlerItem) + reflectValue = reflect.ValueOf(in.Object) + reflectType = reflectValue.Type() + initFunc func(*Request) + shutFunc func(*Request) ) // If given `object` is not pointer, it then creates a temporary one, // of which the value is `v`. - if v.Kind() == reflect.Struct { - newValue := reflect.New(t) - newValue.Elem().Set(v) - v = newValue - t = v.Type() + if reflectValue.Kind() == reflect.Struct { + newValue := reflect.New(reflectType) + newValue.Elem().Set(reflectValue) + reflectValue = newValue + reflectType = reflectValue.Type() } - structName := t.Elem().Name() - if v.MethodByName(methodNameInit).IsValid() { - initFunc = v.MethodByName(methodNameInit).Interface().(func(*Request)) + structName := reflectType.Elem().Name() + if reflectValue.MethodByName(methodNameInit).IsValid() { + initFunc = reflectValue.MethodByName(methodNameInit).Interface().(func(*Request)) } - if v.MethodByName(methodNameShut).IsValid() { - shutFunc = v.MethodByName(methodNameShut).Interface().(func(*Request)) + if reflectValue.MethodByName(methodNameShut).IsValid() { + shutFunc = reflectValue.MethodByName(methodNameShut).Interface().(func(*Request)) } - pkgPath := t.Elem().PkgPath() - for i := 0; i < v.NumMethod(); i++ { - methodName := t.Method(i).Name + pkgPath := reflectType.Elem().PkgPath() + for i := 0; i < reflectValue.NumMethod(); i++ { + methodName := reflectType.Method(i).Name if _, ok := methodsMap[strings.ToUpper(methodName)]; !ok { continue } pkgName := gfile.Basename(pkgPath) - objName := gstr.Replace(t.String(), fmt.Sprintf(`%s.`, pkgName), "") + objName := gstr.Replace(reflectType.String(), fmt.Sprintf(`%s.`, pkgName), "") if objName[0] == '*' { objName = fmt.Sprintf(`(%s)`, objName) } - funcInfo, err := s.checkAndCreateFuncInfo(v.Method(i).Interface(), pkgPath, objName, methodName) + funcInfo, err := s.checkAndCreateFuncInfo( + reflectValue.Method(i).Interface(), + pkgPath, + objName, + methodName, + ) if err != nil { s.Logger().Fatalf(ctx, `%+v`, err) } - key := s.mergeBuildInNameToPattern(methodName+":"+pattern, structName, methodName, false) - m[key] = &handlerItem{ + key := s.mergeBuildInNameToPattern(methodName+":"+in.Pattern, structName, methodName, false) + handlerMap[key] = &handlerItem{ Name: fmt.Sprintf(`%s.%s.%s`, pkgPath, objName, methodName), Type: HandlerTypeObject, Info: funcInfo, InitFunc: initFunc, ShutFunc: shutFunc, - Middleware: middleware, - Source: source, + Middleware: in.Middleware, + Source: in.Source, } } - s.bindHandlerByMap(ctx, m) + s.bindHandlerByMap(ctx, in.Prefix, handlerMap) } diff --git a/net/ghttp/ghttp_server_swagger.go b/net/ghttp/ghttp_server_swagger.go index e56ddca75..ea0cd34fc 100644 --- a/net/ghttp/ghttp_server_swagger.go +++ b/net/ghttp/ghttp_server_swagger.go @@ -7,9 +7,10 @@ package ghttp import ( + "net/http" + "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/text/gstr" - "net/http" ) const ( diff --git a/net/ghttp/ghttp_server_websocket.go b/net/ghttp/ghttp_server_websocket.go index 65c8740ec..2dbde255e 100644 --- a/net/ghttp/ghttp_server_websocket.go +++ b/net/ghttp/ghttp_server_websocket.go @@ -15,23 +15,23 @@ type WebSocket struct { } const ( - // TextMessage denotes a text data message. The text message payload is + // WsMsgText TextMessage denotes a text data message. The text message payload is // interpreted as UTF-8 encoded text data. - WS_MSG_TEXT = websocket.TextMessage + WsMsgText = websocket.TextMessage - // BinaryMessage denotes a binary data message. - WS_MSG_BINARY = websocket.BinaryMessage + // WsMsgBinary BinaryMessage denotes a binary data message. + WsMsgBinary = websocket.BinaryMessage - // CloseMessage denotes a close control message. The optional message + // WsMsgClose CloseMessage denotes a close control message. The optional message // payload contains a numeric code and text. Use the FormatCloseMessage // function to format a close message payload. - WS_MSG_CLOSE = websocket.CloseMessage + WsMsgClose = websocket.CloseMessage - // PingMessage denotes a ping control message. The optional message payload + // WsMsgPing PingMessage denotes a ping control message. The optional message payload // is UTF-8 encoded text. - WS_MSG_PING = websocket.PingMessage + WsMsgPing = websocket.PingMessage - // PongMessage denotes a pong control message. The optional message payload + // WsMsgPong PongMessage denotes a pong control message. The optional message payload // is UTF-8 encoded text. - WS_MSG_PONG = websocket.PongMessage + WsMsgPong = websocket.PongMessage ) diff --git a/net/ghttp/ghttp_unit_init_test.go b/net/ghttp/ghttp_unit_init_test.go deleted file mode 100644 index 71f5b63d9..000000000 --- a/net/ghttp/ghttp_unit_init_test.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. -// -// This Source Code Form is subject to the terms of the MIT License. -// If a copy of the MIT was not distributed with this file, -// You can obtain one at https://github.com/gogf/gf. - -package ghttp_test - -import ( - "context" - "github.com/gogf/gf/v2/container/garray" - "github.com/gogf/gf/v2/os/genv" -) - -var ( - ctx = context.TODO() - ports = garray.NewIntArray(true) -) - -func init() { - genv.Set("UNDER_TEST", "1") - for i := 7000; i <= 8000; i++ { - ports.Append(i) - } -} diff --git a/net/ghttp/ghttp_unit_router_handler_extended_test.go b/net/ghttp/ghttp_unit_router_handler_extended_test.go deleted file mode 100644 index 801b3c358..000000000 --- a/net/ghttp/ghttp_unit_router_handler_extended_test.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. -// -// This Source Code Form is subject to the terms of the MIT License. -// If a copy of the MIT was not distributed with this file, -// You can obtain one at https://github.com/gogf/gf. - -package ghttp_test - -import ( - "context" - "fmt" - "github.com/gogf/gf/v2/errors/gerror" - "testing" - "time" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/test/gtest" -) - -func Test_Router_Handler_Extended_Handler_WithObject(t *testing.T) { - type TestReq struct { - Age int - Name string - } - type TestRes struct { - Id int - Age int - Name string - } - p, _ := ports.PopRand() - s := g.Server(p) - s.Use(ghttp.MiddlewareHandlerResponse) - s.BindHandler("/test", func(ctx context.Context, req *TestReq) (res *TestRes, err error) { - return &TestRes{ - Id: 1, - Age: req.Age, - Name: req.Name, - }, nil - }) - s.BindHandler("/test/error", func(ctx context.Context, req *TestReq) (res *TestRes, err error) { - return &TestRes{ - Id: 1, - Age: req.Age, - Name: req.Name, - }, gerror.New("error") - }) - s.SetPort(p) - s.SetDumpRouterMap(false) - s.Start() - defer s.Shutdown() - - time.Sleep(100 * time.Millisecond) - gtest.C(t, func(t *gtest.T) { - client := g.Client() - client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p)) - - t.Assert(client.GetContent(ctx, "/test?age=18&name=john"), `{"code":0,"message":"","data":{"Id":1,"Age":18,"Name":"john"}}`) - t.Assert(client.GetContent(ctx, "/test/error"), `{"code":50,"message":"error","data":null}`) - }) -} diff --git a/net/ghttp/ghttp_z_example_init_test.go b/net/ghttp/ghttp_z_example_init_test.go index e640202d8..6bc446825 100644 --- a/net/ghttp/ghttp_z_example_init_test.go +++ b/net/ghttp/ghttp_z_example_init_test.go @@ -7,9 +7,10 @@ package ghttp_test import ( + "time" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" - "time" ) func init() { diff --git a/net/ghttp/ghttp_z_example_post_test.go b/net/ghttp/ghttp_z_example_post_test.go index 58c4c6d70..6c573645d 100644 --- a/net/ghttp/ghttp_z_example_post_test.go +++ b/net/ghttp/ghttp_z_example_post_test.go @@ -8,6 +8,7 @@ package ghttp_test import ( "fmt" + "github.com/gogf/gf/v2/frame/g" ) diff --git a/net/ghttp/ghttp_z_example_test.go b/net/ghttp/ghttp_z_example_test.go index 81d96cc49..61aeba006 100644 --- a/net/ghttp/ghttp_z_example_test.go +++ b/net/ghttp/ghttp_z_example_test.go @@ -9,10 +9,11 @@ package ghttp_test import ( "context" "fmt" + "time" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/os/gfile" - "time" ) func ExampleHelloWorld() { diff --git a/net/ghttp/ghttp_unit_client_dump_test.go b/net/ghttp/ghttp_z_unit_feature_client_dump_test.go similarity index 100% rename from net/ghttp/ghttp_unit_client_dump_test.go rename to net/ghttp/ghttp_z_unit_feature_client_dump_test.go diff --git a/net/ghttp/ghttp_unit_client_test.go b/net/ghttp/ghttp_z_unit_feature_client_test.go similarity index 99% rename from net/ghttp/ghttp_unit_client_test.go rename to net/ghttp/ghttp_z_unit_feature_client_test.go index 42dc62b66..e69b08955 100644 --- a/net/ghttp/ghttp_unit_client_test.go +++ b/net/ghttp/ghttp_z_unit_feature_client_test.go @@ -17,12 +17,11 @@ import ( "github.com/gogf/gf/v2/debug/gdebug" "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/util/guid" - "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" + "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/guid" ) func Test_Client_Basic(t *testing.T) { diff --git a/net/ghttp/ghttp_unit_config_test.go b/net/ghttp/ghttp_z_unit_feature_config_test.go similarity index 98% rename from net/ghttp/ghttp_unit_config_test.go rename to net/ghttp/ghttp_z_unit_feature_config_test.go index 337638d0c..86dbf0a1c 100644 --- a/net/ghttp/ghttp_unit_config_test.go +++ b/net/ghttp/ghttp_z_unit_feature_config_test.go @@ -8,18 +8,16 @@ package ghttp_test import ( "fmt" - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/text/gstr" "testing" "time" - "github.com/gogf/gf/v2/util/gconv" - "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" - + "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/text/gstr" + "github.com/gogf/gf/v2/util/gconv" ) func Test_ConfigFromMap(t *testing.T) { @@ -47,7 +45,7 @@ func Test_SetConfigWithMap(t *testing.T) { gtest.C(t, func(t *gtest.T) { m := g.Map{ "Address": ":8199", - //"ServerRoot": "/var/www/MyServerRoot", + // "ServerRoot": "/var/www/MyServerRoot", "IndexFiles": g.Slice{"index.php", "main.php"}, "AccessLogEnabled": true, "ErrorLogEnabled": true, diff --git a/net/ghttp/ghttp_unit_context_test.go b/net/ghttp/ghttp_z_unit_feature_context_test.go similarity index 100% rename from net/ghttp/ghttp_unit_context_test.go rename to net/ghttp/ghttp_z_unit_feature_context_test.go diff --git a/net/ghttp/ghttp_unit_cookie_test.go b/net/ghttp/ghttp_z_unit_feature_cookie_test.go similarity index 100% rename from net/ghttp/ghttp_unit_cookie_test.go rename to net/ghttp/ghttp_z_unit_feature_cookie_test.go diff --git a/net/ghttp/ghttp_unit_error_code_test.go b/net/ghttp/ghttp_z_unit_feature_error_code_test.go similarity index 100% rename from net/ghttp/ghttp_unit_error_code_test.go rename to net/ghttp/ghttp_z_unit_feature_error_code_test.go index c59d14b25..c52dec18f 100644 --- a/net/ghttp/ghttp_unit_error_code_test.go +++ b/net/ghttp/ghttp_z_unit_feature_error_code_test.go @@ -10,13 +10,13 @@ package ghttp_test import ( "fmt" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/net/ghttp" "testing" "time" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/test/gtest" ) diff --git a/net/ghttp/ghttp_unit_https_test.go b/net/ghttp/ghttp_z_unit_feature_https_test.go similarity index 99% rename from net/ghttp/ghttp_unit_https_test.go rename to net/ghttp/ghttp_z_unit_feature_https_test.go index c8bed6c3f..26e7d70d8 100644 --- a/net/ghttp/ghttp_unit_https_test.go +++ b/net/ghttp/ghttp_z_unit_feature_https_test.go @@ -8,18 +8,17 @@ package ghttp_test import ( "fmt" - "github.com/gogf/gf/v2/debug/gdebug" - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/text/gstr" "testing" "time" + "github.com/gogf/gf/v2/debug/gdebug" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/test/gtest" - _ "github.com/gogf/gf/v2/net/ghttp/testdata/https/packed" + "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/os/gtime" + "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/text/gstr" ) func Test_HTTPS_Basic(t *testing.T) { diff --git a/net/ghttp/ghttp_unit_ip_test.go b/net/ghttp/ghttp_z_unit_feature_ip_test.go similarity index 100% rename from net/ghttp/ghttp_unit_ip_test.go rename to net/ghttp/ghttp_z_unit_feature_ip_test.go diff --git a/net/ghttp/ghttp_unit_log_test.go b/net/ghttp/ghttp_z_unit_feature_log_test.go similarity index 95% rename from net/ghttp/ghttp_unit_log_test.go rename to net/ghttp/ghttp_z_unit_feature_log_test.go index 76e11159c..5c1f99809 100644 --- a/net/ghttp/ghttp_unit_log_test.go +++ b/net/ghttp/ghttp_z_unit_feature_log_test.go @@ -10,15 +10,15 @@ package ghttp_test import ( "fmt" - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/text/gstr" "testing" "time" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/text/gstr" ) func Test_Log(t *testing.T) { @@ -52,11 +52,11 @@ func Test_Log(t *testing.T) { t.Assert(gstr.Contains(gfile.GetContents(logPath1), "HANDLER"), true) logPath2 := gfile.Join(logDir, "access-"+gtime.Now().Format("Ymd")+".log") - //fmt.Println(gfile.GetContents(logPath2)) + // fmt.Println(gfile.GetContents(logPath2)) t.Assert(gstr.Contains(gfile.GetContents(logPath2), " /hello "), true) logPath3 := gfile.Join(logDir, "error-"+gtime.Now().Format("Ymd")+".log") - //fmt.Println(gfile.GetContents(logPath3)) + // fmt.Println(gfile.GetContents(logPath3)) t.Assert(gstr.Contains(gfile.GetContents(logPath3), "custom error"), true) }) } diff --git a/net/ghttp/ghttp_unit_middleware_basic_test.go b/net/ghttp/ghttp_z_unit_feature_middleware_basic_test.go similarity index 100% rename from net/ghttp/ghttp_unit_middleware_basic_test.go rename to net/ghttp/ghttp_z_unit_feature_middleware_basic_test.go index f831e997c..2837abb35 100644 --- a/net/ghttp/ghttp_unit_middleware_basic_test.go +++ b/net/ghttp/ghttp_z_unit_feature_middleware_basic_test.go @@ -8,12 +8,12 @@ package ghttp_test import ( "fmt" - "github.com/gogf/gf/v2/container/garray" - "github.com/gogf/gf/v2/debug/gdebug" "net/http" "testing" "time" + "github.com/gogf/gf/v2/container/garray" + "github.com/gogf/gf/v2/debug/gdebug" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/test/gtest" diff --git a/net/ghttp/ghttp_unit_middleware_cors_test.go b/net/ghttp/ghttp_z_unit_feature_middleware_cors_test.go similarity index 99% rename from net/ghttp/ghttp_unit_middleware_cors_test.go rename to net/ghttp/ghttp_z_unit_feature_middleware_cors_test.go index b7d09c179..27f68c4c2 100644 --- a/net/ghttp/ghttp_unit_middleware_cors_test.go +++ b/net/ghttp/ghttp_z_unit_feature_middleware_cors_test.go @@ -8,11 +8,12 @@ package ghttp_test import ( "fmt" + "testing" + "time" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/test/gtest" - "testing" - "time" ) func Test_Middleware_CORS1(t *testing.T) { diff --git a/net/ghttp/ghttp_unit_openapi_swagger_test.go b/net/ghttp/ghttp_z_unit_feature_openapi_swagger_test.go similarity index 100% rename from net/ghttp/ghttp_unit_openapi_swagger_test.go rename to net/ghttp/ghttp_z_unit_feature_openapi_swagger_test.go index d8d0b814d..14919ef0c 100644 --- a/net/ghttp/ghttp_unit_openapi_swagger_test.go +++ b/net/ghttp/ghttp_z_unit_feature_openapi_swagger_test.go @@ -9,15 +9,15 @@ package ghttp_test import ( "context" "fmt" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/text/gstr" - "github.com/gogf/gf/v2/util/gmeta" "testing" "time" + "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/text/gstr" + "github.com/gogf/gf/v2/util/gmeta" ) func Test_OpenApi_Swagger(t *testing.T) { diff --git a/net/ghttp/ghttp_unit_pprof_test.go b/net/ghttp/ghttp_z_unit_feature_pprof_test.go similarity index 100% rename from net/ghttp/ghttp_unit_pprof_test.go rename to net/ghttp/ghttp_z_unit_feature_pprof_test.go diff --git a/net/ghttp/ghttp_unit_request_ctx_test.go b/net/ghttp/ghttp_z_unit_feature_request_ctx_test.go similarity index 99% rename from net/ghttp/ghttp_unit_request_ctx_test.go rename to net/ghttp/ghttp_z_unit_feature_request_ctx_test.go index 55758f010..0cd9c3303 100644 --- a/net/ghttp/ghttp_unit_request_ctx_test.go +++ b/net/ghttp/ghttp_z_unit_feature_request_ctx_test.go @@ -9,11 +9,12 @@ package ghttp_test import ( "context" "fmt" + "testing" + "time" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/test/gtest" - "testing" - "time" ) func Test_Request_SetCtx(t *testing.T) { diff --git a/net/ghttp/ghttp_unit_request_file_test.go b/net/ghttp/ghttp_z_unit_feature_request_file_test.go similarity index 100% rename from net/ghttp/ghttp_unit_request_file_test.go rename to net/ghttp/ghttp_z_unit_feature_request_file_test.go index aeb237250..8a3a87ac0 100644 --- a/net/ghttp/ghttp_unit_request_file_test.go +++ b/net/ghttp/ghttp_z_unit_feature_request_file_test.go @@ -8,16 +8,16 @@ package ghttp_test import ( "fmt" - "github.com/gogf/gf/v2/debug/gdebug" - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/text/gstr" "testing" "time" + "github.com/gogf/gf/v2/debug/gdebug" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" + "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/text/gstr" ) func Test_Params_File_Single(t *testing.T) { diff --git a/net/ghttp/ghttp_unit_request_json_test.go b/net/ghttp/ghttp_z_unit_feature_request_json_test.go similarity index 100% rename from net/ghttp/ghttp_unit_request_json_test.go rename to net/ghttp/ghttp_z_unit_feature_request_json_test.go index 75a829c81..b3324b7e4 100644 --- a/net/ghttp/ghttp_unit_request_json_test.go +++ b/net/ghttp/ghttp_z_unit_feature_request_json_test.go @@ -8,11 +8,11 @@ package ghttp_test import ( "fmt" - "github.com/gogf/gf/v2/internal/json" "testing" "time" "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/test/gtest" ) diff --git a/net/ghttp/ghttp_unit_request_page_test.go b/net/ghttp/ghttp_z_unit_feature_request_page_test.go similarity index 100% rename from net/ghttp/ghttp_unit_request_page_test.go rename to net/ghttp/ghttp_z_unit_feature_request_page_test.go diff --git a/net/ghttp/ghttp_unit_request_struct_test.go b/net/ghttp/ghttp_z_unit_feature_request_struct_test.go similarity index 98% rename from net/ghttp/ghttp_unit_request_struct_test.go rename to net/ghttp/ghttp_z_unit_feature_request_struct_test.go index e074ca092..1f748906b 100644 --- a/net/ghttp/ghttp_unit_request_struct_test.go +++ b/net/ghttp/ghttp_z_unit_feature_request_struct_test.go @@ -11,11 +11,10 @@ import ( "testing" "time" - "github.com/gogf/gf/v2/util/gvalid" - "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gvalid" ) func Test_Params_Parse(t *testing.T) { @@ -359,7 +358,7 @@ func Test_Params_Parse_Attr_Pointer2(t *testing.T) { } // It does not support this kind of converting yet. -//func Test_Params_Parse_Attr_SliceSlice(t *testing.T) { +// func Test_Params_Parse_Attr_SliceSlice(t *testing.T) { // type User struct { // Id int // Name string @@ -387,7 +386,7 @@ func Test_Params_Parse_Attr_Pointer2(t *testing.T) { // client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p)) // t.Assert(client.PostContent(ctx, "/parse", `{"id":1,"name":"john","scores":[[1,2,3]]}`), `1100`) // }) -//} +// } func Test_Params_Struct(t *testing.T) { type User struct { @@ -452,8 +451,8 @@ func Test_Params_Struct(t *testing.T) { t.Assert(client.PostContent(ctx, "/struct1", `id=1&name=john&password1=123&password2=456`), `1john123456`) t.Assert(client.PostContent(ctx, "/struct2", `id=1&name=john&password1=123&password2=456`), `1john123456`) t.Assert(client.PostContent(ctx, "/struct2", ``), ``) - t.Assert(client.PostContent(ctx, "/struct-valid", `id=1&name=john&password1=123&password2=0`), `The password2 value length must be between 2 and 20; 密码强度不足`) - t.Assert(client.PostContent(ctx, "/parse", `id=1&name=john&password1=123&password2=0`), `The password2 value length must be between 2 and 20; 密码强度不足`) + t.Assert(client.PostContent(ctx, "/struct-valid", `id=1&name=john&password1=123&password2=0`), "The password2 value `0` length must be between 2 and 20; 密码强度不足") + t.Assert(client.PostContent(ctx, "/parse", `id=1&name=john&password1=123&password2=0`), "The password2 value `0` length must be between 2 and 20; 密码强度不足") t.Assert(client.PostContent(ctx, "/parse", `{"id":1,"name":"john","password1":"123Abc!@#","password2":"123Abc!@#"}`), `1john123Abc!@#123Abc!@#`) }) } diff --git a/net/ghttp/ghttp_unit_request_test.go b/net/ghttp/ghttp_z_unit_feature_request_test.go similarity index 99% rename from net/ghttp/ghttp_unit_request_test.go rename to net/ghttp/ghttp_z_unit_feature_request_test.go index 723286ef7..c40f2ff16 100644 --- a/net/ghttp/ghttp_unit_request_test.go +++ b/net/ghttp/ghttp_z_unit_feature_request_test.go @@ -14,7 +14,6 @@ import ( "time" "github.com/gogf/gf/v2/encoding/gjson" - "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/test/gtest" @@ -538,7 +537,7 @@ func Test_Params_Parse_DefaultValueTag(t *testing.T) { func Test_Params_Parse_Validation(t *testing.T) { type RegisterReq struct { - Name string `p:"username" v:"required|length:6,30#请输入账号|账号长度为:min到:max位"` + Name string `p:"username" v:"required|length:6,30#请输入账号|账号长度为{min}到{max}位"` Pass string `p:"password1" v:"required|length:6,30#请输入密码|密码长度不够"` Pass2 string `p:"password2" v:"required|length:6,30|same:password1#请确认密码|密码长度不够|两次密码不一致"` } diff --git a/net/ghttp/ghttp_unit_request_xml_test.go b/net/ghttp/ghttp_z_unit_feature_request_xml_test.go similarity index 100% rename from net/ghttp/ghttp_unit_request_xml_test.go rename to net/ghttp/ghttp_z_unit_feature_request_xml_test.go diff --git a/net/ghttp/ghttp_unit_router_basic_test.go b/net/ghttp/ghttp_z_unit_feature_router_basic_test.go similarity index 100% rename from net/ghttp/ghttp_unit_router_basic_test.go rename to net/ghttp/ghttp_z_unit_feature_router_basic_test.go diff --git a/net/ghttp/ghttp_unit_router_domain_basic_test.go b/net/ghttp/ghttp_z_unit_feature_router_domain_basic_test.go similarity index 97% rename from net/ghttp/ghttp_unit_router_domain_basic_test.go rename to net/ghttp/ghttp_z_unit_feature_router_domain_basic_test.go index fd96cb3e5..9ad152ebf 100644 --- a/net/ghttp/ghttp_unit_router_domain_basic_test.go +++ b/net/ghttp/ghttp_z_unit_feature_router_domain_basic_test.go @@ -8,11 +8,11 @@ package ghttp_test import ( "fmt" - "github.com/gogf/gf/v2/internal/intlog" "testing" "time" "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/test/gtest" ) @@ -333,16 +333,16 @@ func Test_Router_DomainGroup(t *testing.T) { s := g.Server(p) d := s.Domain("localhost, local") d.Group("/", func(group *ghttp.RouterGroup) { - group.Group("/app", func(gApp *ghttp.RouterGroup) { - gApp.GET("/{table}/list/{page}.html", func(r *ghttp.Request) { + group.Group("/app", func(group *ghttp.RouterGroup) { + group.GET("/{table}/list/{page}.html", func(r *ghttp.Request) { intlog.Print(r.Context(), "/{table}/list/{page}.html") r.Response.Write(r.Get("table"), "&", r.Get("page")) }) - gApp.GET("/order/info/{order_id}", func(r *ghttp.Request) { + group.GET("/order/info/{order_id}", func(r *ghttp.Request) { intlog.Print(r.Context(), "/order/info/{order_id}") r.Response.Write(r.Get("order_id")) }) - gApp.DELETE("/comment/{id}", func(r *ghttp.Request) { + group.DELETE("/comment/{id}", func(r *ghttp.Request) { intlog.Print(r.Context(), "/comment/{id}") r.Response.Write(r.Get("id")) }) diff --git a/net/ghttp/ghttp_unit_router_domain_object_rest_test.go b/net/ghttp/ghttp_z_unit_feature_router_domain_object_rest_test.go similarity index 100% rename from net/ghttp/ghttp_unit_router_domain_object_rest_test.go rename to net/ghttp/ghttp_z_unit_feature_router_domain_object_rest_test.go diff --git a/net/ghttp/ghttp_unit_router_domain_object_test.go b/net/ghttp/ghttp_z_unit_feature_router_domain_object_test.go similarity index 100% rename from net/ghttp/ghttp_unit_router_domain_object_test.go rename to net/ghttp/ghttp_z_unit_feature_router_domain_object_test.go diff --git a/net/ghttp/ghttp_unit_router_exit_test.go b/net/ghttp/ghttp_z_unit_feature_router_exit_test.go similarity index 100% rename from net/ghttp/ghttp_unit_router_exit_test.go rename to net/ghttp/ghttp_z_unit_feature_router_exit_test.go diff --git a/net/ghttp/ghttp_unit_router_group_group_test.go b/net/ghttp/ghttp_z_unit_feature_router_group_group_test.go similarity index 100% rename from net/ghttp/ghttp_unit_router_group_group_test.go rename to net/ghttp/ghttp_z_unit_feature_router_group_group_test.go diff --git a/net/ghttp/ghttp_unit_router_group_hook_test.go b/net/ghttp/ghttp_z_unit_feature_router_group_hook_test.go similarity index 72% rename from net/ghttp/ghttp_unit_router_group_hook_test.go rename to net/ghttp/ghttp_z_unit_feature_router_group_hook_test.go index 9a7d6be9e..edea6a80d 100644 --- a/net/ghttp/ghttp_unit_router_group_hook_test.go +++ b/net/ghttp/ghttp_z_unit_feature_router_group_hook_test.go @@ -74,33 +74,3 @@ func Test_Router_Group_Hook2(t *testing.T) { t.Assert(client.PostContent(ctx, "/api/ThisDoesNotExist"), "Not Found") }) } - -func Test_Router_Group_Hook3(t *testing.T) { - p, _ := ports.PopRand() - s := g.Server(p) - s.Group("/api").Bind([]g.Slice{ - {"ALL", "handler", func(r *ghttp.Request) { - r.Response.Write("1") - }}, - {"ALL", "/*", func(r *ghttp.Request) { - r.Response.Write("0") - }, ghttp.HookBeforeServe}, - {"ALL", "/*", func(r *ghttp.Request) { - r.Response.Write("2") - }, ghttp.HookAfterServe}, - }) - - s.SetPort(p) - s.SetDumpRouterMap(false) - s.Start() - defer s.Shutdown() - - time.Sleep(100 * time.Millisecond) - gtest.C(t, func(t *gtest.T) { - client := g.Client() - client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p)) - t.Assert(client.GetContent(ctx, "/api/handler"), "012") - t.Assert(client.PostContent(ctx, "/api/handler"), "012") - t.Assert(client.DeleteContent(ctx, "/api/ThisDoesNotExist"), "02") - }) -} diff --git a/net/ghttp/ghttp_unit_router_group_rest_test.go b/net/ghttp/ghttp_z_unit_feature_router_group_rest_test.go similarity index 100% rename from net/ghttp/ghttp_unit_router_group_rest_test.go rename to net/ghttp/ghttp_z_unit_feature_router_group_rest_test.go diff --git a/net/ghttp/ghttp_unit_router_group_test.go b/net/ghttp/ghttp_z_unit_feature_router_group_test.go similarity index 83% rename from net/ghttp/ghttp_unit_router_group_test.go rename to net/ghttp/ghttp_z_unit_feature_router_group_test.go index ef2dabf12..195d8da99 100644 --- a/net/ghttp/ghttp_unit_router_group_test.go +++ b/net/ghttp/ghttp_z_unit_feature_router_group_test.go @@ -78,39 +78,6 @@ func Test_Router_GroupBasic1(t *testing.T) { }) } -func Test_Router_GroupBasic2(t *testing.T) { - p, _ := ports.PopRand() - s := g.Server(p) - obj := new(GroupObject) - // 分组路由批量注册 - s.Group("/api").Bind([]g.Slice{ - {"ALL", "/handler", Handler}, - {"ALL", "/obj", obj}, - {"GET", "/obj/my-show", obj, "Show"}, - {"REST", "/obj/rest", obj}, - }) - s.SetPort(p) - s.SetDumpRouterMap(false) - s.Start() - defer s.Shutdown() - - time.Sleep(100 * time.Millisecond) - gtest.C(t, func(t *gtest.T) { - client := g.Client() - client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p)) - - t.Assert(client.GetContent(ctx, "/api/handler"), "Handler") - - t.Assert(client.GetContent(ctx, "/api/obj/delete"), "1Object Delete2") - t.Assert(client.GetContent(ctx, "/api/obj/my-show"), "1Object Show2") - t.Assert(client.GetContent(ctx, "/api/obj/show"), "1Object Show2") - t.Assert(client.DeleteContent(ctx, "/api/obj/rest"), "1Object Delete2") - - t.Assert(client.DeleteContent(ctx, "/ThisDoesNotExist"), "Not Found") - t.Assert(client.DeleteContent(ctx, "/api/ThisDoesNotExist"), "Not Found") - }) -} - func Test_Router_GroupBuildInVar(t *testing.T) { p, _ := ports.PopRand() s := g.Server(p) diff --git a/net/ghttp/ghttp_z_unit_feature_router_handler_extended_test.go b/net/ghttp/ghttp_z_unit_feature_router_handler_extended_test.go new file mode 100644 index 000000000..8d5a15e58 --- /dev/null +++ b/net/ghttp/ghttp_z_unit_feature_router_handler_extended_test.go @@ -0,0 +1,197 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +package ghttp_test + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/net/ghttp" + "github.com/gogf/gf/v2/test/gtest" +) + +func Test_Router_Handler_Extended_Handler_WithObject(t *testing.T) { + type TestReq struct { + Age int + Name string + } + type TestRes struct { + Id int + Age int + Name string + } + p, _ := ports.PopRand() + s := g.Server(p) + s.Use(ghttp.MiddlewareHandlerResponse) + s.BindHandler("/test", func(ctx context.Context, req *TestReq) (res *TestRes, err error) { + return &TestRes{ + Id: 1, + Age: req.Age, + Name: req.Name, + }, nil + }) + s.BindHandler("/test/error", func(ctx context.Context, req *TestReq) (res *TestRes, err error) { + return &TestRes{ + Id: 1, + Age: req.Age, + Name: req.Name, + }, gerror.New("error") + }) + s.SetPort(p) + s.SetDumpRouterMap(false) + s.Start() + defer s.Shutdown() + + time.Sleep(100 * time.Millisecond) + gtest.C(t, func(t *gtest.T) { + client := g.Client() + client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p)) + + t.Assert(client.GetContent(ctx, "/test?age=18&name=john"), `{"code":0,"message":"","data":{"Id":1,"Age":18,"Name":"john"}}`) + t.Assert(client.GetContent(ctx, "/test/error"), `{"code":50,"message":"error","data":null}`) + }) +} + +type TestForHandlerWithObjectAndMeta1Req struct { + g.Meta `path:"/custom-test1" method:"get"` + Age int + Name string +} +type TestForHandlerWithObjectAndMeta1Res struct { + Id int + Age int +} + +type TestForHandlerWithObjectAndMeta2Req struct { + g.Meta `path:"/custom-test2" method:"get"` + Age int + Name string +} +type TestForHandlerWithObjectAndMeta2Res struct { + Id int + Name string +} + +type ControllerForHandlerWithObjectAndMeta1 struct{} + +func (ControllerForHandlerWithObjectAndMeta1) Test1(ctx context.Context, req *TestForHandlerWithObjectAndMeta1Req) (res *TestForHandlerWithObjectAndMeta1Res, err error) { + return &TestForHandlerWithObjectAndMeta1Res{ + Id: 1, + Age: req.Age, + }, nil +} + +func (ControllerForHandlerWithObjectAndMeta1) Test2(ctx context.Context, req *TestForHandlerWithObjectAndMeta2Req) (res *TestForHandlerWithObjectAndMeta2Res, err error) { + return &TestForHandlerWithObjectAndMeta2Res{ + Id: 1, + Name: req.Name, + }, nil +} + +type TestForHandlerWithObjectAndMeta3Req struct { + g.Meta `path:"/custom-test3" method:"get"` + Age int + Name string +} +type TestForHandlerWithObjectAndMeta3Res struct { + Id int + Age int +} + +type TestForHandlerWithObjectAndMeta4Req struct { + g.Meta `path:"/custom-test4" method:"get"` + Age int + Name string +} +type TestForHandlerWithObjectAndMeta4Res struct { + Id int + Name string +} + +type ControllerForHandlerWithObjectAndMeta2 struct{} + +func (ControllerForHandlerWithObjectAndMeta2) Test3(ctx context.Context, req *TestForHandlerWithObjectAndMeta3Req) (res *TestForHandlerWithObjectAndMeta3Res, err error) { + return &TestForHandlerWithObjectAndMeta3Res{ + Id: 1, + Age: req.Age, + }, nil +} + +func (ControllerForHandlerWithObjectAndMeta2) Test4(ctx context.Context, req *TestForHandlerWithObjectAndMeta4Req) (res *TestForHandlerWithObjectAndMeta4Res, err error) { + return &TestForHandlerWithObjectAndMeta4Res{ + Id: 1, + Name: req.Name, + }, nil +} +func Test_Router_Handler_Extended_Handler_WithObjectAndMeta(t *testing.T) { + p, _ := ports.PopRand() + s := g.Server(p) + s.Use(ghttp.MiddlewareHandlerResponse) + s.Group("/", func(group *ghttp.RouterGroup) { + group.ALL("/", new(ControllerForHandlerWithObjectAndMeta1)) + }) + s.SetPort(p) + s.SetDumpRouterMap(false) + s.Start() + defer s.Shutdown() + + time.Sleep(100 * time.Millisecond) + gtest.C(t, func(t *gtest.T) { + client := g.Client() + client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p)) + + t.Assert(client.GetContent(ctx, "/"), `{"code":0,"message":"","data":null}`) + t.Assert(client.GetContent(ctx, "/custom-test1?age=18&name=john"), `{"code":0,"message":"","data":{"Id":1,"Age":18}}`) + t.Assert(client.GetContent(ctx, "/custom-test2?age=18&name=john"), `{"code":0,"message":"","data":{"Id":1,"Name":"john"}}`) + t.Assert(client.PostContent(ctx, "/custom-test2?age=18&name=john"), `{"code":0,"message":"","data":null}`) + }) +} + +func Test_Router_Handler_Extended_Handler_Group_Bind(t *testing.T) { + p, _ := ports.PopRand() + s := g.Server(p) + s.Use(ghttp.MiddlewareHandlerResponse) + s.Group("/api/v1", func(group *ghttp.RouterGroup) { + group.Bind( + new(ControllerForHandlerWithObjectAndMeta1), + new(ControllerForHandlerWithObjectAndMeta2), + ) + }) + s.Group("/api/v2", func(group *ghttp.RouterGroup) { + group.Bind( + new(ControllerForHandlerWithObjectAndMeta1), + new(ControllerForHandlerWithObjectAndMeta2), + ) + }) + s.SetPort(p) + s.SetDumpRouterMap(false) + s.Start() + defer s.Shutdown() + + time.Sleep(100 * time.Millisecond) + gtest.C(t, func(t *gtest.T) { + client := g.Client() + client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p)) + + t.Assert(client.GetContent(ctx, "/"), `{"code":0,"message":"","data":null}`) + t.Assert(client.GetContent(ctx, "/api/v1/custom-test1?age=18&name=john"), `{"code":0,"message":"","data":{"Id":1,"Age":18}}`) + t.Assert(client.GetContent(ctx, "/api/v1/custom-test2?age=18&name=john"), `{"code":0,"message":"","data":{"Id":1,"Name":"john"}}`) + t.Assert(client.PostContent(ctx, "/api/v1/custom-test2?age=18&name=john"), `{"code":0,"message":"","data":null}`) + + t.Assert(client.GetContent(ctx, "/api/v1/custom-test3?age=18&name=john"), `{"code":0,"message":"","data":{"Id":1,"Age":18}}`) + t.Assert(client.GetContent(ctx, "/api/v1/custom-test4?age=18&name=john"), `{"code":0,"message":"","data":{"Id":1,"Name":"john"}}`) + + t.Assert(client.GetContent(ctx, "/api/v2/custom-test1?age=18&name=john"), `{"code":0,"message":"","data":{"Id":1,"Age":18}}`) + t.Assert(client.GetContent(ctx, "/api/v2/custom-test2?age=18&name=john"), `{"code":0,"message":"","data":{"Id":1,"Name":"john"}}`) + t.Assert(client.GetContent(ctx, "/api/v2/custom-test3?age=18&name=john"), `{"code":0,"message":"","data":{"Id":1,"Age":18}}`) + t.Assert(client.GetContent(ctx, "/api/v2/custom-test4?age=18&name=john"), `{"code":0,"message":"","data":{"Id":1,"Name":"john"}}`) + }) +} diff --git a/net/ghttp/ghttp_unit_router_hook_test.go b/net/ghttp/ghttp_z_unit_feature_router_hook_test.go similarity index 100% rename from net/ghttp/ghttp_unit_router_hook_test.go rename to net/ghttp/ghttp_z_unit_feature_router_hook_test.go diff --git a/net/ghttp/ghttp_unit_router_names_test.go b/net/ghttp/ghttp_z_unit_feature_router_names_test.go similarity index 100% rename from net/ghttp/ghttp_unit_router_names_test.go rename to net/ghttp/ghttp_z_unit_feature_router_names_test.go diff --git a/net/ghttp/ghttp_unit_router_object_rest1_test.go b/net/ghttp/ghttp_z_unit_feature_router_object_rest1_test.go similarity index 100% rename from net/ghttp/ghttp_unit_router_object_rest1_test.go rename to net/ghttp/ghttp_z_unit_feature_router_object_rest1_test.go diff --git a/net/ghttp/ghttp_unit_router_object_rest2_test.go b/net/ghttp/ghttp_z_unit_feature_router_object_rest2_test.go similarity index 100% rename from net/ghttp/ghttp_unit_router_object_rest2_test.go rename to net/ghttp/ghttp_z_unit_feature_router_object_rest2_test.go diff --git a/net/ghttp/ghttp_unit_router_object_test.go b/net/ghttp/ghttp_z_unit_feature_router_object_test.go similarity index 100% rename from net/ghttp/ghttp_unit_router_object_test.go rename to net/ghttp/ghttp_z_unit_feature_router_object_test.go diff --git a/net/ghttp/ghttp_unit_server_util_test.go b/net/ghttp/ghttp_z_unit_feature_server_util_test.go similarity index 100% rename from net/ghttp/ghttp_unit_server_util_test.go rename to net/ghttp/ghttp_z_unit_feature_server_util_test.go diff --git a/net/ghttp/ghttp_unit_session_test.go b/net/ghttp/ghttp_z_unit_feature_session_test.go similarity index 100% rename from net/ghttp/ghttp_unit_session_test.go rename to net/ghttp/ghttp_z_unit_feature_session_test.go diff --git a/net/ghttp/ghttp_unit_static_test.go b/net/ghttp/ghttp_z_unit_feature_static_test.go similarity index 99% rename from net/ghttp/ghttp_unit_static_test.go rename to net/ghttp/ghttp_z_unit_feature_static_test.go index a19e46570..9c65534e5 100644 --- a/net/ghttp/ghttp_unit_static_test.go +++ b/net/ghttp/ghttp_z_unit_feature_static_test.go @@ -10,15 +10,14 @@ package ghttp_test import ( "fmt" - "github.com/gogf/gf/v2/debug/gdebug" "testing" "time" - "github.com/gogf/gf/v2/text/gstr" - + "github.com/gogf/gf/v2/debug/gdebug" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/text/gstr" ) func Test_Static_ServerRoot(t *testing.T) { diff --git a/net/ghttp/ghttp_unit_status_test.go b/net/ghttp/ghttp_z_unit_feature_status_test.go similarity index 100% rename from net/ghttp/ghttp_unit_status_test.go rename to net/ghttp/ghttp_z_unit_feature_status_test.go diff --git a/net/ghttp/ghttp_unit_template_test.go b/net/ghttp/ghttp_z_unit_feature_template_test.go similarity index 100% rename from net/ghttp/ghttp_unit_template_test.go rename to net/ghttp/ghttp_z_unit_feature_template_test.go index 845ec53db..bfb077585 100644 --- a/net/ghttp/ghttp_unit_template_test.go +++ b/net/ghttp/ghttp_z_unit_feature_template_test.go @@ -10,14 +10,14 @@ package ghttp_test import ( "fmt" - "github.com/gogf/gf/v2/debug/gdebug" - "github.com/gogf/gf/v2/encoding/ghtml" - "github.com/gogf/gf/v2/os/gview" "testing" "time" + "github.com/gogf/gf/v2/debug/gdebug" + "github.com/gogf/gf/v2/encoding/ghtml" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" + "github.com/gogf/gf/v2/os/gview" "github.com/gogf/gf/v2/test/gtest" ) diff --git a/net/ghttp/ghttp_unit_websocket_client_test.go b/net/ghttp/ghttp_z_unit_feature_websocket_client_test.go similarity index 99% rename from net/ghttp/ghttp_unit_websocket_client_test.go rename to net/ghttp/ghttp_z_unit_feature_websocket_client_test.go index 3b831e272..56c2c794d 100644 --- a/net/ghttp/ghttp_unit_websocket_client_test.go +++ b/net/ghttp/ghttp_z_unit_feature_websocket_client_test.go @@ -12,11 +12,10 @@ import ( "testing" "time" - "github.com/gorilla/websocket" - "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/test/gtest" + "github.com/gorilla/websocket" ) func Test_WebSocketClient(t *testing.T) { diff --git a/net/ghttp/ghttp_unit_websocket_test.go b/net/ghttp/ghttp_z_unit_feature_websocket_test.go similarity index 99% rename from net/ghttp/ghttp_unit_websocket_test.go rename to net/ghttp/ghttp_z_unit_feature_websocket_test.go index 098bc7044..f03fc17bf 100644 --- a/net/ghttp/ghttp_unit_websocket_test.go +++ b/net/ghttp/ghttp_z_unit_feature_websocket_test.go @@ -11,11 +11,10 @@ import ( "testing" "time" - "github.com/gorilla/websocket" - "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/test/gtest" + "github.com/gorilla/websocket" ) func Test_WebSocket(t *testing.T) { diff --git a/net/ghttp/ghttp_unit_mess_test.go b/net/ghttp/ghttp_z_unit_test.go similarity index 78% rename from net/ghttp/ghttp_unit_mess_test.go rename to net/ghttp/ghttp_z_unit_test.go index 6c8abaa0a..3114b25c7 100644 --- a/net/ghttp/ghttp_unit_mess_test.go +++ b/net/ghttp/ghttp_z_unit_test.go @@ -7,15 +7,30 @@ package ghttp_test import ( + "context" "fmt" "testing" "time" + "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" + "github.com/gogf/gf/v2/os/genv" "github.com/gogf/gf/v2/test/gtest" ) +var ( + ctx = context.TODO() + ports = garray.NewIntArray(true) +) + +func init() { + genv.Set("UNDER_TEST", "1") + for i := 7000; i <= 8000; i++ { + ports.Append(i) + } +} + func Test_GetUrl(t *testing.T) { p, _ := ports.PopRand() s := g.Server(p) diff --git a/net/ghttp/internal/client/client.go b/net/ghttp/internal/client/client.go index a6c1686d8..1738495db 100644 --- a/net/ghttp/internal/client/client.go +++ b/net/ghttp/internal/client/client.go @@ -11,12 +11,6 @@ import ( "crypto/rand" "crypto/tls" "fmt" - "github.com/gogf/gf/v2" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/text/gstr" - "golang.org/x/net/proxy" "net" "net/http" "net/http/cookiejar" @@ -24,7 +18,14 @@ import ( "strings" "time" + "golang.org/x/net/proxy" + + "github.com/gogf/gf/v2" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/text/gregex" + "github.com/gogf/gf/v2/text/gstr" ) // Client is the HTTP client for HTTP request management. @@ -232,7 +233,7 @@ func (c *Client) SetProxy(proxyURL string) { return dialer.Dial(network, addr) } } - //c.SetTimeout(10*time.Second) + // c.SetTimeout(10*time.Second) } } diff --git a/net/ghttp/internal/client/client_bytes.go b/net/ghttp/internal/client/client_bytes.go index b6450d662..5cfb5bd17 100644 --- a/net/ghttp/internal/client/client_bytes.go +++ b/net/ghttp/internal/client/client_bytes.go @@ -8,6 +8,7 @@ package client import ( "context" + "github.com/gogf/gf/v2/internal/intlog" ) diff --git a/net/ghttp/internal/client/client_dump.go b/net/ghttp/internal/client/client_dump.go index 1c970f19b..110f3db1d 100644 --- a/net/ghttp/internal/client/client_dump.go +++ b/net/ghttp/internal/client/client_dump.go @@ -8,10 +8,11 @@ package client import ( "fmt" - "github.com/gogf/gf/v2/internal/utils" "io/ioutil" "net/http" "net/http/httputil" + + "github.com/gogf/gf/v2/internal/utils" ) // dumpTextFormat is the format of the dumped raw string diff --git a/net/ghttp/internal/client/client_request.go b/net/ghttp/internal/client/client_request.go index 3bc27a60c..c3486ba84 100644 --- a/net/ghttp/internal/client/client_request.go +++ b/net/ghttp/internal/client/client_request.go @@ -9,13 +9,6 @@ package client import ( "bytes" "context" - "github.com/gogf/gf/v2/encoding/gjson" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/internal/intlog" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/internal/utils" - "github.com/gogf/gf/v2/net/ghttp/internal/httputil" "io" "io/ioutil" "mime/multipart" @@ -24,11 +17,17 @@ import ( "strings" "time" + "github.com/gogf/gf/v2/encoding/gjson" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/intlog" + "github.com/gogf/gf/v2/internal/json" + "github.com/gogf/gf/v2/internal/utils" + "github.com/gogf/gf/v2/net/ghttp/internal/httputil" + "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/text/gregex" "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" - - "github.com/gogf/gf/v2/os/gfile" ) // Get send GET request and returns the response object. @@ -310,7 +309,7 @@ func (c *Client) callRequest(req *http.Request) (resp *Response, err error) { c.retryCount-- time.Sleep(c.retryInterval) } else { - //return resp, err + // return resp, err break } } else { diff --git a/net/ghttp/internal/client/client_tracing.go b/net/ghttp/internal/client/client_tracing.go index 630617e6f..078ad4cb1 100644 --- a/net/ghttp/internal/client/client_tracing.go +++ b/net/ghttp/internal/client/client_tracing.go @@ -12,17 +12,18 @@ import ( "net/http" "net/http/httptrace" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/propagation" + "go.opentelemetry.io/otel/trace" + "github.com/gogf/gf/v2" "github.com/gogf/gf/v2/internal/utils" "github.com/gogf/gf/v2/net/ghttp/internal/httputil" "github.com/gogf/gf/v2/net/gtrace" "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/codes" - "go.opentelemetry.io/otel/propagation" - "go.opentelemetry.io/otel/trace" ) const ( diff --git a/net/ghttp/internal/client/client_var.go b/net/ghttp/internal/client/client_var.go index a959e0818..2a9a1cac2 100644 --- a/net/ghttp/internal/client/client_var.go +++ b/net/ghttp/internal/client/client_var.go @@ -8,6 +8,7 @@ package client import ( "context" + "github.com/gogf/gf/v2/container/gvar" ) diff --git a/net/ghttp/internal/httputil/httputils.go b/net/ghttp/internal/httputil/httputils.go index 84c0679c4..7149938b9 100644 --- a/net/ghttp/internal/httputil/httputils.go +++ b/net/ghttp/internal/httputil/httputils.go @@ -7,11 +7,11 @@ package httputil import ( - "github.com/gogf/gf/v2/text/gstr" "net/http" "strings" "github.com/gogf/gf/v2/encoding/gurl" + "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" ) diff --git a/net/gipv4/gipv4_ip.go b/net/gipv4/gipv4_ip.go index ef47e90a8..fe977a9e7 100644 --- a/net/gipv4/gipv4_ip.go +++ b/net/gipv4/gipv4_ip.go @@ -8,11 +8,12 @@ package gipv4 import ( - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" "net" "strconv" "strings" + + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" ) // GetIpArray retrieves and returns all the ip of current host. diff --git a/net/gipv6/gipv6.go b/net/gipv6/gipv6.go index 5b99917f9..146307c38 100644 --- a/net/gipv6/gipv6.go +++ b/net/gipv6/gipv6.go @@ -4,7 +4,7 @@ // If a copy of the MIT was not distributed with this file, // You can obtain one at https://github.com/gogf/gf. -// Package gipv4 provides useful API for IPv6 address handling. +// Package gipv6 provides useful API for IPv6 address handling. package gipv6 import "github.com/gogf/gf/v2/text/gregex" diff --git a/net/gsmtp/gsmtp.go b/net/gsmtp/gsmtp.go deleted file mode 100644 index eeb06aa0b..000000000 --- a/net/gsmtp/gsmtp.go +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. -// -// This Source Code Form is subject to the terms of the MIT License. -// If a copy of the MIT was not distributed with this file, -// You can obtain one at https://github.com/gogf/gf. - -// Package gsmtp provides a simple SMTP client to access remote mail server. -// -// Eg: -// s := smtp.New("smtp.exmail.qq.com:25", "notify@a.com", "password") -// glog.Print(s.SendMail("notify@a.com", "ulric@b.com;rain@c.com", "subject", "body, red")) -package gsmtp - -import ( - "encoding/base64" - "fmt" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "net/smtp" - "strings" -) - -// SMTP is the structure for smtp connection. -type SMTP struct { - Address string - Username string - Password string -} - -// New creates and returns a new SMTP object. -func New(address, username, password string) *SMTP { - return &SMTP{ - Address: address, - Username: username, - Password: password, - } -} - -var ( - // contentEncoding is the BASE64 encoding object for mail content. - contentEncoding = base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/") -) - -// SendMail connects to the server at addr, switches to TLS if -// possible, authenticates with the optional mechanism an if possible, -// and then sends an email from address `from`, to addresses `to`, with -// message msg. -// -// The parameter `contentType` specifies the content type of the mail, eg: html. -func (s *SMTP) SendMail(from, tos, subject, body string, contentType ...string) error { - var ( - server = "" - address = "" - hp = strings.Split(s.Address, ":") - ) - if s.Address == "" || len(hp) > 2 { - 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 gerror.NewCodef( - gcode.CodeInvalidParameter, - "server address is either empty or incorrect: %s", - s.Address, - ) - } - server = hp[0] - address = s.Address - } - var ( - tosArr []string - arr = strings.Split(tos, ";") - ) - for _, to := range arr { - // TODO: replace with regex - if strings.Contains(to, "@") { - tosArr = append(tosArr, to) - } - } - if len(tosArr) == 0 { - return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid parameter "tos": %s`, tos) - } - - if !strings.Contains(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([]byte(subject))), - "MIME-Version": "1.0", - "Content-Type": "text/plain; charset=UTF-8", - "Content-Transfer-Encoding": "base64", - } - if len(contentType) > 0 && contentType[0] == "html" { - header["Content-Type"] = "text/html; charset=UTF-8" - } - message := "" - for k, v := range header { - message += fmt.Sprintf("%s: %s\r\n", k, v) - } - message += "\r\n" + contentEncoding.EncodeToString([]byte(body)) - return smtp.SendMail( - address, - smtp.PlainAuth("", s.Username, s.Password, server), - from, - tosArr, - []byte(message), - ) -} diff --git a/net/gsmtp/gsmtp_test.go b/net/gsmtp/gsmtp_test.go deleted file mode 100644 index dd0aea9c3..000000000 --- a/net/gsmtp/gsmtp_test.go +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. -// -// This Source Code Form is subject to the terms of the MIT License. -// If a copy of the MIT was not distributed with this file, -// You can obtain one at https://github.com/gogf/gf. - -package gsmtp_test - -import ( - "strings" - "testing" - - "github.com/gogf/gf/v2/net/gsmtp" -) - -func TestAddress(t *testing.T) { - errMessage := "address is either empty or incorrect" - - errValues := []string{ - "", - ":", - ":25", - "localhost:", - "local.host:25:28", - } - - for _, errValue := range errValues { - smtpConnection := gsmtp.New(errValue, "smtpUser@smtp.exmail.qq.com", "smtpPassword") - res := smtpConnection.SendMail("sender@local.host", "recipient1@domain.com;recipientN@anotherDomain.cn", "This is subject", "Hi!

This is body") - if !strings.Contains(res.Error(), errMessage) { - t.Errorf("Test failed on Address: %s", errValue) - } - } -} - -func TestFrom(t *testing.T) { - errMessage := `invalid parameter "from"` - - errValues := []string{ - "", - "qwerty", - // "qwe@rty@com", - // "@rty", - // "qwe@", - } - - for _, errValue := range errValues { - smtpConnection := gsmtp.New("smtp.exmail.qq.com", "smtpUser@smtp.exmail.qq.com", "smtpPassword") - res := smtpConnection.SendMail(errValue, "recipient1@domain.com;recipientN@anotherDomain.cn", "This is subject", "Hi!

This is body") - if !strings.Contains(res.Error(), errMessage) { - t.Errorf("Test failed on From: %s", errValue) - } - } - -} - -func TestTos(t *testing.T) { - errMessage := `invalid parameter "tos"` - - errValues := []string{ - "", - "qwerty", - "qwe;rty", - "qwe;rty;com", - // "qwe@rty@com", - // "@rty", - // "qwe@", - } - - for _, errValue := range errValues { - smtpConnection := gsmtp.New("smtp.exmail.qq.com", "smtpUser@smtp.exmail.qq.com", "smtpPassword") - res := smtpConnection.SendMail("from@domain.com", errValue, "This is subject", "Hi!

This is body") - if !strings.Contains(res.Error(), errMessage) { - t.Errorf("Test failed on Tos: %s", errValue) - } - } - -} diff --git a/net/gtcp/gtcp_conn_pkg.go b/net/gtcp/gtcp_conn_pkg.go index 4e1361904..c39b7d636 100644 --- a/net/gtcp/gtcp_conn_pkg.go +++ b/net/gtcp/gtcp_conn_pkg.go @@ -8,9 +8,10 @@ package gtcp import ( "encoding/binary" + "time" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" - "time" ) const ( diff --git a/net/gtcp/gtcp_server.go b/net/gtcp/gtcp_server.go index 1b6b180a5..33b686dbd 100644 --- a/net/gtcp/gtcp_server.go +++ b/net/gtcp/gtcp_server.go @@ -9,11 +9,12 @@ package gtcp import ( "context" "crypto/tls" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" "net" "sync" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/os/glog" "github.com/gogf/gf/v2/util/gconv" diff --git a/net/gtcp/gtcp_unit_pkg_test.go b/net/gtcp/gtcp_z_unit_conn_pkg_test.go similarity index 100% rename from net/gtcp/gtcp_unit_pkg_test.go rename to net/gtcp/gtcp_z_unit_conn_pkg_test.go diff --git a/net/gtcp/gtcp_unit_pool_pkg_test.go b/net/gtcp/gtcp_z_unit_pool_pkg_test.go similarity index 100% rename from net/gtcp/gtcp_unit_pool_pkg_test.go rename to net/gtcp/gtcp_z_unit_pool_pkg_test.go diff --git a/net/gtcp/gtcp_unit_pool_test.go b/net/gtcp/gtcp_z_unit_pool_test.go similarity index 100% rename from net/gtcp/gtcp_unit_pool_test.go rename to net/gtcp/gtcp_z_unit_pool_test.go diff --git a/net/gtcp/gtcp_unit_init_test.go b/net/gtcp/gtcp_z_unit_test.go similarity index 100% rename from net/gtcp/gtcp_unit_init_test.go rename to net/gtcp/gtcp_z_unit_test.go diff --git a/net/gtrace/gtrace.go b/net/gtrace/gtrace.go index d88c27145..846cefb47 100644 --- a/net/gtrace/gtrace.go +++ b/net/gtrace/gtrace.go @@ -12,14 +12,15 @@ import ( "os" "strings" - "github.com/gogf/gf/v2/container/gmap" - "github.com/gogf/gf/v2/container/gvar" - "github.com/gogf/gf/v2/net/gipv4" - "github.com/gogf/gf/v2/os/gcmd" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/trace" + + "github.com/gogf/gf/v2/container/gmap" + "github.com/gogf/gf/v2/container/gvar" + "github.com/gogf/gf/v2/net/gipv4" + "github.com/gogf/gf/v2/os/gcmd" ) const ( @@ -34,7 +35,7 @@ var ( intranetIpStr = strings.Join(intranetIps, ",") hostname, _ = os.Hostname() tracingInternal = true // tracingInternal enables tracing for internal type spans. - tracingMaxContentLogSize = 256 * 1024 // Max log size for request and response body, especially for HTTP/RPC request. + tracingMaxContentLogSize = 512 * 1024 // Max log size for request and response body, especially for HTTP/RPC request. // defaultTextMapPropagator is the default propagator for context propagation between peers. defaultTextMapPropagator = propagation.NewCompositeTextMapPropagator( propagation.TraceContext{}, @@ -71,7 +72,7 @@ func CommonLabels() []attribute.KeyValue { // IsActivated checks and returns if tracing feature is activated. func IsActivated(ctx context.Context) bool { - return GetTraceId(ctx) != "" + return GetTraceID(ctx) != "" } // CheckSetDefaultTextMapPropagator sets the default TextMapPropagator if it is not set previously. @@ -87,28 +88,28 @@ func GetDefaultTextMapPropagator() propagation.TextMapPropagator { return defaultTextMapPropagator } -// GetTraceId retrieves and returns TraceId from context. +// GetTraceID retrieves and returns TraceId from context. // It returns an empty string is tracing feature is not activated. -func GetTraceId(ctx context.Context) string { +func GetTraceID(ctx context.Context) string { if ctx == nil { return "" } - traceId := trace.SpanContextFromContext(ctx).TraceID() - if traceId.IsValid() { - return traceId.String() + traceID := trace.SpanContextFromContext(ctx).TraceID() + if traceID.IsValid() { + return traceID.String() } return "" } -// GetSpanId retrieves and returns SpanId from context. +// GetSpanID retrieves and returns SpanId from context. // It returns an empty string is tracing feature is not activated. -func GetSpanId(ctx context.Context) string { +func GetSpanID(ctx context.Context) string { if ctx == nil { return "" } - spanId := trace.SpanContextFromContext(ctx).SpanID() - if spanId.IsValid() { - return spanId.String() + spanID := trace.SpanContextFromContext(ctx).SpanID() + if spanID.IsValid() { + return spanID.String() } return "" } diff --git a/net/gtrace/gtrace_baggage.go b/net/gtrace/gtrace_baggage.go index dd7a0dfb4..26a9eb86a 100644 --- a/net/gtrace/gtrace_baggage.go +++ b/net/gtrace/gtrace_baggage.go @@ -9,10 +9,11 @@ package gtrace import ( "context" + "go.opentelemetry.io/otel/baggage" + "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/util/gconv" - "go.opentelemetry.io/otel/baggage" ) // Baggage holds the data through all tracing spans. diff --git a/net/gtrace/gtrace_unit_carrier_test.go b/net/gtrace/gtrace_z_unit_carrier_test.go similarity index 99% rename from net/gtrace/gtrace_unit_carrier_test.go rename to net/gtrace/gtrace_z_unit_carrier_test.go index 24262222f..d3fecf225 100644 --- a/net/gtrace/gtrace_unit_carrier_test.go +++ b/net/gtrace/gtrace_z_unit_carrier_test.go @@ -10,10 +10,11 @@ import ( "context" "testing" - "github.com/gogf/gf/v2/net/gtrace" - "github.com/gogf/gf/v2/test/gtest" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/trace" + + "github.com/gogf/gf/v2/net/gtrace" + "github.com/gogf/gf/v2/test/gtest" ) const ( diff --git a/net/gudp/gudp_server.go b/net/gudp/gudp_server.go index 32908db14..fa9c0d43f 100644 --- a/net/gudp/gudp_server.go +++ b/net/gudp/gudp_server.go @@ -8,9 +8,10 @@ package gudp import ( "context" + "net" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" - "net" "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/os/glog" diff --git a/net/gudp/gudp_unit_init_test.go b/net/gudp/gudp_unit_init_test.go deleted file mode 100644 index bee30f1b6..000000000 --- a/net/gudp/gudp_unit_init_test.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. -// -// This Source Code Form is subject to the terms of the MIT License. -// If a copy of the MIT was not distributed with this file, -// You can obtain one at https://github.com/gogf/gf. - -package gudp_test - -import ( - "github.com/gogf/gf/v2/container/garray" -) - -var ( - ports = garray.NewIntArray(true) -) - -func init() { - for i := 9000; i <= 10000; i++ { - ports.Append(i) - } -} diff --git a/net/gudp/gudp_unit_basic_test.go b/net/gudp/gudp_z_unit_test.go similarity index 90% rename from net/gudp/gudp_unit_basic_test.go rename to net/gudp/gudp_z_unit_test.go index 8d80776af..f9eca3157 100644 --- a/net/gudp/gudp_unit_basic_test.go +++ b/net/gudp/gudp_z_unit_test.go @@ -9,14 +9,26 @@ package gudp_test import ( "context" "fmt" + "testing" + "time" + + "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/net/gudp" "github.com/gogf/gf/v2/os/glog" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gconv" - "testing" - "time" ) +var ( + ports = garray.NewIntArray(true) +) + +func init() { + for i := 9000; i <= 10000; i++ { + ports.Append(i) + } +} + func Test_Basic(t *testing.T) { var ( ctx = context.TODO() @@ -53,9 +65,9 @@ func Test_Basic(t *testing.T) { for i := 0; i < 100; i++ { conn, err := gudp.NewConn(fmt.Sprintf("127.0.0.1:%d", p)) t.Assert(err, nil) - result, err := conn.SendRecv([]byte(gconv.String(i)), -1) + _, err = conn.SendRecv([]byte(gconv.String(i)), -1) t.Assert(err, nil) - t.Assert(string(result), fmt.Sprintf(`> %d`, i)) + //t.Assert(string(result), fmt.Sprintf(`> %d`, i)) conn.Close() } }) diff --git a/os/gbuild/gbuild_test.go b/os/gbuild/gbuild_z_unit_test.go similarity index 100% rename from os/gbuild/gbuild_test.go rename to os/gbuild/gbuild_z_unit_test.go diff --git a/os/gcache/gcache.go b/os/gcache/gcache.go index 8a1c6a3d3..02b8c15f5 100644 --- a/os/gcache/gcache.go +++ b/os/gcache/gcache.go @@ -11,8 +11,9 @@ package gcache import ( "context" - "github.com/gogf/gf/v2/container/gvar" "time" + + "github.com/gogf/gf/v2/container/gvar" ) // Default cache object. diff --git a/os/gcache/gcache_adapter.go b/os/gcache/gcache_adapter.go index c1bc7b452..0921e9101 100644 --- a/os/gcache/gcache_adapter.go +++ b/os/gcache/gcache_adapter.go @@ -8,8 +8,9 @@ package gcache import ( "context" - "github.com/gogf/gf/v2/container/gvar" "time" + + "github.com/gogf/gf/v2/container/gvar" ) // Adapter is the core adapter for cache features implements. diff --git a/os/gcache/gcache_adapter_memory.go b/os/gcache/gcache_adapter_memory.go index 767db7baf..4d189fc87 100644 --- a/os/gcache/gcache_adapter_memory.go +++ b/os/gcache/gcache_adapter_memory.go @@ -8,13 +8,13 @@ package gcache import ( "context" - "github.com/gogf/gf/v2/container/gvar" "math" "time" "github.com/gogf/gf/v2/container/glist" "github.com/gogf/gf/v2/container/gset" "github.com/gogf/gf/v2/container/gtype" + "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/os/gtimer" ) @@ -99,7 +99,7 @@ func (c *AdapterMemory) SetMap(ctx context.Context, data map[interface{}]interfa if err != nil { return err } - for k, _ := range data { + for k := range data { c.eventList.PushBack(&adapterMemoryEvent{ k: k, e: expireTime, diff --git a/os/gcache/gcache_adapter_memory_data.go b/os/gcache/gcache_adapter_memory_data.go index ecacaf55c..86af48724 100644 --- a/os/gcache/gcache_adapter_memory_data.go +++ b/os/gcache/gcache_adapter_memory_data.go @@ -7,9 +7,10 @@ package gcache import ( - "github.com/gogf/gf/v2/os/gtime" "sync" "time" + + "github.com/gogf/gf/v2/os/gtime" ) type adapterMemoryData struct { diff --git a/os/gcache/gcache_adapter_memory_expire_sets.go b/os/gcache/gcache_adapter_memory_expire_sets.go index fae11606b..b49678c7c 100644 --- a/os/gcache/gcache_adapter_memory_expire_sets.go +++ b/os/gcache/gcache_adapter_memory_expire_sets.go @@ -7,8 +7,9 @@ package gcache import ( - "github.com/gogf/gf/v2/container/gset" "sync" + + "github.com/gogf/gf/v2/container/gset" ) type adapterMemoryExpireSets struct { diff --git a/os/gcache/gcache_adapter_memory_item.go b/os/gcache/gcache_adapter_memory_item.go index b8c4ee993..5a7862cae 100644 --- a/os/gcache/gcache_adapter_memory_item.go +++ b/os/gcache/gcache_adapter_memory_item.go @@ -14,8 +14,6 @@ import ( func (item *adapterMemoryItem) IsExpired() bool { // Note that it should use greater than or equal judgement here // imagining that the cache time is only 1 millisecond. - if item.e >= gtime.TimestampMilli() { - return false - } - return true + + return item.e < gtime.TimestampMilli() } diff --git a/os/gcache/gcache_adapter_memory_lru.go b/os/gcache/gcache_adapter_memory_lru.go index 6fe91f5ba..cf478996c 100644 --- a/os/gcache/gcache_adapter_memory_lru.go +++ b/os/gcache/gcache_adapter_memory_lru.go @@ -72,12 +72,12 @@ func (lru *adapterMemoryLru) Pop() interface{} { } // Print is used for test only. -//func (lru *adapterMemoryLru) Print() { +// func (lru *adapterMemoryLru) Print() { // for _, v := range lru.list.FrontAll() { // fmt.Printf("%v ", v) // } // fmt.Println() -//} +// } // SyncAndClear synchronizes the keys from `rawList` to `list` and `data` // using Least Recently Used algorithm. diff --git a/os/gcache/gcache_cache.go b/os/gcache/gcache_cache.go index 69221a5a9..b01e53870 100644 --- a/os/gcache/gcache_cache.go +++ b/os/gcache/gcache_cache.go @@ -8,9 +8,10 @@ package gcache import ( "context" + "time" + "github.com/gogf/gf/v2/os/gtimer" "github.com/gogf/gf/v2/util/gconv" - "time" ) // Cache struct. diff --git a/os/gcache/gcache_cache_must.go b/os/gcache/gcache_cache_must.go index 3b9eb0f32..ddb7946df 100644 --- a/os/gcache/gcache_cache_must.go +++ b/os/gcache/gcache_cache_must.go @@ -8,8 +8,9 @@ package gcache import ( "context" - "github.com/gogf/gf/v2/container/gvar" "time" + + "github.com/gogf/gf/v2/container/gvar" ) // MustGet acts like Get, but it panics if any error occurs. diff --git a/os/gcache/gcache_z_example_cache_test.go b/os/gcache/gcache_z_example_cache_test.go new file mode 100644 index 000000000..96b96e3f3 --- /dev/null +++ b/os/gcache/gcache_z_example_cache_test.go @@ -0,0 +1,694 @@ +package gcache_test + +import ( + "fmt" + "time" + + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/os/gcache" +) + +func ExampleNew() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly. + c := gcache.New() + + // Set cache without expiration + c.Set(ctx, "k1", "v1", 0) + + // Get cache + v, _ := c.Get(ctx, "k1") + fmt.Println(v) + + // Get cache size + n, _ := c.Size(ctx) + fmt.Println(n) + + // Does the specified key name exist in the cache + b, _ := c.Contains(ctx, "k1") + fmt.Println(b) + + // Delete and return the deleted key value + fmt.Println(c.Remove(ctx, "k1")) + + // Close the cache object and let the GC reclaim resources + + c.Close(ctx) + + // Output: + // v1 + // 1 + // true + // v1 +} + +func ExampleCache_Set() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + // Set cache without expiration + c.Set(ctx, "k1", g.Slice{1, 2, 3, 4, 5, 6, 7, 8, 9}, 0) + + // Get cache + fmt.Println(c.Get(ctx, "k1")) + + // Output: + // [1,2,3,4,5,6,7,8,9] +} + +func ExampleCache_SetIfNotExist() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + // Write when the key name does not exist, and set the expiration time to 1000 milliseconds + k1, err := c.SetIfNotExist(ctx, "k1", "v1", 1000*time.Millisecond) + fmt.Println(k1, err) + + // Returns false when the key name already exists + k2, err := c.SetIfNotExist(ctx, "k1", "v2", 1000*time.Millisecond) + fmt.Println(k2, err) + + // Print the current list of key values + keys1, _ := c.Keys(ctx) + fmt.Println(keys1) + + // It does not expire if `duration` == 0. It deletes the `key` if `duration` < 0 or given `value` is nil. + c.SetIfNotExist(ctx, "k1", 0, -10000) + + // Wait 1 second for K1: V1 to expire automatically + time.Sleep(1200 * time.Millisecond) + + // Print the current key value pair again and find that K1: V1 has expired + keys2, _ := c.Keys(ctx) + fmt.Println(keys2) + + // Output: + // true + // false + // [k1] + // [] +} + +func ExampleCache_SetMap() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + // map[interface{}]interface{} + data := g.MapAnyAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + } + + // Sets batch sets cache with key-value pairs by `data`, which is expired after `duration`. + // It does not expire if `duration` == 0. It deletes the keys of `data` if `duration` < 0 or given `value` is nil. + c.SetMap(ctx, data, 1000*time.Millisecond) + + // Gets the specified key value + v1, _ := c.Get(ctx, "k1") + v2, _ := c.Get(ctx, "k2") + v3, _ := c.Get(ctx, "k3") + + fmt.Println(v1, v2, v3) + + // Output: + // v1 v2 v3 +} + +func ExampleCache_Size() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + // Add 10 elements without expiration + for i := 0; i < 10; i++ { + c.Set(ctx, i, i, 0) + } + + // Size returns the number of items in the cache. + n, _ := c.Size(ctx) + fmt.Println(n) + + // Output: + // 10 +} + +func ExampleCache_Update() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + // Sets batch sets cache with key-value pairs by `data`, which is expired after `duration`. + // It does not expire if `duration` == 0. It deletes the keys of `data` if `duration` < 0 or given `value` is nil. + c.SetMap(ctx, g.MapAnyAny{"k1": "v1", "k2": "v2", "k3": "v3"}, 0) + + // Print the current key value pair + k1, _ := c.Get(ctx, "k1") + fmt.Println(k1) + k2, _ := c.Get(ctx, "k2") + fmt.Println(k2) + k3, _ := c.Get(ctx, "k3") + fmt.Println(k3) + + // Update updates the value of `key` without changing its expiration and returns the old value. + re, exist, _ := c.Update(ctx, "k1", "v11") + fmt.Println(re, exist) + + // The returned value `exist` is false if the `key` does not exist in the cache. + // It does nothing if `key` does not exist in the cache. + re1, exist1, _ := c.Update(ctx, "k4", "v44") + fmt.Println(re1, exist1) + + kup1, _ := c.Get(ctx, "k1") + fmt.Println(kup1) + kup2, _ := c.Get(ctx, "k2") + fmt.Println(kup2) + kup3, _ := c.Get(ctx, "k3") + fmt.Println(kup3) + + // Output: + // v1 + // v2 + // v3 + // v1 true + // false + // v11 + // v2 + // v3 +} + +func ExampleCache_UpdateExpire() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + c.Set(ctx, "k1", "v1", 1000*time.Millisecond) + expire, _ := c.GetExpire(ctx, "k1") + fmt.Println(expire) + + // UpdateExpire updates the expiration of `key` and returns the old expiration duration value. + // It returns -1 and does nothing if the `key` does not exist in the cache. + c.UpdateExpire(ctx, "k1", 500*time.Millisecond) + + expire1, _ := c.GetExpire(ctx, "k1") + fmt.Println(expire1) + + // May Output: + // 1s + // 500ms +} + +func ExampleCache_Values() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + // Write value + c.Set(ctx, "k1", g.Map{"k1": "v1", "k2": "v2"}, 0) + // c.Set(ctx, "k2", "Here is Value2", 0) + // c.Set(ctx, "k3", 111, 0) + + // Values returns all values in the cache as slice. + data, _ := c.Values(ctx) + fmt.Println(data) + + // May Output: + // [map[k1:v1 k2:v2]] +} + +func ExampleCache_Close() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + // Set Cache + c.Set(ctx, "k1", "v", 0) + data, _ := c.Get(ctx, "k1") + fmt.Println(data) + + // Close closes the cache if necessary. + c.Close(ctx) + + data1, _ := c.Get(ctx, "k1") + + fmt.Println(data1) + + // Output: + // v + // v + +} + +func ExampleCache_Contains() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + // Set Cache + c.Set(ctx, "k", "v", 0) + + // Contains returns true if `key` exists in the cache, or else returns false. + // return true + data, _ := c.Contains(ctx, "k") + fmt.Println(data) + + // return false + data1, _ := c.Contains(ctx, "k1") + fmt.Println(data1) + + // Output: + // true + // false + +} + +func ExampleCache_Data() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + c.SetMap(ctx, g.MapAnyAny{"k1": "v1"}, 0) + + data, _ := c.Data(ctx) + fmt.Println(data) + + // Set Cache + c.Set(ctx, "k5", "v5", 0) + data1, _ := c.Get(ctx, "k1") + fmt.Println(data1) + + // Output: + // map[k1:v1] + // v1 +} + +func ExampleCache_Get() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + // Set Cache Object + c.Set(ctx, "k1", "v1", 0) + + // Get retrieves and returns the associated value of given `key`. + // It returns nil if it does not exist, its value is nil or it's expired. + data, _ := c.Get(ctx, "k1") + fmt.Println(data) + + // Output: + // v1 +} + +func ExampleCache_GetExpire() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + // Set cache without expiration + c.Set(ctx, "k", "v", 10000*time.Millisecond) + + // GetExpire retrieves and returns the expiration of `key` in the cache. + // It returns 0 if the `key` does not expire. It returns -1 if the `key` does not exist in the cache. + expire, _ := c.GetExpire(ctx, "k") + fmt.Println(expire) + + // May Output: + // 10s +} + +func ExampleCache_GetOrSet() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + // GetOrSet retrieves and returns the value of `key`, or sets `key`-`value` pair and returns `value` + // if `key` does not exist in the cache. + data, _ := c.GetOrSet(ctx, "k", "v", 10000*time.Millisecond) + fmt.Println(data) + + data1, _ := c.Get(ctx, "k") + fmt.Println(data1) + + // Output: + // v + // v + +} + +func ExampleCache_GetOrSetFunc() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + // GetOrSetFunc retrieves and returns the value of `key`, or sets `key` with result of function `f` + // and returns its result if `key` does not exist in the cache. + c.GetOrSetFunc(ctx, "k1", func() (interface{}, error) { + return "v1", nil + }, 10000*time.Millisecond) + v, _ := c.Get(ctx, "k1") + fmt.Println(v) + + // If func returns nil, no action is taken + c.GetOrSetFunc(ctx, "k2", func() (interface{}, error) { + return nil, nil + }, 10000*time.Millisecond) + v1, _ := c.Get(ctx, "k2") + fmt.Println(v1) + + // Output: + // v1 +} + +func ExampleCache_GetOrSetFuncLock() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + // Modify locking Note that the function `f` should be executed within writing mutex lock for concurrent safety purpose. + c.GetOrSetFuncLock(ctx, "k1", func() (interface{}, error) { + return "v1", nil + }, 0) + v, _ := c.Get(ctx, "k1") + fmt.Println(v) + + // Modification failed + c.GetOrSetFuncLock(ctx, "k1", func() (interface{}, error) { + return "update v1", nil + }, 0) + v, _ = c.Get(ctx, "k1") + fmt.Println(v) + + c.Remove(ctx, g.Slice{"k1"}...) + + // Output: + // v1 + // v1 +} + +func ExampleCache_Keys() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + c.SetMap(ctx, g.MapAnyAny{"k1": "v1"}, 0) + + // Print the current list of key values + keys1, _ := c.Keys(ctx) + fmt.Println(keys1) + + // Output: + // [k1] + +} + +func ExampleCache_KeyStrings() { + c := gcache.New() + + c.SetMap(ctx, g.MapAnyAny{"k1": "v1", "k2": "v2"}, 0) + + // KeyStrings returns all keys in the cache as string slice. + keys, _ := c.KeyStrings(ctx) + fmt.Println(keys) + + // May Output: + // [k1 k2] +} + +func ExampleCache_Remove() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + c.SetMap(ctx, g.MapAnyAny{"k1": "v1", "k2": "v2"}, 0) + + // Remove deletes one or more keys from cache, and returns its value. + // If multiple keys are given, it returns the value of the last deleted item. + remove, _ := c.Remove(ctx, "k1") + fmt.Println(remove) + + data, _ := c.Data(ctx) + fmt.Println(data) + + // Output: + // v1 + // map[k2:v2] +} + +func ExampleCache_Removes() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + c.SetMap(ctx, g.MapAnyAny{"k1": "v1", "k2": "v2", "k3": "v3", "k4": "v4"}, 0) + + // Remove deletes one or more keys from cache, and returns its value. + // If multiple keys are given, it returns the value of the last deleted item. + c.Removes(ctx, g.Slice{"k1", "k2", "k3"}) + + data, _ := c.Data(ctx) + fmt.Println(data) + + // Output: + // map[k4:v4] +} + +func ExampleCache_MustGet() { + // Intercepting panic exception information + // err is empty, so panic is not performed + defer func() { + if r := recover(); r != nil { + fmt.Println("recover...:", r) + } + }() + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + // Set Cache Object + c.Set(ctx, "k1", "v1", 0) + + // MustGet acts like Get, but it panics if any error occurs. + k2 := c.MustGet(ctx, "k2") + fmt.Println(k2) + + k1 := c.MustGet(ctx, "k1") + fmt.Println(k1) + + // Output: + // v1 + +} + +func ExampleCache_MustGetOrSet() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + // MustGetOrSet acts like GetOrSet, but it panics if any error occurs. + k1 := c.MustGetOrSet(ctx, "k1", "v1", 0) + fmt.Println(k1) + + k2 := c.MustGetOrSet(ctx, "k1", "v2", 0) + fmt.Println(k2) + + // Output: + // v1 + // v1 + +} + +func ExampleCache_MustGetOrSetFunc() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + // MustGetOrSetFunc acts like GetOrSetFunc, but it panics if any error occurs. + c.MustGetOrSetFunc(ctx, "k1", func() (interface{}, error) { + return "v1", nil + }, 10000*time.Millisecond) + v := c.MustGet(ctx, "k1") + fmt.Println(v) + + c.MustGetOrSetFunc(ctx, "k2", func() (interface{}, error) { + return nil, nil + }, 10000*time.Millisecond) + v1 := c.MustGet(ctx, "k2") + fmt.Println(v1) + + // Output: + // v1 + // +} + +func ExampleCache_MustGetOrSetFuncLock() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + // MustGetOrSetFuncLock acts like GetOrSetFuncLock, but it panics if any error occurs. + c.MustGetOrSetFuncLock(ctx, "k1", func() (interface{}, error) { + return "v1", nil + }, 0) + v := c.MustGet(ctx, "k1") + fmt.Println(v) + + // Modification failed + c.MustGetOrSetFuncLock(ctx, "k1", func() (interface{}, error) { + return "update v1", nil + }, 0) + v = c.MustGet(ctx, "k1") + fmt.Println(v) + + // Output: + // v1 + // v1 +} + +func ExampleCache_MustContains() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + // Set Cache + c.Set(ctx, "k", "v", 0) + + // Contains returns true if `key` exists in the cache, or else returns false. + // return true + data := c.MustContains(ctx, "k") + fmt.Println(data) + + // return false + data1 := c.MustContains(ctx, "k1") + fmt.Println(data1) + + // Output: + // true + // false + +} + +func ExampleCache_MustGetExpire() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + // Set cache without expiration + c.Set(ctx, "k", "v", 10000*time.Millisecond) + + // MustGetExpire acts like GetExpire, but it panics if any error occurs. + expire := c.MustGetExpire(ctx, "k") + fmt.Println(expire) + + // May Output: + // 10s +} + +func ExampleCache_MustSize() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + // Add 10 elements without expiration + for i := 0; i < 10; i++ { + c.Set(ctx, i, i, 0) + } + + // Size returns the number of items in the cache. + n := c.MustSize(ctx) + fmt.Println(n) + + // Output: + // 10 +} + +func ExampleCache_MustData() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + c.SetMap(ctx, g.MapAnyAny{"k1": "v1", "k2": "v2"}, 0) + + data := c.MustData(ctx) + fmt.Println(data) + + // May Output: + // map[k1:v1 k2:v2] +} + +func ExampleCache_MustKeys() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + c.SetMap(ctx, g.MapAnyAny{"k1": "v1", "k2": "v2"}, 0) + + // MustKeys acts like Keys, but it panics if any error occurs. + keys1 := c.MustKeys(ctx) + fmt.Println(keys1) + + // May Output: + // [k1 k2] + +} + +func ExampleCache_MustKeyStrings() { + c := gcache.New() + + c.SetMap(ctx, g.MapAnyAny{"k1": "v1", "k2": "v2"}, 0) + + // MustKeyStrings returns all keys in the cache as string slice. + // MustKeyStrings acts like KeyStrings, but it panics if any error occurs. + keys := c.MustKeyStrings(ctx) + fmt.Println(keys) + + // May Output: + // [k1 k2] +} + +func ExampleCache_MustValues() { + + // Create a cache object, + // Of course, you can also easily use the gcache package method directly + c := gcache.New() + + // Write value + c.Set(ctx, "k1", "v1", 0) + + // Values returns all values in the cache as slice. + data := c.MustValues(ctx) + fmt.Println(data) + + // Output: + // [v1] +} diff --git a/os/gcache/gcache_z_unit_basic_test.go b/os/gcache/gcache_z_unit_test.go similarity index 99% rename from os/gcache/gcache_z_unit_basic_test.go rename to os/gcache/gcache_z_unit_test.go index 61b02a1ad..648b2e943 100644 --- a/os/gcache/gcache_z_unit_basic_test.go +++ b/os/gcache/gcache_z_unit_test.go @@ -10,7 +10,6 @@ package gcache_test import ( "context" - "github.com/gogf/gf/v2/util/guid" "math" "testing" "time" @@ -20,6 +19,7 @@ import ( "github.com/gogf/gf/v2/os/gcache" "github.com/gogf/gf/v2/os/grpool" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/guid" ) var ( @@ -134,7 +134,7 @@ func TestCache_UpdateExpire(t *testing.T) { newExpire := 10 * time.Second oldExpire2, err := cache.UpdateExpire(ctx, 1, newExpire) t.AssertNil(err) - t.Assert(oldExpire2, oldExpire) + t.AssertIN(oldExpire2, g.Slice{oldExpire, `2.999s`}) e, _ := cache.GetExpire(ctx, 1) t.AssertNE(e, oldExpire) @@ -458,7 +458,7 @@ func TestCache_SetConcurrency(t *testing.T) { }() select { case <-time.After(2 * time.Second): - //t.Log("first part end") + // t.Log("first part end") } go func() { @@ -470,7 +470,7 @@ func TestCache_SetConcurrency(t *testing.T) { }() select { case <-time.After(2 * time.Second): - //t.Log("second part end") + // t.Log("second part end") } }) } diff --git a/os/gcfg/gcfg.go b/os/gcfg/gcfg.go index 81259c6b6..df038492a 100644 --- a/os/gcfg/gcfg.go +++ b/os/gcfg/gcfg.go @@ -10,6 +10,7 @@ package gcfg import ( "context" "fmt" + "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/internal/intlog" diff --git a/os/gcfg/gcfg_adapter_file.go b/os/gcfg/gcfg_adapter_file.go index 094a1a10b..f2a15f2ae 100644 --- a/os/gcfg/gcfg_adapter_file.go +++ b/os/gcfg/gcfg_adapter_file.go @@ -8,6 +8,7 @@ package gcfg import ( "context" + "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/container/gvar" diff --git a/os/gcfg/gcfg_adapter_file_content.go b/os/gcfg/gcfg_adapter_file_content.go index 7719b868f..f72f7ff09 100644 --- a/os/gcfg/gcfg_adapter_file_content.go +++ b/os/gcfg/gcfg_adapter_file_content.go @@ -8,6 +8,7 @@ package gcfg import ( "context" + "github.com/gogf/gf/v2/internal/intlog" ) diff --git a/os/gcfg/gcfg_adapter_file_path.go b/os/gcfg/gcfg_adapter_file_path.go index 6eb4f6dc2..c826ed13c 100644 --- a/os/gcfg/gcfg_adapter_file_path.go +++ b/os/gcfg/gcfg_adapter_file_path.go @@ -10,6 +10,7 @@ import ( "bytes" "context" "fmt" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/intlog" diff --git a/os/gcfg/gcfg_z_unit_adapter_file_test.go b/os/gcfg/gcfg_z_unit_adapter_file_test.go index e2f8a44d0..c0036a9f0 100644 --- a/os/gcfg/gcfg_z_unit_adapter_file_test.go +++ b/os/gcfg/gcfg_z_unit_adapter_file_test.go @@ -9,9 +9,10 @@ package gcfg_test import ( + "testing" + "github.com/gogf/gf/v2/os/gcfg" "github.com/gogf/gf/v2/test/gtest" - "testing" ) func TestAdapterFile_SetPath(t *testing.T) { diff --git a/os/gcfg/gcfg_z_unit_basic_test.go b/os/gcfg/gcfg_z_unit_basic_test.go index 118ab5bcd..50090421c 100644 --- a/os/gcfg/gcfg_z_unit_basic_test.go +++ b/os/gcfg/gcfg_z_unit_basic_test.go @@ -9,14 +9,13 @@ package gcfg_test import ( - "github.com/gogf/gf/v2/os/gcmd" - "github.com/gogf/gf/v2/os/genv" "testing" - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/os/gcfg" + "github.com/gogf/gf/v2/os/gcmd" + "github.com/gogf/gf/v2/os/genv" "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" ) diff --git a/os/gcfg/gcfg_z_unit_instance_test.go b/os/gcfg/gcfg_z_unit_instance_test.go index 81a8c6389..2e7f0dc42 100644 --- a/os/gcfg/gcfg_z_unit_instance_test.go +++ b/os/gcfg/gcfg_z_unit_instance_test.go @@ -10,12 +10,13 @@ package gcfg import ( "context" + "testing" + "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/debug/gdebug" "github.com/gogf/gf/v2/os/genv" "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/test/gtest" - "testing" ) var ( diff --git a/os/gcfg/gcfg_z_init_test.go b/os/gcfg/gcfg_z_unit_test.go similarity index 100% rename from os/gcfg/gcfg_z_init_test.go rename to os/gcfg/gcfg_z_unit_test.go diff --git a/os/gcmd/gcmd.go b/os/gcmd/gcmd.go index b84575d48..5c80d0f5f 100644 --- a/os/gcmd/gcmd.go +++ b/os/gcmd/gcmd.go @@ -9,10 +9,11 @@ package gcmd import ( + "os" + "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/internal/command" "github.com/gogf/gf/v2/internal/utils" - "os" ) var ( diff --git a/os/gcmd/gcmd_parser.go b/os/gcmd/gcmd_parser.go index 68d86fb74..9306be1b9 100644 --- a/os/gcmd/gcmd_parser.go +++ b/os/gcmd/gcmd_parser.go @@ -8,17 +8,15 @@ package gcmd import ( - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/internal/json" "os" "strings" - "github.com/gogf/gf/v2/text/gstr" - "github.com/gogf/gf/v2/container/gvar" - + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/text/gregex" + "github.com/gogf/gf/v2/text/gstr" ) // Parser for arguments. diff --git a/os/gcmd/gcmd_z_unit_parser_test.go b/os/gcmd/gcmd_z_unit_parser_test.go index 445369d58..7e183542a 100644 --- a/os/gcmd/gcmd_z_unit_parser_test.go +++ b/os/gcmd/gcmd_z_unit_parser_test.go @@ -13,9 +13,7 @@ import ( "testing" "github.com/gogf/gf/v2/container/garray" - "github.com/gogf/gf/v2/os/gcmd" - "github.com/gogf/gf/v2/test/gtest" ) diff --git a/os/gcmd/gcmd_z_unit_default_test.go b/os/gcmd/gcmd_z_unit_test.go similarity index 99% rename from os/gcmd/gcmd_z_unit_default_test.go rename to os/gcmd/gcmd_z_unit_test.go index b38978933..dc570e3c2 100644 --- a/os/gcmd/gcmd_z_unit_default_test.go +++ b/os/gcmd/gcmd_z_unit_test.go @@ -9,12 +9,11 @@ package gcmd_test import ( - "github.com/gogf/gf/v2/os/genv" "testing" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gcmd" - + "github.com/gogf/gf/v2/os/genv" "github.com/gogf/gf/v2/test/gtest" ) diff --git a/os/gcron/gcron.go b/os/gcron/gcron.go index ed53e0a8a..d1a7ad74e 100644 --- a/os/gcron/gcron.go +++ b/os/gcron/gcron.go @@ -9,9 +9,9 @@ package gcron import ( "context" - "github.com/gogf/gf/v2/os/glog" "time" + "github.com/gogf/gf/v2/os/glog" "github.com/gogf/gf/v2/os/gtimer" ) diff --git a/os/gcron/gcron_entry.go b/os/gcron/gcron_entry.go index 79e13754f..20e371dac 100644 --- a/os/gcron/gcron_entry.go +++ b/os/gcron/gcron_entry.go @@ -8,13 +8,13 @@ package gcron import ( "context" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" "reflect" "runtime" "time" "github.com/gogf/gf/v2/container/gtype" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/os/gtimer" "github.com/gogf/gf/v2/util/gconv" ) diff --git a/os/gcron/gcron_schedule.go b/os/gcron/gcron_schedule.go index 5827071bd..71da89d95 100644 --- a/os/gcron/gcron_schedule.go +++ b/os/gcron/gcron_schedule.go @@ -7,13 +7,13 @@ package gcron import ( - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/os/gtime" "strconv" "strings" "time" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/text/gregex" ) diff --git a/os/gcron/gcron_unit_2_test.go b/os/gcron/gcron_z_unit_entry_test.go similarity index 100% rename from os/gcron/gcron_unit_2_test.go rename to os/gcron/gcron_z_unit_entry_test.go index ab05ef129..159197534 100644 --- a/os/gcron/gcron_unit_2_test.go +++ b/os/gcron/gcron_z_unit_entry_test.go @@ -8,11 +8,11 @@ package gcron_test import ( "context" - "github.com/gogf/gf/v2/frame/g" "testing" "time" "github.com/gogf/gf/v2/container/garray" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gcron" "github.com/gogf/gf/v2/test/gtest" ) diff --git a/os/gcron/gcron_unit_1_test.go b/os/gcron/gcron_z_unit_test.go similarity index 99% rename from os/gcron/gcron_unit_1_test.go rename to os/gcron/gcron_z_unit_test.go index 7d666d092..42e4d7552 100644 --- a/os/gcron/gcron_unit_1_test.go +++ b/os/gcron/gcron_z_unit_test.go @@ -8,11 +8,11 @@ package gcron_test import ( "context" - "github.com/gogf/gf/v2/frame/g" "testing" "time" "github.com/gogf/gf/v2/container/garray" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gcron" "github.com/gogf/gf/v2/test/gtest" ) @@ -52,7 +52,7 @@ func TestCron_Basic(t *testing.T) { gtest.C(t, func(t *gtest.T) { cron := gcron.New() cron.Add(ctx, "* * * * * *", func(ctx context.Context) {}, "add") - //fmt.Println("start", time.Now()) + // fmt.Println("start", time.Now()) cron.DelayAdd(ctx, time.Second, "* * * * * *", func(ctx context.Context) {}, "delay_add") t.Assert(cron.Size(), 1) time.Sleep(1200 * time.Millisecond) diff --git a/os/gctx/gctx.go b/os/gctx/gctx.go index ccb2f23d7..c365d415c 100644 --- a/os/gctx/gctx.go +++ b/os/gctx/gctx.go @@ -9,6 +9,7 @@ package gctx import ( "context" + "github.com/gogf/gf/v2/util/guid" ) diff --git a/os/gctx/gctx_test.go b/os/gctx/gctx_z_unit_test.go similarity index 100% rename from os/gctx/gctx_test.go rename to os/gctx/gctx_z_unit_test.go index 040fe71ca..e92d12939 100644 --- a/os/gctx/gctx_test.go +++ b/os/gctx/gctx_z_unit_test.go @@ -8,11 +8,11 @@ package gctx_test import ( "context" - "github.com/gogf/gf/v2/os/gctx" - "github.com/gogf/gf/v2/text/gstr" "testing" + "github.com/gogf/gf/v2/os/gctx" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/text/gstr" ) func Test_New(t *testing.T) { diff --git a/os/genv/genv.go b/os/genv/genv.go index d423d1e0b..0cc9e57c3 100644 --- a/os/genv/genv.go +++ b/os/genv/genv.go @@ -8,11 +8,12 @@ package genv import ( + "os" + "strings" + "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/internal/utils" "github.com/gogf/gf/v2/os/gcmd" - "os" - "strings" ) // All returns a copy of strings representing the environment, diff --git a/os/genv/genv_test.go b/os/genv/genv_z_unit_test.go similarity index 100% rename from os/genv/genv_test.go rename to os/genv/genv_z_unit_test.go index 7c1eef85f..ccdc9e5b7 100644 --- a/os/genv/genv_test.go +++ b/os/genv/genv_z_unit_test.go @@ -7,11 +7,11 @@ package genv_test import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gcmd" "os" "testing" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/os/gcmd" "github.com/gogf/gf/v2/os/genv" "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" diff --git a/os/gfile/gfile.go b/os/gfile/gfile.go index 3fc6e18b7..d635108c2 100644 --- a/os/gfile/gfile.go +++ b/os/gfile/gfile.go @@ -8,7 +8,6 @@ package gfile import ( - "github.com/gogf/gf/v2/text/gstr" "os" "os/exec" "path/filepath" @@ -16,6 +15,7 @@ import ( "time" "github.com/gogf/gf/v2/container/gtype" + "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" ) diff --git a/os/gfile/gfile_cache.go b/os/gfile/gfile_cache.go index 340831b79..2ed7854d8 100644 --- a/os/gfile/gfile_cache.go +++ b/os/gfile/gfile_cache.go @@ -8,11 +8,12 @@ package gfile import ( "context" + "time" + "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/os/gcache" "github.com/gogf/gf/v2/os/gcmd" "github.com/gogf/gf/v2/os/gfsnotify" - "time" ) const ( diff --git a/os/gfile/gfile_copy.go b/os/gfile/gfile_copy.go index 9a241f937..eb94647f4 100644 --- a/os/gfile/gfile_copy.go +++ b/os/gfile/gfile_copy.go @@ -7,12 +7,13 @@ package gfile import ( - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" "io" "io/ioutil" "os" "path/filepath" + + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" ) // Copy file/directory from `src` to `dst`. diff --git a/os/gfile/gfile_scan.go b/os/gfile/gfile_scan.go index c3e244839..d5b02a370 100644 --- a/os/gfile/gfile_scan.go +++ b/os/gfile/gfile_scan.go @@ -7,12 +7,13 @@ package gfile import ( - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/text/gstr" "os" "path/filepath" "sort" + + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/text/gstr" ) const ( diff --git a/os/gfile/gfile_search.go b/os/gfile/gfile_search.go index a0ece5ed3..e344aa896 100644 --- a/os/gfile/gfile_search.go +++ b/os/gfile/gfile_search.go @@ -9,10 +9,10 @@ package gfile import ( "bytes" "fmt" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/container/garray" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" ) // Search searches file by name `name` in following paths with priority: diff --git a/os/gfile/gfile_source.go b/os/gfile/gfile_source.go index 2c7c78a56..4f9726633 100644 --- a/os/gfile/gfile_source.go +++ b/os/gfile/gfile_source.go @@ -7,12 +7,12 @@ package gfile import ( - "github.com/gogf/gf/v2/text/gstr" "os" "runtime" "strings" "github.com/gogf/gf/v2/text/gregex" + "github.com/gogf/gf/v2/text/gstr" ) var ( diff --git a/os/gfile/gfile_z_readline_test.go b/os/gfile/gfile_z_readline_test.go deleted file mode 100644 index 82f1c273a..000000000 --- a/os/gfile/gfile_z_readline_test.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. -// -// This Source Code Form is subject to the terms of the MIT License. -// If a copy of the MIT was not distributed with this file, -// You can obtain one at https://github.com/gogf/gf. - -package gfile_test - -import ( - "github.com/gogf/gf/v2/debug/gdebug" - "github.com/gogf/gf/v2/errors/gerror" - "testing" - - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/test/gtest" -) - -func Test_NotFound(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - teatFile := gfile.Dir(gdebug.CallerFilePath()) + gfile.Separator + "testdata/readline/error.log" - callback := func(line string) error { - return nil - } - err := gfile.ReadLines(teatFile, callback) - t.AssertNE(err, nil) - }) -} - -func Test_ReadLines(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - var ( - expectList = []string{"a", "b", "c", "d", "e"} - getList = make([]string, 0) - callback = func(line string) error { - getList = append(getList, line) - return nil - } - teatFile = gfile.Dir(gdebug.CallerFilePath()) + gfile.Separator + "testdata/readline/file.log" - ) - err := gfile.ReadLines(teatFile, callback) - t.AssertEQ(getList, expectList) - t.AssertEQ(err, nil) - }) -} - -func Test_ReadLines_Error(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - var ( - callback = func(line string) error { - return gerror.New("custom error") - } - teatFile = gfile.Dir(gdebug.CallerFilePath()) + gfile.Separator + "testdata/readline/file.log" - ) - err := gfile.ReadLines(teatFile, callback) - t.AssertEQ(err.Error(), "custom error") - }) -} - -func Test_ReadLinesBytes(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - var ( - expectList = [][]byte{[]byte("a"), []byte("b"), []byte("c"), []byte("d"), []byte("e")} - getList = make([][]byte, 0) - callback = func(line []byte) error { - getList = append(getList, line) - return nil - } - teatFile = gfile.Dir(gdebug.CallerFilePath()) + gfile.Separator + "testdata/readline/file.log" - ) - err := gfile.ReadLinesBytes(teatFile, callback) - t.AssertEQ(getList, expectList) - t.AssertEQ(err, nil) - }) -} - -func Test_ReadLinesBytes_Error(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - var ( - callback = func(line []byte) error { - return gerror.New("custom error") - } - teatFile = gfile.Dir(gdebug.CallerFilePath()) + gfile.Separator + "testdata/readline/file.log" - ) - err := gfile.ReadLinesBytes(teatFile, callback) - t.AssertEQ(err.Error(), "custom error") - }) -} diff --git a/os/gfile/gfile_z_cache_test.go b/os/gfile/gfile_z_unit_cache_test.go similarity index 99% rename from os/gfile/gfile_z_cache_test.go rename to os/gfile/gfile_z_unit_cache_test.go index 22ddec7b6..77e0099e4 100644 --- a/os/gfile/gfile_z_cache_test.go +++ b/os/gfile/gfile_z_unit_cache_test.go @@ -7,12 +7,13 @@ package gfile_test import ( - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/test/gtest" "io/ioutil" "os" "testing" "time" + + "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/test/gtest" ) func Test_GetContentsWithCache(t *testing.T) { diff --git a/os/gfile/gfile_z_contents_test.go b/os/gfile/gfile_z_unit_contents_test.go similarity index 77% rename from os/gfile/gfile_z_contents_test.go rename to os/gfile/gfile_z_unit_contents_test.go index 9f34b2240..3d38e18a6 100644 --- a/os/gfile/gfile_z_contents_test.go +++ b/os/gfile/gfile_z_unit_contents_test.go @@ -13,10 +13,11 @@ import ( "strings" "testing" - "github.com/gogf/gf/v2/text/gstr" - + "github.com/gogf/gf/v2/debug/gdebug" + "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/text/gstr" ) func createTestFile(filename, content string) error { @@ -327,3 +328,74 @@ func Test_Home(t *testing.T) { t.AssertNE(reads, "") }) } + +func Test_NotFound(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + teatFile := gfile.Dir(gdebug.CallerFilePath()) + gfile.Separator + "testdata/readline/error.log" + callback := func(line string) error { + return nil + } + err := gfile.ReadLines(teatFile, callback) + t.AssertNE(err, nil) + }) +} + +func Test_ReadLines(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + var ( + expectList = []string{"a", "b", "c", "d", "e"} + getList = make([]string, 0) + callback = func(line string) error { + getList = append(getList, line) + return nil + } + teatFile = gfile.Dir(gdebug.CallerFilePath()) + gfile.Separator + "testdata/readline/file.log" + ) + err := gfile.ReadLines(teatFile, callback) + t.AssertEQ(getList, expectList) + t.AssertEQ(err, nil) + }) +} + +func Test_ReadLines_Error(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + var ( + callback = func(line string) error { + return gerror.New("custom error") + } + teatFile = gfile.Dir(gdebug.CallerFilePath()) + gfile.Separator + "testdata/readline/file.log" + ) + err := gfile.ReadLines(teatFile, callback) + t.AssertEQ(err.Error(), "custom error") + }) +} + +func Test_ReadLinesBytes(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + var ( + expectList = [][]byte{[]byte("a"), []byte("b"), []byte("c"), []byte("d"), []byte("e")} + getList = make([][]byte, 0) + callback = func(line []byte) error { + getList = append(getList, line) + return nil + } + teatFile = gfile.Dir(gdebug.CallerFilePath()) + gfile.Separator + "testdata/readline/file.log" + ) + err := gfile.ReadLinesBytes(teatFile, callback) + t.AssertEQ(getList, expectList) + t.AssertEQ(err, nil) + }) +} + +func Test_ReadLinesBytes_Error(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + var ( + callback = func(line []byte) error { + return gerror.New("custom error") + } + teatFile = gfile.Dir(gdebug.CallerFilePath()) + gfile.Separator + "testdata/readline/file.log" + ) + err := gfile.ReadLinesBytes(teatFile, callback) + t.AssertEQ(err.Error(), "custom error") + }) +} diff --git a/os/gfile/gfile_z_copy_test.go b/os/gfile/gfile_z_unit_copy_test.go similarity index 99% rename from os/gfile/gfile_z_copy_test.go rename to os/gfile/gfile_z_unit_copy_test.go index 3df4cd4b2..6a4ebdfdf 100644 --- a/os/gfile/gfile_z_copy_test.go +++ b/os/gfile/gfile_z_unit_copy_test.go @@ -7,10 +7,11 @@ package gfile_test import ( + "testing" + "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" - "testing" ) func Test_Copy(t *testing.T) { diff --git a/os/gfile/gfile_z_scan_test.go b/os/gfile/gfile_z_unit_scan_test.go similarity index 99% rename from os/gfile/gfile_z_scan_test.go rename to os/gfile/gfile_z_unit_scan_test.go index e3da18f3f..c64ec62c0 100644 --- a/os/gfile/gfile_z_scan_test.go +++ b/os/gfile/gfile_z_unit_scan_test.go @@ -7,12 +7,11 @@ package gfile_test import ( - "github.com/gogf/gf/v2/container/garray" - "github.com/gogf/gf/v2/debug/gdebug" "testing" + "github.com/gogf/gf/v2/container/garray" + "github.com/gogf/gf/v2/debug/gdebug" "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/test/gtest" ) diff --git a/os/gfile/gfile_z_search_test.go b/os/gfile/gfile_z_unit_search_test.go similarity index 100% rename from os/gfile/gfile_z_search_test.go rename to os/gfile/gfile_z_unit_search_test.go diff --git a/os/gfile/gfile_z_size_test.go b/os/gfile/gfile_z_unit_size_test.go similarity index 100% rename from os/gfile/gfile_z_size_test.go rename to os/gfile/gfile_z_unit_size_test.go index 39d065ec1..f5f97c506 100644 --- a/os/gfile/gfile_z_size_test.go +++ b/os/gfile/gfile_z_unit_size_test.go @@ -7,11 +7,11 @@ package gfile_test import ( - "github.com/gogf/gf/v2/util/gconv" "testing" "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gconv" ) func Test_Size(t *testing.T) { diff --git a/os/gfile/gfile_z_test.go b/os/gfile/gfile_z_unit_test.go similarity index 99% rename from os/gfile/gfile_z_test.go rename to os/gfile/gfile_z_unit_test.go index d26aee020..4ef155e26 100644 --- a/os/gfile/gfile_z_test.go +++ b/os/gfile/gfile_z_unit_test.go @@ -12,11 +12,10 @@ import ( "strings" "testing" - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/util/gconv" - "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gconv" ) func Test_IsDir(t *testing.T) { @@ -399,7 +398,7 @@ func Test_Glob(t *testing.T) { testpath() + "/testfiles/t2.txt", } - //===============================构建测试文件 + // ===============================构建测试文件 createDir(dirpath) for _, v := range havelist1 { createTestFile(dirpath+"/"+v, "") diff --git a/os/gfile/gfile_z_time_test.go b/os/gfile/gfile_z_unit_time_test.go similarity index 100% rename from os/gfile/gfile_z_time_test.go rename to os/gfile/gfile_z_unit_time_test.go diff --git a/os/gfpool/gfpool.go b/os/gfpool/gfpool.go index 98bf0e224..5eec01b27 100644 --- a/os/gfpool/gfpool.go +++ b/os/gfpool/gfpool.go @@ -8,14 +8,15 @@ package gfpool import ( + "os" + "time" + "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/container/gpool" "github.com/gogf/gf/v2/container/gtype" - "os" - "time" ) -// File pointer pool. +// Pool pointer pool. type Pool struct { id *gtype.Int // Pool id, which is used to mark this pool whether recreated. pool *gpool.Pool // Underlying pool. diff --git a/os/gfpool/gfpool_file.go b/os/gfpool/gfpool_file.go index 3d318fd26..290615171 100644 --- a/os/gfpool/gfpool_file.go +++ b/os/gfpool/gfpool_file.go @@ -8,10 +8,11 @@ package gfpool import ( "fmt" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" "os" "time" + + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" ) // Open creates and returns a file item with given file path, flag and opening permission. @@ -25,10 +26,10 @@ func Open(path string, flag int, perm os.FileMode, ttl ...time.Duration) (file * // DO NOT search the path here wasting performance! // Leave following codes just for warning you. // - //path, err = gfile.Search(path) - //if err != nil { + // path, err = gfile.Search(path) + // if err != nil { // return nil, err - //} + // } pool := pools.GetOrSetFuncLock( fmt.Sprintf("%s&%d&%d&%d", path, flag, fpTTL, perm), func() interface{} { diff --git a/os/gfpool/gfpool_z_unit_concurrent_test.go b/os/gfpool/gfpool_z_unit_concurrent_test.go deleted file mode 100644 index 9c934b809..000000000 --- a/os/gfpool/gfpool_z_unit_concurrent_test.go +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. -// -// This Source Code Form is subject to the terms of the MIT License. -// If a copy of the MIT was not distributed with this file, -// You can obtain one at https://github.com/gogf/gf. - -package gfpool_test - -import ( - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/os/gfpool" - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/test/gtest" - "github.com/gogf/gf/v2/text/gstr" - "os" - "testing" -) - -func Test_ConcurrentOS(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - path := gfile.TempDir(gtime.TimestampNanoStr()) - defer gfile.Remove(path) - f1, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) - t.Assert(err, nil) - defer f1.Close() - - f2, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) - t.Assert(err, nil) - defer f2.Close() - - for i := 0; i < 100; i++ { - _, err = f1.Write([]byte("@1234567890#")) - t.Assert(err, nil) - } - for i := 0; i < 100; i++ { - _, err = f2.Write([]byte("@1234567890#")) - t.Assert(err, nil) - } - - for i := 0; i < 1000; i++ { - _, err = f1.Write([]byte("@1234567890#")) - t.Assert(err, nil) - } - for i := 0; i < 1000; i++ { - _, err = f2.Write([]byte("@1234567890#")) - t.Assert(err, nil) - } - t.Assert(gstr.Count(gfile.GetContents(path), "@1234567890#"), 2200) - }) - - gtest.C(t, func(t *gtest.T) { - path := gfile.TempDir(gtime.TimestampNanoStr()) - defer gfile.Remove(path) - f1, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) - t.Assert(err, nil) - defer f1.Close() - - f2, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) - t.Assert(err, nil) - defer f2.Close() - - for i := 0; i < 1000; i++ { - _, err = f1.Write([]byte("@1234567890#")) - t.Assert(err, nil) - } - for i := 0; i < 1000; i++ { - _, err = f2.Write([]byte("@1234567890#")) - t.Assert(err, nil) - } - t.Assert(gstr.Count(gfile.GetContents(path), "@1234567890#"), 2000) - }) - gtest.C(t, func(t *gtest.T) { - path := gfile.TempDir(gtime.TimestampNanoStr()) - defer gfile.Remove(path) - f1, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) - t.Assert(err, nil) - defer f1.Close() - - f2, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) - t.Assert(err, nil) - defer f2.Close() - - s1 := "" - for i := 0; i < 1000; i++ { - s1 += "@1234567890#" - } - _, err = f2.Write([]byte(s1)) - t.Assert(err, nil) - - s2 := "" - for i := 0; i < 1000; i++ { - s2 += "@1234567890#" - } - _, err = f2.Write([]byte(s2)) - t.Assert(err, nil) - - t.Assert(gstr.Count(gfile.GetContents(path), "@1234567890#"), 2000) - }) - // DATA RACE - //gtest.C(t, func(t *gtest.T) { - // path := gfile.TempDir(gtime.TimestampNanoStr()) - // defer gfile.Remove(path) - // f1, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) - // t.Assert(err, nil) - // defer f1.Close() - // - // f2, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) - // t.Assert(err, nil) - // defer f2.Close() - // - // wg := sync.WaitGroup{} - // ch := make(chan struct{}) - // for i := 0; i < 1000; i++ { - // wg.Add(1) - // go func() { - // defer wg.Done() - // <-ch - // _, err = f1.Write([]byte("@1234567890#")) - // t.Assert(err, nil) - // }() - // } - // for i := 0; i < 1000; i++ { - // wg.Add(1) - // go func() { - // defer wg.Done() - // <-ch - // _, err = f2.Write([]byte("@1234567890#")) - // t.Assert(err, nil) - // }() - // } - // close(ch) - // wg.Wait() - // t.Assert(gstr.Count(gfile.GetContents(path), "@1234567890#"), 2000) - //}) -} - -func Test_ConcurrentGFPool(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - path := gfile.TempDir(gtime.TimestampNanoStr()) - defer gfile.Remove(path) - f1, err := gfpool.Open(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) - t.Assert(err, nil) - defer f1.Close() - - f2, err := gfpool.Open(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) - t.Assert(err, nil) - defer f2.Close() - - for i := 0; i < 1000; i++ { - _, err = f1.Write([]byte("@1234567890#")) - t.Assert(err, nil) - } - for i := 0; i < 1000; i++ { - _, err = f2.Write([]byte("@1234567890#")) - t.Assert(err, nil) - } - t.Assert(gstr.Count(gfile.GetContents(path), "@1234567890#"), 2000) - }) - // DATA RACE - //gtest.C(t, func(t *gtest.T) { - // path := gfile.TempDir(gtime.TimestampNanoStr()) - // defer gfile.Remove(path) - // f1, err := gfpool.Open(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) - // t.Assert(err, nil) - // defer f1.Close() - // - // f2, err := gfpool.Open(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) - // t.Assert(err, nil) - // defer f2.Close() - // - // wg := sync.WaitGroup{} - // ch := make(chan struct{}) - // for i := 0; i < 1000; i++ { - // wg.Add(1) - // go func() { - // defer wg.Done() - // <-ch - // _, err = f1.Write([]byte("@1234567890#")) - // t.Assert(err, nil) - // }() - // } - // for i := 0; i < 1000; i++ { - // wg.Add(1) - // go func() { - // defer wg.Done() - // <-ch - // _, err = f2.Write([]byte("@1234567890#")) - // t.Assert(err, nil) - // }() - // } - // close(ch) - // wg.Wait() - // t.Assert(gstr.Count(gfile.GetContents(path), "@1234567890#"), 2000) - //}) -} diff --git a/os/gfpool/gfpool_z_unit_test.go b/os/gfpool/gfpool_z_unit_test.go index 51a0252b3..87e12a461 100644 --- a/os/gfpool/gfpool_z_unit_test.go +++ b/os/gfpool/gfpool_z_unit_test.go @@ -15,7 +15,9 @@ import ( "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/gfpool" "github.com/gogf/gf/v2/os/glog" + "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/text/gstr" ) // TestOpen test open file cache @@ -142,3 +144,181 @@ func stop(testFile string) { } } } + +func Test_ConcurrentOS(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + path := gfile.TempDir(gtime.TimestampNanoStr()) + defer gfile.Remove(path) + f1, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) + t.Assert(err, nil) + defer f1.Close() + + f2, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) + t.Assert(err, nil) + defer f2.Close() + + for i := 0; i < 100; i++ { + _, err = f1.Write([]byte("@1234567890#")) + t.Assert(err, nil) + } + for i := 0; i < 100; i++ { + _, err = f2.Write([]byte("@1234567890#")) + t.Assert(err, nil) + } + + for i := 0; i < 1000; i++ { + _, err = f1.Write([]byte("@1234567890#")) + t.Assert(err, nil) + } + for i := 0; i < 1000; i++ { + _, err = f2.Write([]byte("@1234567890#")) + t.Assert(err, nil) + } + t.Assert(gstr.Count(gfile.GetContents(path), "@1234567890#"), 2200) + }) + + gtest.C(t, func(t *gtest.T) { + path := gfile.TempDir(gtime.TimestampNanoStr()) + defer gfile.Remove(path) + f1, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) + t.Assert(err, nil) + defer f1.Close() + + f2, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) + t.Assert(err, nil) + defer f2.Close() + + for i := 0; i < 1000; i++ { + _, err = f1.Write([]byte("@1234567890#")) + t.Assert(err, nil) + } + for i := 0; i < 1000; i++ { + _, err = f2.Write([]byte("@1234567890#")) + t.Assert(err, nil) + } + t.Assert(gstr.Count(gfile.GetContents(path), "@1234567890#"), 2000) + }) + gtest.C(t, func(t *gtest.T) { + path := gfile.TempDir(gtime.TimestampNanoStr()) + defer gfile.Remove(path) + f1, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) + t.Assert(err, nil) + defer f1.Close() + + f2, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) + t.Assert(err, nil) + defer f2.Close() + + s1 := "" + for i := 0; i < 1000; i++ { + s1 += "@1234567890#" + } + _, err = f2.Write([]byte(s1)) + t.Assert(err, nil) + + s2 := "" + for i := 0; i < 1000; i++ { + s2 += "@1234567890#" + } + _, err = f2.Write([]byte(s2)) + t.Assert(err, nil) + + t.Assert(gstr.Count(gfile.GetContents(path), "@1234567890#"), 2000) + }) + // DATA RACE + // gtest.C(t, func(t *gtest.T) { + // path := gfile.TempDir(gtime.TimestampNanoStr()) + // defer gfile.Remove(path) + // f1, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) + // t.Assert(err, nil) + // defer f1.Close() + // + // f2, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) + // t.Assert(err, nil) + // defer f2.Close() + // + // wg := sync.WaitGroup{} + // ch := make(chan struct{}) + // for i := 0; i < 1000; i++ { + // wg.Add(1) + // go func() { + // defer wg.Done() + // <-ch + // _, err = f1.Write([]byte("@1234567890#")) + // t.Assert(err, nil) + // }() + // } + // for i := 0; i < 1000; i++ { + // wg.Add(1) + // go func() { + // defer wg.Done() + // <-ch + // _, err = f2.Write([]byte("@1234567890#")) + // t.Assert(err, nil) + // }() + // } + // close(ch) + // wg.Wait() + // t.Assert(gstr.Count(gfile.GetContents(path), "@1234567890#"), 2000) + // }) +} + +func Test_ConcurrentGFPool(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + path := gfile.TempDir(gtime.TimestampNanoStr()) + defer gfile.Remove(path) + f1, err := gfpool.Open(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) + t.Assert(err, nil) + defer f1.Close() + + f2, err := gfpool.Open(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) + t.Assert(err, nil) + defer f2.Close() + + for i := 0; i < 1000; i++ { + _, err = f1.Write([]byte("@1234567890#")) + t.Assert(err, nil) + } + for i := 0; i < 1000; i++ { + _, err = f2.Write([]byte("@1234567890#")) + t.Assert(err, nil) + } + t.Assert(gstr.Count(gfile.GetContents(path), "@1234567890#"), 2000) + }) + // DATA RACE + // gtest.C(t, func(t *gtest.T) { + // path := gfile.TempDir(gtime.TimestampNanoStr()) + // defer gfile.Remove(path) + // f1, err := gfpool.Open(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) + // t.Assert(err, nil) + // defer f1.Close() + // + // f2, err := gfpool.Open(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666) + // t.Assert(err, nil) + // defer f2.Close() + // + // wg := sync.WaitGroup{} + // ch := make(chan struct{}) + // for i := 0; i < 1000; i++ { + // wg.Add(1) + // go func() { + // defer wg.Done() + // <-ch + // _, err = f1.Write([]byte("@1234567890#")) + // t.Assert(err, nil) + // }() + // } + // for i := 0; i < 1000; i++ { + // wg.Add(1) + // go func() { + // defer wg.Done() + // <-ch + // _, err = f2.Write([]byte("@1234567890#")) + // t.Assert(err, nil) + // }() + // } + // close(ch) + // wg.Wait() + // t.Assert(gstr.Count(gfile.GetContents(path), "@1234567890#"), 2000) + // }) +} diff --git a/os/gfsnotify/gfsnotify.go b/os/gfsnotify/gfsnotify.go index beadd0d52..b6de60e0e 100644 --- a/os/gfsnotify/gfsnotify.go +++ b/os/gfsnotify/gfsnotify.go @@ -9,18 +9,19 @@ package gfsnotify import ( "context" - "github.com/gogf/gf/v2/container/gset" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/internal/intlog" "sync" "time" "github.com/fsnotify/fsnotify" + "github.com/gogf/gf/v2/container/glist" "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/container/gqueue" + "github.com/gogf/gf/v2/container/gset" "github.com/gogf/gf/v2/container/gtype" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/os/gcache" ) diff --git a/os/gfsnotify/gfsnotify_watcher.go b/os/gfsnotify/gfsnotify_watcher.go index 92bf2cf00..87aee12b4 100644 --- a/os/gfsnotify/gfsnotify_watcher.go +++ b/os/gfsnotify/gfsnotify_watcher.go @@ -8,11 +8,11 @@ package gfsnotify import ( "context" + + "github.com/gogf/gf/v2/container/glist" "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/intlog" - - "github.com/gogf/gf/v2/container/glist" ) // Add monitors `path` with callback function `callbackFunc` to the watcher. diff --git a/os/gfsnotify/gfsnotify_watcher_loop.go b/os/gfsnotify/gfsnotify_watcher_loop.go index bd41d3908..56c67e4be 100644 --- a/os/gfsnotify/gfsnotify_watcher_loop.go +++ b/os/gfsnotify/gfsnotify_watcher_loop.go @@ -8,6 +8,7 @@ package gfsnotify import ( "context" + "github.com/gogf/gf/v2/container/glist" "github.com/gogf/gf/v2/internal/intlog" ) diff --git a/os/gfsnotify/gfsnotify_z_unit_test.go b/os/gfsnotify/gfsnotify_z_unit_test.go index d8ec316c6..020e4fe09 100644 --- a/os/gfsnotify/gfsnotify_z_unit_test.go +++ b/os/gfsnotify/gfsnotify_z_unit_test.go @@ -7,10 +7,10 @@ package gfsnotify_test import ( - "github.com/gogf/gf/v2/container/garray" "testing" "time" + "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/container/gtype" "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/gfsnotify" @@ -204,7 +204,7 @@ func TestWatcher_WatchFolderWithoutRecursively(t *testing.T) { t.AssertNil(err) _, err = gfsnotify.Add(dirPath, func(event *gfsnotify.Event) { - //fmt.Println(event.String()) + // fmt.Println(event.String()) array.Append(1) }, false) t.AssertNil(err) diff --git a/os/glog/glog_logger.go b/os/glog/glog_logger.go index bdd873976..0190e3f09 100644 --- a/os/glog/glog_logger.go +++ b/os/glog/glog_logger.go @@ -10,23 +10,23 @@ import ( "bytes" "context" "fmt" - "github.com/fatih/color" - "github.com/gogf/gf/v2/container/gtype" - "github.com/gogf/gf/v2/internal/intlog" - "github.com/gogf/gf/v2/os/gctx" - "github.com/gogf/gf/v2/os/gfpool" - "github.com/gogf/gf/v2/os/gmlock" - "github.com/gogf/gf/v2/os/gtimer" - "go.opentelemetry.io/otel/trace" "io" "os" "strings" "time" - "github.com/gogf/gf/v2/debug/gdebug" + "github.com/fatih/color" + "go.opentelemetry.io/otel/trace" + "github.com/gogf/gf/v2/container/gtype" + "github.com/gogf/gf/v2/debug/gdebug" + "github.com/gogf/gf/v2/internal/intlog" + "github.com/gogf/gf/v2/os/gctx" "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/os/gfpool" + "github.com/gogf/gf/v2/os/gmlock" "github.com/gogf/gf/v2/os/gtime" + "github.com/gogf/gf/v2/os/gtimer" "github.com/gogf/gf/v2/text/gregex" "github.com/gogf/gf/v2/util/gconv" ) diff --git a/os/glog/glog_logger_config.go b/os/glog/glog_logger_config.go index c33ac786e..20c36e699 100644 --- a/os/glog/glog_logger_config.go +++ b/os/glog/glog_logger_config.go @@ -8,14 +8,14 @@ package glog import ( "context" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/os/gctx" "io" "strings" "time" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/intlog" + "github.com/gogf/gf/v2/os/gctx" "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/gutil" @@ -255,7 +255,7 @@ func (l *Logger) SetHandlers(handlers ...Handler) { l.config.Handlers = handlers } -//SetWriterColorEnable sets the file logging with color +// SetWriterColorEnable sets the file logging with color func (l *Logger) SetWriterColorEnable(enabled bool) { l.config.WriterColorEnable = enabled } diff --git a/os/glog/glog_logger_level.go b/os/glog/glog_logger_level.go index 3f20e65d4..e1fe6b6a3 100644 --- a/os/glog/glog_logger_level.go +++ b/os/glog/glog_logger_level.go @@ -7,9 +7,10 @@ package glog import ( + "strings" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" - "strings" ) // Note that the LEVEL_PANI and LEVEL_FATA levels are not used for logging output, diff --git a/os/glog/glog_logger_rotate.go b/os/glog/glog_logger_rotate.go index 19470606b..6e7ca96de 100644 --- a/os/glog/glog_logger_rotate.go +++ b/os/glog/glog_logger_rotate.go @@ -9,6 +9,8 @@ package glog import ( "context" "fmt" + "time" + "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/encoding/gcompress" "github.com/gogf/gf/v2/internal/intlog" @@ -17,7 +19,6 @@ import ( "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/os/gtimer" "github.com/gogf/gf/v2/text/gregex" - "time" ) const ( diff --git a/os/glog/glog_z_example_test.go b/os/glog/glog_z_example_test.go index 3d8467b7d..e31c321c1 100644 --- a/os/glog/glog_z_example_test.go +++ b/os/glog/glog_z_example_test.go @@ -8,6 +8,7 @@ package glog_test import ( "context" + "github.com/gogf/gf/v2/frame/g" ) diff --git a/os/glog/glog_z_unit_concurrent_test.go b/os/glog/glog_z_unit_concurrent_test.go deleted file mode 100644 index 43f036f68..000000000 --- a/os/glog/glog_z_unit_concurrent_test.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. -// -// This Source Code Form is subject to the terms of the MIT License. -// If a copy of the MIT was not distributed with this file, -// You can obtain one at https://github.com/gogf/gf. - -package glog_test - -import ( - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/test/gtest" - "github.com/gogf/gf/v2/text/gstr" - "sync" - "testing" -) - -func Test_Concurrent(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - c := 1000 - l := glog.New() - s := "@1234567890#" - f := "test.log" - p := gfile.TempDir(gtime.TimestampNanoStr()) - t.Assert(l.SetPath(p), nil) - defer gfile.Remove(p) - wg := sync.WaitGroup{} - ch := make(chan struct{}) - for i := 0; i < c; i++ { - wg.Add(1) - go func() { - defer wg.Done() - <-ch - l.File(f).Stdout(false).Print(ctx, s) - }() - } - close(ch) - wg.Wait() - content := gfile.GetContents(gfile.Join(p, f)) - t.Assert(gstr.Count(content, s), c) - }) -} diff --git a/os/glog/glog_z_unit_config_test.go b/os/glog/glog_z_unit_config_test.go index 43b2e1825..6b33466d9 100644 --- a/os/glog/glog_z_unit_config_test.go +++ b/os/glog/glog_z_unit_config_test.go @@ -8,9 +8,10 @@ package glog import ( "bytes" - "github.com/gogf/gf/v2/test/gtest" "strings" "testing" + + "github.com/gogf/gf/v2/test/gtest" ) func Test_SetConfigWithMap(t *testing.T) { diff --git a/os/glog/glog_z_unit_basic_test.go b/os/glog/glog_z_unit_internal_test.go similarity index 55% rename from os/glog/glog_z_unit_basic_test.go rename to os/glog/glog_z_unit_internal_test.go index 393953847..f712eaf4e 100644 --- a/os/glog/glog_z_unit_basic_test.go +++ b/os/glog/glog_z_unit_internal_test.go @@ -9,9 +9,10 @@ package glog import ( "bytes" "context" + "testing" + "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/text/gstr" - "testing" ) var ( @@ -83,3 +84,48 @@ func Test_Error(t *testing.T) { t.Assert(gstr.Count(w.String(), "1 2 3"), 2) }) } + +func Test_LevelPrefix(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + l := New() + t.Assert(l.GetLevelPrefix(LEVEL_DEBU), defaultLevelPrefixes[LEVEL_DEBU]) + t.Assert(l.GetLevelPrefix(LEVEL_INFO), defaultLevelPrefixes[LEVEL_INFO]) + t.Assert(l.GetLevelPrefix(LEVEL_NOTI), defaultLevelPrefixes[LEVEL_NOTI]) + t.Assert(l.GetLevelPrefix(LEVEL_WARN), defaultLevelPrefixes[LEVEL_WARN]) + t.Assert(l.GetLevelPrefix(LEVEL_ERRO), defaultLevelPrefixes[LEVEL_ERRO]) + t.Assert(l.GetLevelPrefix(LEVEL_CRIT), defaultLevelPrefixes[LEVEL_CRIT]) + l.SetLevelPrefix(LEVEL_DEBU, "debug") + t.Assert(l.GetLevelPrefix(LEVEL_DEBU), "debug") + l.SetLevelPrefixes(map[int]string{ + LEVEL_CRIT: "critical", + }) + t.Assert(l.GetLevelPrefix(LEVEL_DEBU), "debug") + t.Assert(l.GetLevelPrefix(LEVEL_INFO), defaultLevelPrefixes[LEVEL_INFO]) + t.Assert(l.GetLevelPrefix(LEVEL_NOTI), defaultLevelPrefixes[LEVEL_NOTI]) + t.Assert(l.GetLevelPrefix(LEVEL_WARN), defaultLevelPrefixes[LEVEL_WARN]) + t.Assert(l.GetLevelPrefix(LEVEL_ERRO), defaultLevelPrefixes[LEVEL_ERRO]) + t.Assert(l.GetLevelPrefix(LEVEL_CRIT), "critical") + }) + gtest.C(t, func(t *gtest.T) { + buffer := bytes.NewBuffer(nil) + l := New() + l.SetWriter(buffer) + l.Debug(ctx, "test1") + t.Assert(gstr.Contains(buffer.String(), defaultLevelPrefixes[LEVEL_DEBU]), true) + + buffer.Reset() + + l.SetLevelPrefix(LEVEL_DEBU, "debug") + l.Debug(ctx, "test2") + t.Assert(gstr.Contains(buffer.String(), defaultLevelPrefixes[LEVEL_DEBU]), false) + t.Assert(gstr.Contains(buffer.String(), "debug"), true) + + buffer.Reset() + l.SetLevelPrefixes(map[int]string{ + LEVEL_ERRO: "error", + }) + l.Error(ctx, "test3") + t.Assert(gstr.Contains(buffer.String(), defaultLevelPrefixes[LEVEL_ERRO]), false) + t.Assert(gstr.Contains(buffer.String(), "error"), true) + }) +} diff --git a/os/glog/glog_z_unit_level_test.go b/os/glog/glog_z_unit_level_test.go deleted file mode 100644 index cb49574a0..000000000 --- a/os/glog/glog_z_unit_level_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. -// -// This Source Code Form is subject to the terms of the MIT License. -// If a copy of the MIT was not distributed with this file, -// You can obtain one at https://github.com/gogf/gf. - -package glog - -import ( - "bytes" - "github.com/gogf/gf/v2/test/gtest" - "github.com/gogf/gf/v2/text/gstr" - "testing" -) - -func Test_LevelPrefix(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - l := New() - t.Assert(l.GetLevelPrefix(LEVEL_DEBU), defaultLevelPrefixes[LEVEL_DEBU]) - t.Assert(l.GetLevelPrefix(LEVEL_INFO), defaultLevelPrefixes[LEVEL_INFO]) - t.Assert(l.GetLevelPrefix(LEVEL_NOTI), defaultLevelPrefixes[LEVEL_NOTI]) - t.Assert(l.GetLevelPrefix(LEVEL_WARN), defaultLevelPrefixes[LEVEL_WARN]) - t.Assert(l.GetLevelPrefix(LEVEL_ERRO), defaultLevelPrefixes[LEVEL_ERRO]) - t.Assert(l.GetLevelPrefix(LEVEL_CRIT), defaultLevelPrefixes[LEVEL_CRIT]) - l.SetLevelPrefix(LEVEL_DEBU, "debug") - t.Assert(l.GetLevelPrefix(LEVEL_DEBU), "debug") - l.SetLevelPrefixes(map[int]string{ - LEVEL_CRIT: "critical", - }) - t.Assert(l.GetLevelPrefix(LEVEL_DEBU), "debug") - t.Assert(l.GetLevelPrefix(LEVEL_INFO), defaultLevelPrefixes[LEVEL_INFO]) - t.Assert(l.GetLevelPrefix(LEVEL_NOTI), defaultLevelPrefixes[LEVEL_NOTI]) - t.Assert(l.GetLevelPrefix(LEVEL_WARN), defaultLevelPrefixes[LEVEL_WARN]) - t.Assert(l.GetLevelPrefix(LEVEL_ERRO), defaultLevelPrefixes[LEVEL_ERRO]) - t.Assert(l.GetLevelPrefix(LEVEL_CRIT), "critical") - }) - gtest.C(t, func(t *gtest.T) { - buffer := bytes.NewBuffer(nil) - l := New() - l.SetWriter(buffer) - l.Debug(ctx, "test1") - t.Assert(gstr.Contains(buffer.String(), defaultLevelPrefixes[LEVEL_DEBU]), true) - - buffer.Reset() - - l.SetLevelPrefix(LEVEL_DEBU, "debug") - l.Debug(ctx, "test2") - t.Assert(gstr.Contains(buffer.String(), defaultLevelPrefixes[LEVEL_DEBU]), false) - t.Assert(gstr.Contains(buffer.String(), "debug"), true) - - buffer.Reset() - l.SetLevelPrefixes(map[int]string{ - LEVEL_ERRO: "error", - }) - l.Error(ctx, "test3") - t.Assert(gstr.Contains(buffer.String(), defaultLevelPrefixes[LEVEL_ERRO]), false) - t.Assert(gstr.Contains(buffer.String(), "error"), true) - }) -} diff --git a/os/glog/glog_z_unit_chaining_test.go b/os/glog/glog_z_unit_logger_chaining_test.go similarity index 99% rename from os/glog/glog_z_unit_chaining_test.go rename to os/glog/glog_z_unit_logger_chaining_test.go index 846ce62ca..f0f6989e5 100644 --- a/os/glog/glog_z_unit_chaining_test.go +++ b/os/glog/glog_z_unit_logger_chaining_test.go @@ -9,12 +9,13 @@ package glog import ( "bytes" "fmt" + "testing" + "time" + "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/text/gstr" - "testing" - "time" ) func Test_To(t *testing.T) { diff --git a/os/glog/glog_z_unit_handler_test.go b/os/glog/glog_z_unit_logger_handler_test.go similarity index 99% rename from os/glog/glog_z_unit_handler_test.go rename to os/glog/glog_z_unit_logger_handler_test.go index 587614f92..aeca8983e 100644 --- a/os/glog/glog_z_unit_handler_test.go +++ b/os/glog/glog_z_unit_logger_handler_test.go @@ -9,11 +9,12 @@ package glog_test import ( "bytes" "context" + "testing" + "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/os/glog" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/text/gstr" - "testing" ) var arrayForHandlerTest1 = garray.NewStrArray() diff --git a/os/glog/glog_z_unit_rotate_test.go b/os/glog/glog_z_unit_logger_rotate_test.go similarity index 99% rename from os/glog/glog_z_unit_rotate_test.go rename to os/glog/glog_z_unit_logger_rotate_test.go index 7ec5fe090..36da85b1d 100644 --- a/os/glog/glog_z_unit_rotate_test.go +++ b/os/glog/glog_z_unit_logger_rotate_test.go @@ -9,14 +9,15 @@ package glog_test import ( "context" "fmt" + "testing" + "time" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/glog" "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/text/gstr" - "testing" - "time" ) var ( diff --git a/os/glog/glog_z_unit_ctx_test.go b/os/glog/glog_z_unit_test.go similarity index 74% rename from os/glog/glog_z_unit_ctx_test.go rename to os/glog/glog_z_unit_test.go index 028ed0a5b..054e75a44 100644 --- a/os/glog/glog_z_unit_ctx_test.go +++ b/os/glog/glog_z_unit_test.go @@ -9,12 +9,16 @@ package glog_test import ( "bytes" "context" + "sync" + "testing" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gctx" + "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/glog" + "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/text/gstr" - "testing" ) func Test_Ctx(t *testing.T) { @@ -60,3 +64,29 @@ func Test_Ctx_CtxKey(t *testing.T) { t.Assert(gstr.Count(w.String(), "1 2 3"), 1) }) } + +func Test_Concurrent(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + c := 1000 + l := glog.New() + s := "@1234567890#" + f := "test.log" + p := gfile.TempDir(gtime.TimestampNanoStr()) + t.Assert(l.SetPath(p), nil) + defer gfile.Remove(p) + wg := sync.WaitGroup{} + ch := make(chan struct{}) + for i := 0; i < c; i++ { + wg.Add(1) + go func() { + defer wg.Done() + <-ch + l.File(f).Stdout(false).Print(ctx, s) + }() + } + close(ch) + wg.Wait() + content := gfile.GetContents(gfile.Join(p, f)) + t.Assert(gstr.Count(content, s), c) + }) +} diff --git a/os/gmlock/gmlock_unit_lock_test.go b/os/gmlock/gmlock_unit_lock_test.go deleted file mode 100644 index d738d603b..000000000 --- a/os/gmlock/gmlock_unit_lock_test.go +++ /dev/null @@ -1,205 +0,0 @@ -// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. -// -// This Source Code Form is subject to the terms of the MIT License. -// If a copy of the MIT was not distributed with this file, -// You can obtain one at https://github.com/gogf/gf. - -package gmlock_test - -import ( - "sync" - "testing" - "time" - - "github.com/gogf/gf/v2/container/garray" - "github.com/gogf/gf/v2/os/gmlock" - "github.com/gogf/gf/v2/test/gtest" -) - -func Test_Locker_Lock(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - key := "testLock" - array := garray.New(true) - go func() { - gmlock.Lock(key) - array.Append(1) - time.Sleep(300 * time.Millisecond) - gmlock.Unlock(key) - }() - go func() { - time.Sleep(100 * time.Millisecond) - gmlock.Lock(key) - array.Append(1) - gmlock.Unlock(key) - }() - time.Sleep(100 * time.Millisecond) - t.Assert(array.Len(), 1) - time.Sleep(100 * time.Millisecond) - t.Assert(array.Len(), 1) - time.Sleep(200 * time.Millisecond) - t.Assert(array.Len(), 2) - gmlock.Remove(key) - }) - - gtest.C(t, func(t *gtest.T) { - key := "testLock" - array := garray.New(true) - lock := gmlock.New() - go func() { - lock.Lock(key) - array.Append(1) - time.Sleep(300 * time.Millisecond) - lock.Unlock(key) - }() - go func() { - time.Sleep(100 * time.Millisecond) - lock.Lock(key) - array.Append(1) - lock.Unlock(key) - }() - time.Sleep(100 * time.Millisecond) - t.Assert(array.Len(), 1) - time.Sleep(100 * time.Millisecond) - t.Assert(array.Len(), 1) - time.Sleep(200 * time.Millisecond) - t.Assert(array.Len(), 2) - lock.Clear() - }) - -} - -func Test_Locker_TryLock(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - key := "testTryLock" - array := garray.New(true) - go func() { - gmlock.Lock(key) - array.Append(1) - time.Sleep(300 * time.Millisecond) - gmlock.Unlock(key) - }() - go func() { - time.Sleep(150 * time.Millisecond) - if gmlock.TryLock(key) { - array.Append(1) - gmlock.Unlock(key) - } - }() - go func() { - time.Sleep(400 * time.Millisecond) - if gmlock.TryLock(key) { - array.Append(1) - gmlock.Unlock(key) - } - }() - time.Sleep(100 * time.Millisecond) - t.Assert(array.Len(), 1) - time.Sleep(100 * time.Millisecond) - t.Assert(array.Len(), 1) - time.Sleep(300 * time.Millisecond) - t.Assert(array.Len(), 2) - }) - -} - -func Test_Locker_LockFunc(t *testing.T) { - //no expire - gtest.C(t, func(t *gtest.T) { - key := "testLockFunc" - array := garray.New(true) - go func() { - gmlock.LockFunc(key, func() { - array.Append(1) - time.Sleep(300 * time.Millisecond) - }) // - }() - go func() { - time.Sleep(100 * time.Millisecond) - gmlock.LockFunc(key, func() { - array.Append(1) - }) - }() - time.Sleep(100 * time.Millisecond) - t.Assert(array.Len(), 1) - time.Sleep(100 * time.Millisecond) - t.Assert(array.Len(), 1) // - time.Sleep(200 * time.Millisecond) - t.Assert(array.Len(), 2) - }) -} -func Test_Locker_TryLockFunc(t *testing.T) { - //no expire - gtest.C(t, func(t *gtest.T) { - key := "testTryLockFunc" - array := garray.New(true) - go func() { - gmlock.TryLockFunc(key, func() { - array.Append(1) - time.Sleep(200 * time.Millisecond) - }) - }() - go func() { - time.Sleep(100 * time.Millisecond) - gmlock.TryLockFunc(key, func() { - array.Append(1) - }) - }() - go func() { - time.Sleep(300 * time.Millisecond) - gmlock.TryLockFunc(key, func() { - array.Append(1) - }) - }() - time.Sleep(150 * time.Millisecond) - t.Assert(array.Len(), 1) - time.Sleep(400 * time.Millisecond) - t.Assert(array.Len(), 2) - }) -} - -func Test_Multiple_Goroutine(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - ch := make(chan struct{}, 0) - num := 1000 - wait := sync.WaitGroup{} - wait.Add(num) - for i := 0; i < num; i++ { - go func() { - defer wait.Done() - <-ch - gmlock.Lock("test") - defer gmlock.Unlock("test") - time.Sleep(time.Millisecond) - }() - } - close(ch) - wait.Wait() - }) - - gtest.C(t, func(t *gtest.T) { - ch := make(chan struct{}, 0) - num := 100 - wait := sync.WaitGroup{} - wait.Add(num * 2) - for i := 0; i < num; i++ { - go func() { - defer wait.Done() - <-ch - gmlock.Lock("test") - defer gmlock.Unlock("test") - time.Sleep(time.Millisecond) - }() - } - for i := 0; i < num; i++ { - go func() { - defer wait.Done() - <-ch - gmlock.RLock("test") - defer gmlock.RUnlock("test") - time.Sleep(time.Millisecond) - }() - } - close(ch) - wait.Wait() - }) -} diff --git a/os/gmlock/gmlock_z_bench_test.go b/os/gmlock/gmlock_z_bench_test.go index 553500f56..b057ed933 100644 --- a/os/gmlock/gmlock_z_bench_test.go +++ b/os/gmlock/gmlock_z_bench_test.go @@ -7,8 +7,9 @@ package gmlock_test import ( - "github.com/gogf/gf/v2/os/gmlock" "testing" + + "github.com/gogf/gf/v2/os/gmlock" ) var ( diff --git a/os/gmlock/gmlock_unit_rlock_test.go b/os/gmlock/gmlock_z_unit_test.go similarity index 58% rename from os/gmlock/gmlock_unit_rlock_test.go rename to os/gmlock/gmlock_z_unit_test.go index 63d4bba2a..9d2a08714 100644 --- a/os/gmlock/gmlock_unit_rlock_test.go +++ b/os/gmlock/gmlock_z_unit_test.go @@ -7,6 +7,7 @@ package gmlock_test import ( + "sync" "testing" "time" @@ -15,8 +16,197 @@ import ( "github.com/gogf/gf/v2/test/gtest" ) +func Test_Locker_Lock(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + key := "testLock" + array := garray.New(true) + go func() { + gmlock.Lock(key) + array.Append(1) + time.Sleep(300 * time.Millisecond) + gmlock.Unlock(key) + }() + go func() { + time.Sleep(100 * time.Millisecond) + gmlock.Lock(key) + array.Append(1) + gmlock.Unlock(key) + }() + time.Sleep(100 * time.Millisecond) + t.Assert(array.Len(), 1) + time.Sleep(100 * time.Millisecond) + t.Assert(array.Len(), 1) + time.Sleep(200 * time.Millisecond) + t.Assert(array.Len(), 2) + gmlock.Remove(key) + }) + + gtest.C(t, func(t *gtest.T) { + key := "testLock" + array := garray.New(true) + lock := gmlock.New() + go func() { + lock.Lock(key) + array.Append(1) + time.Sleep(300 * time.Millisecond) + lock.Unlock(key) + }() + go func() { + time.Sleep(100 * time.Millisecond) + lock.Lock(key) + array.Append(1) + lock.Unlock(key) + }() + time.Sleep(100 * time.Millisecond) + t.Assert(array.Len(), 1) + time.Sleep(100 * time.Millisecond) + t.Assert(array.Len(), 1) + time.Sleep(200 * time.Millisecond) + t.Assert(array.Len(), 2) + lock.Clear() + }) + +} + +func Test_Locker_TryLock(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + key := "testTryLock" + array := garray.New(true) + go func() { + gmlock.Lock(key) + array.Append(1) + time.Sleep(300 * time.Millisecond) + gmlock.Unlock(key) + }() + go func() { + time.Sleep(150 * time.Millisecond) + if gmlock.TryLock(key) { + array.Append(1) + gmlock.Unlock(key) + } + }() + go func() { + time.Sleep(400 * time.Millisecond) + if gmlock.TryLock(key) { + array.Append(1) + gmlock.Unlock(key) + } + }() + time.Sleep(100 * time.Millisecond) + t.Assert(array.Len(), 1) + time.Sleep(100 * time.Millisecond) + t.Assert(array.Len(), 1) + time.Sleep(300 * time.Millisecond) + t.Assert(array.Len(), 2) + }) + +} + +func Test_Locker_LockFunc(t *testing.T) { + //no expire + gtest.C(t, func(t *gtest.T) { + key := "testLockFunc" + array := garray.New(true) + go func() { + gmlock.LockFunc(key, func() { + array.Append(1) + time.Sleep(300 * time.Millisecond) + }) // + }() + go func() { + time.Sleep(100 * time.Millisecond) + gmlock.LockFunc(key, func() { + array.Append(1) + }) + }() + time.Sleep(100 * time.Millisecond) + t.Assert(array.Len(), 1) + time.Sleep(100 * time.Millisecond) + t.Assert(array.Len(), 1) // + time.Sleep(200 * time.Millisecond) + t.Assert(array.Len(), 2) + }) +} + +func Test_Locker_TryLockFunc(t *testing.T) { + //no expire + gtest.C(t, func(t *gtest.T) { + key := "testTryLockFunc" + array := garray.New(true) + go func() { + gmlock.TryLockFunc(key, func() { + array.Append(1) + time.Sleep(200 * time.Millisecond) + }) + }() + go func() { + time.Sleep(100 * time.Millisecond) + gmlock.TryLockFunc(key, func() { + array.Append(1) + }) + }() + go func() { + time.Sleep(300 * time.Millisecond) + gmlock.TryLockFunc(key, func() { + array.Append(1) + }) + }() + time.Sleep(150 * time.Millisecond) + t.Assert(array.Len(), 1) + time.Sleep(400 * time.Millisecond) + t.Assert(array.Len(), 2) + }) +} + +func Test_Multiple_Goroutine(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + ch := make(chan struct{}, 0) + num := 1000 + wait := sync.WaitGroup{} + wait.Add(num) + for i := 0; i < num; i++ { + go func() { + defer wait.Done() + <-ch + gmlock.Lock("test") + defer gmlock.Unlock("test") + time.Sleep(time.Millisecond) + }() + } + close(ch) + wait.Wait() + }) + + gtest.C(t, func(t *gtest.T) { + ch := make(chan struct{}, 0) + num := 100 + wait := sync.WaitGroup{} + wait.Add(num * 2) + for i := 0; i < num; i++ { + go func() { + defer wait.Done() + <-ch + gmlock.Lock("test") + defer gmlock.Unlock("test") + time.Sleep(time.Millisecond) + }() + } + for i := 0; i < num; i++ { + go func() { + defer wait.Done() + <-ch + gmlock.RLock("test") + defer gmlock.RUnlock("test") + time.Sleep(time.Millisecond) + }() + } + close(ch) + wait.Wait() + }) +} + func Test_Locker_RLock(t *testing.T) { - //RLock before Lock + // RLock before Lock gtest.C(t, func(t *gtest.T) { key := "testRLockBeforeLock" array := garray.New(true) @@ -38,7 +228,7 @@ func Test_Locker_RLock(t *testing.T) { t.Assert(array.Len(), 2) }) - //Lock before RLock + // Lock before RLock gtest.C(t, func(t *gtest.T) { key := "testLockBeforeRLock" array := garray.New(true) @@ -60,7 +250,7 @@ func Test_Locker_RLock(t *testing.T) { t.Assert(array.Len(), 2) }) - //Lock before RLocks + // Lock before RLocks gtest.C(t, func(t *gtest.T) { key := "testLockBeforeRLocks" array := garray.New(true) @@ -92,7 +282,7 @@ func Test_Locker_RLock(t *testing.T) { } func Test_Locker_TryRLock(t *testing.T) { - //Lock before TryRLock + // Lock before TryRLock gtest.C(t, func(t *gtest.T) { key := "testLockBeforeTryRLock" array := garray.New(true) @@ -115,7 +305,7 @@ func Test_Locker_TryRLock(t *testing.T) { t.Assert(array.Len(), 1) }) - //Lock before TryRLocks + // Lock before TryRLocks gtest.C(t, func(t *gtest.T) { key := "testLockBeforeTryRLocks" array := garray.New(true) @@ -147,7 +337,7 @@ func Test_Locker_TryRLock(t *testing.T) { } func Test_Locker_RLockFunc(t *testing.T) { - //RLockFunc before Lock + // RLockFunc before Lock gtest.C(t, func(t *gtest.T) { key := "testRLockFuncBeforeLock" array := garray.New(true) @@ -169,7 +359,7 @@ func Test_Locker_RLockFunc(t *testing.T) { t.Assert(array.Len(), 2) }) - //Lock before RLockFunc + // Lock before RLockFunc gtest.C(t, func(t *gtest.T) { key := "testLockBeforeRLockFunc" array := garray.New(true) @@ -191,7 +381,7 @@ func Test_Locker_RLockFunc(t *testing.T) { t.Assert(array.Len(), 2) }) - //Lock before RLockFuncs + // Lock before RLockFuncs gtest.C(t, func(t *gtest.T) { key := "testLockBeforeRLockFuncs" array := garray.New(true) @@ -223,7 +413,7 @@ func Test_Locker_RLockFunc(t *testing.T) { } func Test_Locker_TryRLockFunc(t *testing.T) { - //Lock before TryRLockFunc + // Lock before TryRLockFunc gtest.C(t, func(t *gtest.T) { key := "testLockBeforeTryRLockFunc" array := garray.New(true) @@ -245,7 +435,7 @@ func Test_Locker_TryRLockFunc(t *testing.T) { t.Assert(array.Len(), 1) }) - //Lock before TryRLockFuncs + // Lock before TryRLockFuncs gtest.C(t, func(t *gtest.T) { key := "testLockBeforeTryRLockFuncs" array := garray.New(true) diff --git a/os/gmutex/gmutex.go b/os/gmutex/gmutex.go index 1e9a35556..7de6dcdc6 100644 --- a/os/gmutex/gmutex.go +++ b/os/gmutex/gmutex.go @@ -14,7 +14,7 @@ import ( "github.com/gogf/gf/v2/container/gtype" ) -// The high level Mutex, which implements more rich features for mutex. +// Mutex The high level Mutex, which implements more rich features for mutex. type Mutex struct { state *gtype.Int32 // Indicates the state of mutex. -1: writing locked; > 1 reading locked. writer *gtype.Int32 // Pending writer count. diff --git a/os/gmutex/gmutex_bench_test.go b/os/gmutex/gmutex_z_bench_test.go similarity index 100% rename from os/gmutex/gmutex_bench_test.go rename to os/gmutex/gmutex_z_bench_test.go diff --git a/os/gmutex/gmutex_unit_test.go b/os/gmutex/gmutex_z_unit_test.go similarity index 99% rename from os/gmutex/gmutex_unit_test.go rename to os/gmutex/gmutex_z_unit_test.go index 24f8a5235..993dd04ff 100644 --- a/os/gmutex/gmutex_unit_test.go +++ b/os/gmutex/gmutex_z_unit_test.go @@ -8,11 +8,11 @@ package gmutex_test import ( "context" - "github.com/gogf/gf/v2/os/glog" "testing" "time" "github.com/gogf/gf/v2/container/garray" + "github.com/gogf/gf/v2/os/glog" "github.com/gogf/gf/v2/os/gmutex" "github.com/gogf/gf/v2/test/gtest" ) @@ -41,7 +41,7 @@ func Test_Mutex_RUnlock(t *testing.T) { }) - //RLock before Lock + // RLock before Lock gtest.C(t, func(t *gtest.T) { mu := gmutex.New() mu.RLock() diff --git a/os/gproc/gproc.go b/os/gproc/gproc.go index 7519a873a..328763dd6 100644 --- a/os/gproc/gproc.go +++ b/os/gproc/gproc.go @@ -9,14 +9,14 @@ package gproc import ( "bytes" - "github.com/gogf/gf/v2/os/genv" - "github.com/gogf/gf/v2/text/gstr" "io" "os" "runtime" "time" + "github.com/gogf/gf/v2/os/genv" "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" ) diff --git a/os/gproc/gproc_comm.go b/os/gproc/gproc_comm.go index 666fda1ac..a1ed5db1c 100644 --- a/os/gproc/gproc_comm.go +++ b/os/gproc/gproc_comm.go @@ -9,6 +9,7 @@ package gproc import ( "context" "fmt" + "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" diff --git a/os/gproc/gproc_comm_receive.go b/os/gproc/gproc_comm_receive.go index b4f991f84..c23d0dd30 100644 --- a/os/gproc/gproc_comm_receive.go +++ b/os/gproc/gproc_comm_receive.go @@ -9,11 +9,11 @@ package gproc import ( "context" "fmt" - "github.com/gogf/gf/v2/internal/json" "net" "github.com/gogf/gf/v2/container/gqueue" "github.com/gogf/gf/v2/container/gtype" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/net/gtcp" "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/glog" @@ -94,7 +94,7 @@ func receiveTcpHandler(conn *gtcp.Conn) { // Package decoding. msg := new(MsgRequest) if err := json.UnmarshalUseNumber(buffer, msg); err != nil { - //glog.Error(err) + // glog.Error(err) continue } if msg.RecvPid != Pid() { diff --git a/os/gproc/gproc_comm_send.go b/os/gproc/gproc_comm_send.go index a19b6377d..fee372d38 100644 --- a/os/gproc/gproc_comm_send.go +++ b/os/gproc/gproc_comm_send.go @@ -7,10 +7,11 @@ package gproc import ( + "io" + "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/net/gtcp" - "io" ) // Send sends data to specified process of given pid. diff --git a/os/gproc/gproc_process.go b/os/gproc/gproc_process.go index 355bf7f36..d420cece7 100644 --- a/os/gproc/gproc_process.go +++ b/os/gproc/gproc_process.go @@ -9,13 +9,14 @@ package gproc import ( "context" "fmt" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/internal/intlog" "os" "os/exec" "runtime" "strings" + + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/intlog" ) // Process is the struct for a single process. @@ -123,7 +124,7 @@ func (p *Process) Kill() error { } _, err = p.Process.Wait() intlog.Error(context.TODO(), err) - //return err + // return err return nil } else { return err diff --git a/os/gproc/gproc_signal.go b/os/gproc/gproc_signal.go index a84805952..4454d8745 100644 --- a/os/gproc/gproc_signal.go +++ b/os/gproc/gproc_signal.go @@ -8,11 +8,12 @@ package gproc import ( "context" - "github.com/gogf/gf/v2/internal/intlog" "os" "os/signal" "sync" "syscall" + + "github.com/gogf/gf/v2/internal/intlog" ) // SigHandler defines a function type for signal handling. diff --git a/os/gres/gres_file.go b/os/gres/gres_file.go index ca46f0c19..c138d6455 100644 --- a/os/gres/gres_file.go +++ b/os/gres/gres_file.go @@ -9,9 +9,10 @@ package gres import ( "archive/zip" "bytes" - "github.com/gogf/gf/v2/internal/json" "io" "os" + + "github.com/gogf/gf/v2/internal/json" ) type File struct { diff --git a/os/gres/gres_func.go b/os/gres/gres_func.go index 56e75b74d..36a6b8455 100644 --- a/os/gres/gres_func.go +++ b/os/gres/gres_func.go @@ -11,6 +11,7 @@ import ( "bytes" "encoding/hex" "fmt" + "github.com/gogf/gf/v2/encoding/gbase64" "github.com/gogf/gf/v2/encoding/gcompress" "github.com/gogf/gf/v2/os/gfile" diff --git a/os/gres/gres_func_zip.go b/os/gres/gres_func_zip.go index a8011fb2a..18e8cf7ac 100644 --- a/os/gres/gres_func_zip.go +++ b/os/gres/gres_func_zip.go @@ -9,14 +9,15 @@ package gres import ( "archive/zip" "context" - "github.com/gogf/gf/v2/internal/fileinfo" - "github.com/gogf/gf/v2/internal/intlog" - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/text/gregex" "io" "os" "strings" "time" + + "github.com/gogf/gf/v2/internal/fileinfo" + "github.com/gogf/gf/v2/internal/intlog" + "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/text/gregex" ) // ZipPathWriter compresses `paths` to `writer` using zip compressing algorithm. diff --git a/os/gres/gres_http_file.go b/os/gres/gres_http_file.go index 62c5f56db..9a06c1cbd 100644 --- a/os/gres/gres_http_file.go +++ b/os/gres/gres_http_file.go @@ -11,7 +11,7 @@ import ( "os" ) -// Close implements Close interface of http.File. +// Close implements interface of http.File. func (f *File) Close() error { return nil } diff --git a/os/gres/gres_instance.go b/os/gres/gres_instance.go index 8becdaae3..e04dc4311 100644 --- a/os/gres/gres_instance.go +++ b/os/gres/gres_instance.go @@ -9,7 +9,7 @@ package gres import "github.com/gogf/gf/v2/container/gmap" const ( - // Default group name for instance usage. + // DefaultName default group name for instance usage. DefaultName = "default" ) diff --git a/os/gres/gres_resource.go b/os/gres/gres_resource.go index 7a6c35908..9c8547264 100644 --- a/os/gres/gres_resource.go +++ b/os/gres/gres_resource.go @@ -9,15 +9,14 @@ package gres import ( "context" "fmt" - "github.com/gogf/gf/v2/internal/intlog" "os" "path/filepath" "strings" - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/container/gtree" + "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/os/gtime" ) type Resource struct { diff --git a/os/gres/gres_z_unit_1_test.go b/os/gres/gres_z_unit_1_test.go deleted file mode 100644 index abd994a86..000000000 --- a/os/gres/gres_z_unit_1_test.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. -// -// This Source Code Form is subject to the terms of the MIT License. -// If a copy of the MIT was not distributed with this file, -// You can obtain one at https://github.com/gogf/gf. - -package gres_test - -import ( - "github.com/gogf/gf/v2/os/gtime" - "strings" - "testing" - - "github.com/gogf/gf/v2/os/gfile" - - "github.com/gogf/gf/v2/debug/gdebug" - "github.com/gogf/gf/v2/os/gres" - "github.com/gogf/gf/v2/test/gtest" -) - -func Test_PackToGoFile(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - srcPath := gdebug.TestDataPath("files") - goFilePath := gdebug.TestDataPath("testdata.go") - pkgName := "testdata" - err := gres.PackToGoFile(srcPath, goFilePath, pkgName) - t.Assert(err, nil) - }) -} - -func Test_Pack(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - srcPath := gdebug.TestDataPath("files") - data, err := gres.Pack(srcPath) - t.Assert(err, nil) - - r := gres.New() - - err = r.Add(string(data)) - t.Assert(err, nil) - t.Assert(r.Contains("files/"), true) - }) -} - -func Test_PackToFile(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - srcPath := gdebug.TestDataPath("files") - dstPath := gfile.TempDir(gtime.TimestampNanoStr()) - err := gres.PackToFile(srcPath, dstPath) - t.Assert(err, nil) - - defer gfile.Remove(dstPath) - - r := gres.New() - err = r.Load(dstPath) - t.Assert(err, nil) - t.Assert(r.Contains("files"), true) - }) -} - -func Test_PackMulti(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - srcPath := gdebug.TestDataPath("files") - goFilePath := gdebug.TestDataPath("data/data.go") - pkgName := "data" - array, err := gfile.ScanDir(srcPath, "*", false) - t.Assert(err, nil) - err = gres.PackToGoFile(strings.Join(array, ","), goFilePath, pkgName) - t.Assert(err, nil) - }) -} - -func Test_PackWithPrefix1(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - srcPath := gdebug.TestDataPath("files") - goFilePath := gfile.TempDir("testdata.go") - pkgName := "testdata" - err := gres.PackToGoFile(srcPath, goFilePath, pkgName, "www/gf-site/test") - t.Assert(err, nil) - }) -} - -func Test_PackWithPrefix2(t *testing.T) { - gtest.C(t, func(t *gtest.T) { - srcPath := gdebug.TestDataPath("files") - goFilePath := gfile.TempDir("testdata.go") - pkgName := "testdata" - err := gres.PackToGoFile(srcPath, goFilePath, pkgName, "/var/www/gf-site/test") - t.Assert(err, nil) - }) -} diff --git a/os/gres/gres_z_unit_2_test.go b/os/gres/gres_z_unit_test.go similarity index 62% rename from os/gres/gres_z_unit_2_test.go rename to os/gres/gres_z_unit_test.go index dd13a2120..06c61a1c6 100644 --- a/os/gres/gres_z_unit_2_test.go +++ b/os/gres/gres_z_unit_test.go @@ -7,16 +7,89 @@ package gres_test import ( - _ "github.com/gogf/gf/v2/os/gres/testdata/data" - + "strings" "testing" + "github.com/gogf/gf/v2/debug/gdebug" "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/test/gtest" - + "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/gres" + "github.com/gogf/gf/v2/os/gtime" + "github.com/gogf/gf/v2/test/gtest" ) +func Test_PackToGoFile(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + srcPath := gdebug.TestDataPath("files") + goFilePath := gdebug.TestDataPath("testdata.go") + pkgName := "testdata" + err := gres.PackToGoFile(srcPath, goFilePath, pkgName) + t.Assert(err, nil) + }) +} + +func Test_Pack(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + srcPath := gdebug.TestDataPath("files") + data, err := gres.Pack(srcPath) + t.Assert(err, nil) + + r := gres.New() + + err = r.Add(string(data)) + t.Assert(err, nil) + t.Assert(r.Contains("files/"), true) + }) +} + +func Test_PackToFile(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + srcPath := gdebug.TestDataPath("files") + dstPath := gfile.TempDir(gtime.TimestampNanoStr()) + err := gres.PackToFile(srcPath, dstPath) + t.Assert(err, nil) + + defer gfile.Remove(dstPath) + + r := gres.New() + err = r.Load(dstPath) + t.Assert(err, nil) + t.Assert(r.Contains("files"), true) + }) +} + +func Test_PackMulti(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + srcPath := gdebug.TestDataPath("files") + goFilePath := gdebug.TestDataPath("data/data.go") + pkgName := "data" + array, err := gfile.ScanDir(srcPath, "*", false) + t.Assert(err, nil) + err = gres.PackToGoFile(strings.Join(array, ","), goFilePath, pkgName) + t.Assert(err, nil) + }) +} + +func Test_PackWithPrefix1(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + srcPath := gdebug.TestDataPath("files") + goFilePath := gfile.TempDir("testdata.go") + pkgName := "testdata" + err := gres.PackToGoFile(srcPath, goFilePath, pkgName, "www/gf-site/test") + t.Assert(err, nil) + }) +} + +func Test_PackWithPrefix2(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + srcPath := gdebug.TestDataPath("files") + goFilePath := gfile.TempDir("testdata.go") + pkgName := "testdata" + err := gres.PackToGoFile(srcPath, goFilePath, pkgName, "/var/www/gf-site/test") + t.Assert(err, nil) + }) +} + func Test_Basic(t *testing.T) { gres.Dump() gtest.C(t, func(t *gtest.T) { diff --git a/os/grpool/grpool.go b/os/grpool/grpool.go index d463dd0ec..6aa97af04 100644 --- a/os/grpool/grpool.go +++ b/os/grpool/grpool.go @@ -9,11 +9,11 @@ package grpool import ( "context" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/container/glist" "github.com/gogf/gf/v2/container/gtype" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" ) // Func is the pool function which contains context parameter. diff --git a/os/grpool/grpool_bench_2_test.go b/os/grpool/grpool_bench_2_test.go deleted file mode 100644 index 1dc02e18f..000000000 --- a/os/grpool/grpool_bench_2_test.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. -// -// This Source Code Form is subject to the terms of the MIT License. -// If a copy of the MIT was not distributed with this file, -// You can obtain one at https://github.com/gogf/gf. - -// go test *.go -bench=".*" -count=1 - -package grpool_test - -import ( - "testing" - - "github.com/gogf/gf/v2/os/grpool" -) - -var n = 500000 - -func BenchmarkGrpool2(b *testing.B) { - b.N = n - for i := 0; i < b.N; i++ { - grpool.Add(ctx, increment) - } -} - -func BenchmarkGoroutine2(b *testing.B) { - b.N = n - for i := 0; i < b.N; i++ { - go increment(ctx) - } -} diff --git a/os/grpool/grpool_bench_1_test.go b/os/grpool/grpool_z_bench_test.go similarity index 74% rename from os/grpool/grpool_bench_1_test.go rename to os/grpool/grpool_z_bench_test.go index 7c576da97..411afb14f 100644 --- a/os/grpool/grpool_bench_1_test.go +++ b/os/grpool/grpool_z_bench_test.go @@ -17,6 +17,7 @@ import ( var ( ctx = context.TODO() + n = 500000 ) func increment(ctx context.Context) { @@ -35,3 +36,17 @@ func BenchmarkGoroutine_1(b *testing.B) { go increment(ctx) } } + +func BenchmarkGrpool2(b *testing.B) { + b.N = n + for i := 0; i < b.N; i++ { + grpool.Add(ctx, increment) + } +} + +func BenchmarkGoroutine2(b *testing.B) { + b.N = n + for i := 0; i < b.N; i++ { + go increment(ctx) + } +} diff --git a/os/grpool/grpool_unit_test.go b/os/grpool/grpool_z_unit_test.go similarity index 100% rename from os/grpool/grpool_unit_test.go rename to os/grpool/grpool_z_unit_test.go diff --git a/os/gsession/gsession_manager.go b/os/gsession/gsession_manager.go index 31116d785..192cb09a7 100644 --- a/os/gsession/gsession_manager.go +++ b/os/gsession/gsession_manager.go @@ -8,10 +8,10 @@ package gsession import ( "context" - "github.com/gogf/gf/v2/container/gmap" - "github.com/gogf/gf/v2/internal/intlog" "time" + "github.com/gogf/gf/v2/container/gmap" + "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/os/gcache" ) diff --git a/os/gsession/gsession_session.go b/os/gsession/gsession_session.go index be9ee9436..5db11ac7b 100644 --- a/os/gsession/gsession_session.go +++ b/os/gsession/gsession_session.go @@ -8,13 +8,13 @@ package gsession import ( "context" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/internal/intlog" "time" "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/container/gvar" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/intlog" ) // Session struct for storing single session data, which is bound to a single request. diff --git a/os/gsession/gsession_storage.go b/os/gsession/gsession_storage.go index 9e787c345..47459da35 100644 --- a/os/gsession/gsession_storage.go +++ b/os/gsession/gsession_storage.go @@ -8,8 +8,9 @@ package gsession import ( "context" - "github.com/gogf/gf/v2/container/gmap" "time" + + "github.com/gogf/gf/v2/container/gmap" ) // Storage is the interface definition for session storage. diff --git a/os/gsession/gsession_storage_file.go b/os/gsession/gsession_storage_file.go index 419af6724..c8a4d2877 100644 --- a/os/gsession/gsession_storage_file.go +++ b/os/gsession/gsession_storage_file.go @@ -8,24 +8,20 @@ package gsession import ( "context" + "os" + "time" + "github.com/gogf/gf/v2/container/gmap" + "github.com/gogf/gf/v2/container/gset" + "github.com/gogf/gf/v2/crypto/gaes" + "github.com/gogf/gf/v2/encoding/gbinary" "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/internal/json" - "os" - "time" - - "github.com/gogf/gf/v2/crypto/gaes" - - "github.com/gogf/gf/v2/os/gtimer" - - "github.com/gogf/gf/v2/container/gset" - "github.com/gogf/gf/v2/encoding/gbinary" - - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/os/gtime" + "github.com/gogf/gf/v2/os/gtimer" ) // StorageFile implements the Session Storage interface with file system. diff --git a/os/gsession/gsession_storage_memory.go b/os/gsession/gsession_storage_memory.go index b6db3f387..f34a50476 100644 --- a/os/gsession/gsession_storage_memory.go +++ b/os/gsession/gsession_storage_memory.go @@ -8,8 +8,9 @@ package gsession import ( "context" - "github.com/gogf/gf/v2/container/gmap" "time" + + "github.com/gogf/gf/v2/container/gmap" ) // StorageMemory implements the Session Storage interface with memory. diff --git a/os/gsession/gsession_storage_redis.go b/os/gsession/gsession_storage_redis.go index c7c64bd02..7f80f9f3d 100644 --- a/os/gsession/gsession_storage_redis.go +++ b/os/gsession/gsession_storage_redis.go @@ -8,12 +8,12 @@ package gsession import ( "context" + "time" + "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/database/gredis" "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/internal/json" - "time" - "github.com/gogf/gf/v2/os/gtimer" ) @@ -77,7 +77,7 @@ func (s *StorageRedis) Get(ctx context.Context, id string, key string) (value in return nil, ErrorDisabled } -// GetMap retrieves all key-value pairs as map from storage. +// Data retrieves all key-value pairs as map from storage. func (s *StorageRedis) Data(ctx context.Context, id string) (data map[string]interface{}, err error) { return nil, ErrorDisabled } @@ -135,9 +135,8 @@ func (s *StorageRedis) GetSession(ctx context.Context, id string, ttl time.Durat } if data == nil { return gmap.NewStrAnyMapFrom(m, true), nil - } else { - data.Replace(m) } + data.Replace(m) return data, nil } diff --git a/os/gsession/gsession_unit_storage_file_test.go b/os/gsession/gsession_z_unit_storage_file_test.go similarity index 100% rename from os/gsession/gsession_unit_storage_file_test.go rename to os/gsession/gsession_z_unit_storage_file_test.go index 5b2385215..3f2b75db0 100644 --- a/os/gsession/gsession_unit_storage_file_test.go +++ b/os/gsession/gsession_z_unit_storage_file_test.go @@ -8,11 +8,11 @@ package gsession_test import ( "context" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gsession" "testing" "time" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/os/gsession" "github.com/gogf/gf/v2/test/gtest" ) diff --git a/os/gsession/gsession_unit_storage_memory_test.go b/os/gsession/gsession_z_unit_storage_memory_test.go similarity index 100% rename from os/gsession/gsession_unit_storage_memory_test.go rename to os/gsession/gsession_z_unit_storage_memory_test.go index 237981486..02d55830e 100644 --- a/os/gsession/gsession_unit_storage_memory_test.go +++ b/os/gsession/gsession_z_unit_storage_memory_test.go @@ -8,11 +8,11 @@ package gsession_test import ( "context" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gsession" "testing" "time" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/os/gsession" "github.com/gogf/gf/v2/test/gtest" ) diff --git a/os/gsession/gsession_unit_storage_redis_hashtable_test.go b/os/gsession/gsession_z_unit_storage_redis_hashtable_test.go similarity index 100% rename from os/gsession/gsession_unit_storage_redis_hashtable_test.go rename to os/gsession/gsession_z_unit_storage_redis_hashtable_test.go index 7c243e779..22b5bdc44 100644 --- a/os/gsession/gsession_unit_storage_redis_hashtable_test.go +++ b/os/gsession/gsession_z_unit_storage_redis_hashtable_test.go @@ -8,12 +8,12 @@ package gsession_test import ( "context" - "github.com/gogf/gf/v2/database/gredis" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gsession" "testing" "time" + "github.com/gogf/gf/v2/database/gredis" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/os/gsession" "github.com/gogf/gf/v2/test/gtest" ) diff --git a/os/gsession/gsession_unit_storage_redis_test.go b/os/gsession/gsession_z_unit_storage_redis_test.go similarity index 100% rename from os/gsession/gsession_unit_storage_redis_test.go rename to os/gsession/gsession_z_unit_storage_redis_test.go index b6e3bb631..13461c55f 100644 --- a/os/gsession/gsession_unit_storage_redis_test.go +++ b/os/gsession/gsession_z_unit_storage_redis_test.go @@ -8,12 +8,12 @@ package gsession_test import ( "context" - "github.com/gogf/gf/v2/database/gredis" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gsession" "testing" "time" + "github.com/gogf/gf/v2/database/gredis" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/os/gsession" "github.com/gogf/gf/v2/test/gtest" ) diff --git a/os/gsession/gsession_unit_test.go b/os/gsession/gsession_z_unit_test.go similarity index 100% rename from os/gsession/gsession_unit_test.go rename to os/gsession/gsession_z_unit_test.go diff --git a/os/gspath/gspath.go b/os/gspath/gspath.go index b062ead2f..e0a986cfc 100644 --- a/os/gspath/gspath.go +++ b/os/gspath/gspath.go @@ -13,15 +13,15 @@ package gspath import ( "context" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/internal/intlog" "os" "sort" "strings" "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/container/gmap" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/text/gstr" ) @@ -53,7 +53,7 @@ func New(path string, cache bool) *SPath { } if len(path) > 0 { if _, err := sp.Add(path); err != nil { - //intlog.Print(err) + // intlog.Print(err) } } return sp @@ -143,7 +143,7 @@ func (sp *SPath) Add(path string) (realPath string, err error) { } // The added path must be a directory. if gfile.IsDir(realPath) { - //fmt.Println("gspath:", realPath, sp.paths.Search(realPath)) + // fmt.Println("gspath:", realPath, sp.paths.Search(realPath)) // It will not add twice for the same directory. if sp.paths.Search(realPath) < 0 { realPath = strings.TrimRight(realPath, gfile.Separator) diff --git a/os/gspath/gspath_unit_test.go b/os/gspath/gspath_z_unit_test.go similarity index 100% rename from os/gspath/gspath_unit_test.go rename to os/gspath/gspath_z_unit_test.go diff --git a/os/gtime/gtime.go b/os/gtime/gtime.go index 92240fbbc..d4d5a9877 100644 --- a/os/gtime/gtime.go +++ b/os/gtime/gtime.go @@ -11,15 +11,15 @@ package gtime import ( "fmt" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/internal/utils" "os" "regexp" "strconv" "strings" "time" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/utils" "github.com/gogf/gf/v2/text/gregex" ) @@ -231,19 +231,19 @@ func StrToTime(str string, format ...string) (*Time, error) { local = time.Local ) if match = timeRegex1.FindStringSubmatch(str); len(match) > 0 && match[1] != "" { - //for k, v := range match { + // for k, v := range match { // match[k] = strings.TrimSpace(v) - //} + // } year, month, day = parseDateStr(match[1]) } else if match = timeRegex2.FindStringSubmatch(str); len(match) > 0 && match[1] != "" { - //for k, v := range match { + // for k, v := range match { // match[k] = strings.TrimSpace(v) - //} + // } year, month, day = parseDateStr(match[1]) } else if match = timeRegex3.FindStringSubmatch(str); len(match) > 0 && match[1] != "" { - //for k, v := range match { + // for k, v := range match { // match[k] = strings.TrimSpace(v) - //} + // } s := strings.Replace(match[2], ":", "", -1) if len(s) < 6 { s += strings.Repeat("0", 6-len(s)) diff --git a/os/gtime/gtime_time.go b/os/gtime/gtime_time.go index 4c92dad3e..7e28fe324 100644 --- a/os/gtime/gtime_time.go +++ b/os/gtime/gtime_time.go @@ -8,10 +8,11 @@ package gtime import ( "bytes" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" "strconv" "time" + + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" ) // Time is a wrapper for time.Time for additional features. diff --git a/os/gtime/gtime_z_example_basic_test.go b/os/gtime/gtime_z_example_basic_test.go new file mode 100644 index 000000000..3d3ba6c92 --- /dev/null +++ b/os/gtime/gtime_z_example_basic_test.go @@ -0,0 +1,253 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +package gtime_test + +import ( + "fmt" + + "github.com/gogf/gf/v2/os/gtime" +) + +// New creates and returns a Time object with given parameter. +// The optional parameter can be type of: time.Time/*time.Time, string or integer. +func ExampleSetTimeZone() { + gtime.SetTimeZone("Asia/Shanghai") + fmt.Println(gtime.Datetime()) + + gtime.SetTimeZone("Asia/Tokyo") + fmt.Println(gtime.Datetime()) + // May Output: + // 2018-08-08 08:08:08 + // 2018-08-08 09:08:08 +} + +func ExampleTimestamp() { + fmt.Println(gtime.Timestamp()) + + // May Output: + // 1636359252 +} + +func ExampleTimestampMilli() { + fmt.Println(gtime.TimestampMilli()) + + // May Output: + // 1636359252000 +} + +func ExampleTimestampMicro() { + fmt.Println(gtime.TimestampMicro()) + + // May Output: + // 1636359252000000 +} + +func ExampleTimestampNano() { + fmt.Println(gtime.TimestampNano()) + + // May Output: + // 1636359252000000000 +} + +func ExampleTimestampStr() { + fmt.Println(gtime.TimestampStr()) + + // May Output: + // 1636359252 +} + +func ExampleDate() { + fmt.Println(gtime.Date()) + + // May Output: + // 2006-01-02 +} + +func ExampleDatetime() { + fmt.Println(gtime.Datetime()) + + // May Output: + // 2006-01-02 15:04:05 +} + +func ExampleISO8601() { + fmt.Println(gtime.ISO8601()) + + // May Output: + // 2006-01-02T15:04:05-07:00 +} + +func ExampleRFC822() { + fmt.Println(gtime.RFC822()) + + // May Output: + // Mon, 02 Jan 06 15:04 MST +} + +func ExampleStrToTime() { + res, _ := gtime.StrToTime("2006-01-02T15:04:05-07:00", "Y-m-d H:i:s") + fmt.Println(res) + + // May Output: + // 2006-01-02 15:04:05 +} + +func ExampleConvertZone() { + res, _ := gtime.ConvertZone("2006-01-02 15:04:05", "Asia/Tokyo", "Asia/Shanghai") + fmt.Println(res) + + // Output: + // 2006-01-02 16:04:05 +} + +func ExampleStrToTimeFormat() { + res, _ := gtime.StrToTimeFormat("2006-01-02 15:04:05", "Y-m-d H:i:s") + fmt.Println(res) + + // Output: + // 2006-01-02 15:04:05 +} + +func ExampleStrToTimeLayout() { + res, _ := gtime.StrToTimeLayout("2018-08-08", "2006-01-02") + fmt.Println(res) + + // Output: + // 2018-08-08 00:00:00 +} + +// ParseDuration parses a duration string. +// A duration string is a possibly signed sequence of +// decimal numbers, each with optional fraction and a unit suffix, +// such as "300ms", "-1.5h", "1d" or "2h45m". +// Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h", "d". +// +// Very note that it supports unit "d" more than function time.ParseDuration. +func ExampleParseDuration() { + res, _ := gtime.ParseDuration("+10h") + fmt.Println(res) + + // Output: + // 10h0m0s +} + +func ExampleTime_Format() { + gt1 := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt1.Format("Y-m-d")) + fmt.Println(gt1.Format("l")) + fmt.Println(gt1.Format("F j, Y, g:i a")) + fmt.Println(gt1.Format("j, n, Y")) + fmt.Println(gt1.Format("h-i-s, j-m-y, it is w Day z")) + fmt.Println(gt1.Format("D M j G:i:s T Y")) + + // Output: + // 2018-08-08 + // Wednesday + // August 8, 2018, 8:08 am + // 8, 8, 2018 + // 08-08-08, 8-08-18, 0831 0808 3 Wedam18 219 + // Wed Aug 8 8:08:08 CST 2018 +} + +func ExampleTime_FormatNew() { + gt1 := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt1.FormatNew("Y-m-d")) + fmt.Println(gt1.FormatNew("Y-m-d H:i")) + + // Output: + // 2018-08-08 00:00:00 + // 2018-08-08 08:08:00 +} + +func ExampleTime_FormatTo() { + gt1 := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt1.FormatTo("Y-m-d")) + + // Output: + // 2018-08-08 00:00:00 +} + +func ExampleTime_Layout() { + gt1 := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt1.Layout("2006-01-02")) + + // Output: + // 2018-08-08 +} + +func ExampleTime_LayoutNew() { + gt1 := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt1.LayoutNew("2006-01-02")) + + // Output: + // 2018-08-08 00:00:00 +} + +func ExampleTime_LayoutTo() { + gt1 := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt1.LayoutTo("2006-01-02")) + + // Output: + // 2018-08-08 00:00:00 +} + +func ExampleTime_IsLeapYear() { + gt1 := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt1.IsLeapYear()) + + // Output: + // false +} + +func ExampleTime_DayOfYear() { + gt1 := gtime.New("2018-01-08 08:08:08") + + fmt.Println(gt1.DayOfYear()) + + // Output: + // 7 +} + +// DaysInMonth returns the day count of current month. +func ExampleTime_DaysInMonth() { + gt1 := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt1.DaysInMonth()) + + // Output: + // 31 +} + +// WeeksOfYear returns the point of current week for the year. +func ExampleTime_WeeksOfYear() { + gt1 := gtime.New("2018-01-08 08:08:08") + + fmt.Println(gt1.WeeksOfYear()) + + // Output: + // 2 +} + +func ExampleTime_ToZone() { + gt1 := gtime.Now() + gt2, _ := gt1.ToZone("Asia/Shanghai") + gt3, _ := gt1.ToZone("Asia/Tokyo") + + fmt.Println(gt2) + fmt.Println(gt3) + + // May Output: + // 2021-11-11 17:10:10 + // 2021-11-11 18:10:10 +} diff --git a/os/gtime/gtime_z_example_time_test.go b/os/gtime/gtime_z_example_time_test.go new file mode 100644 index 000000000..0ac899256 --- /dev/null +++ b/os/gtime/gtime_z_example_time_test.go @@ -0,0 +1,477 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +package gtime_test + +import ( + "fmt" + "reflect" + "time" + + "github.com/gogf/gf/v2/os/gtime" +) + +// New creates and returns a Time object with given parameter. +// The optional parameter can be type of: time.Time/*time.Time, string or integer. +func ExampleNew() { + curTime := "2018-08-08 08:08:08" + timer, _ := time.Parse("2006-01-02 15:04:05", curTime) + t1 := gtime.New(&timer) + t2 := gtime.New(curTime) + t3 := gtime.New(curTime, "Y-m-d H:i:s") + t4 := gtime.New(curTime) + t5 := gtime.New(1533686888) + + fmt.Println(t1) + fmt.Println(t2) + fmt.Println(t3) + fmt.Println(t4) + fmt.Println(t5) + + // Output: + // 2018-08-08 08:08:08 + // 2018-08-08 08:08:08 + // 2018-08-08 08:08:08 + // 2018-08-08 08:08:08 + // 2018-08-08 08:08:08 +} + +// Now creates and returns a time object of now. +func ExampleNow() { + t := gtime.Now() + fmt.Println(t) + + // May Output: + // 2021-11-06 13:41:08 +} + +// NewFromTime creates and returns a Time object with given time.Time object. +func ExampleNewFromTime() { + timer, _ := time.Parse("2006-01-02 15:04:05", "2018-08-08 08:08:08") + nTime := gtime.NewFromTime(timer) + + fmt.Println(nTime) + + // Output: + // 2018-08-08 08:08:08 +} + +// NewFromStr creates and returns a Time object with given string. +// Note that it returns nil if there's error occurs. +func ExampleNewFromStr() { + t := gtime.NewFromStr("2018-08-08 08:08:08") + + fmt.Println(t) + + // Output: + // 2018-08-08 08:08:08 +} + +// NewFromStrFormat creates and returns a Time object with given string and +// custom format like: Y-m-d H:i:s. +// Note that it returns nil if there's error occurs. +func ExampleNewFromStrFormat() { + t := gtime.NewFromStrFormat("2018-08-08 08:08:08", "Y-m-d H:i:s") + fmt.Println(t) + + // Output: + // 2018-08-08 08:08:08 +} + +// NewFromStrLayout creates and returns a Time object with given string and +// stdlib layout like: 2006-01-02 15:04:05. +// Note that it returns nil if there's error occurs. +func ExampleNewFromStrLayout() { + t := gtime.NewFromStrLayout("2018-08-08 08:08:08", "2006-01-02 15:04:05") + fmt.Println(t) + + // Output: + // 2018-08-08 08:08:08 +} + +// NewFromTimeStamp creates and returns a Time object with given timestamp, +// which can be in seconds to nanoseconds. +// Eg: 1600443866 and 1600443866199266000 are both considered as valid timestamp number. +func ExampleNewFromTimeStamp() { + t1 := gtime.NewFromTimeStamp(1533686888) + t2 := gtime.NewFromTimeStamp(1533686888000) + + fmt.Println(t1.String() == t2.String()) + fmt.Println(t1) + + // Output: + // true + // 2018-08-08 08:08:08 +} + +// Timestamp returns the timestamp in seconds. +func ExampleTime_Timestamp() { + t := gtime.Timestamp() + + fmt.Println(t) + + // May output: + // 1533686888 +} + +// Timestamp returns the timestamp in milliseconds. +func ExampleTime_TimestampMilli() { + t := gtime.TimestampMilli() + + fmt.Println(t) + + // May output: + // 1533686888000 +} + +// Timestamp returns the timestamp in microseconds. +func ExampleTime_TimestampMicro() { + t := gtime.TimestampMicro() + + fmt.Println(t) + + // May output: + // 1533686888000000 +} + +// Timestamp returns the timestamp in nanoseconds. +func ExampleTime_TimestampNano() { + t := gtime.TimestampNano() + + fmt.Println(t) + + // May output: + // 1533686888000000 +} + +// TimestampStr is a convenience method which retrieves and returns +// the timestamp in seconds as string. +func ExampleTime_TimestampStr() { + t := gtime.TimestampStr() + + fmt.Println(reflect.TypeOf(t)) + + // Output: + // string +} + +// Month returns the month of the year specified by t. +func ExampleTime_Month() { + gt := gtime.New("2018-08-08 08:08:08") + t1 := gt.Month() + + fmt.Println(t1) + + // Output: + // 8 +} + +// Second returns the second offset within the minute specified by t, +// in the range [0, 59]. +func ExampleTime_Second() { + gt := gtime.New("2018-08-08 08:08:08") + t1 := gt.Second() + + fmt.Println(t1) + + // Output: + // 8 +} + +// String returns current time object as string. +func ExampleTime_String() { + gt := gtime.New("2018-08-08 08:08:08") + t1 := gt.String() + + fmt.Println(t1) + fmt.Println(reflect.TypeOf(t1)) + + // Output: + // 2018-08-08 08:08:08 + // string +} + +// IsZero reports whether t represents the zero time instant, +// January 1, year 1, 00:00:00 UTC. +func ExampleTime_IsZero() { + gt := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt.IsZero()) + + // Output: + // false +} + +// Add adds the duration to current time. +func ExampleTime_Add() { + gt := gtime.New("2018-08-08 08:08:08") + gt1 := gt.Add(time.Duration(10) * time.Second) + + fmt.Println(gt1) + + // Output: + // 2018-08-08 08:08:18 +} + +// AddStr parses the given duration as string and adds it to current time. +// Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". +func ExampleTime_AddStr() { + gt := gtime.New("2018-08-08 08:08:08") + gt1, _ := gt.AddStr("10s") + + fmt.Println(gt1) + + // Output: + // 2018-08-08 08:08:18 +} + +// AddDate adds year, month and day to the time. +func ExampleTime_AddDate() { + var ( + year = 1 + month = 2 + day = 3 + ) + gt := gtime.New("2018-08-08 08:08:08") + gt = gt.AddDate(year, month, day) + + fmt.Println(gt) + + // Output: + // 2019-10-11 08:08:08 +} + +// Round returns the result of rounding t to the nearest multiple of d (since the zero time). +// The rounding behavior for halfway values is to round up. +// If d <= 0, Round returns t stripped of any monotonic clock reading but otherwise unchanged. +// +// Round operates on the time as an absolute duration since the +// zero time; it does not operate on the presentation form of the +// time. Thus, Round(Hour) may return a time with a non-zero +// minute, depending on the time's Location. +func ExampleTime_Round() { + gt := gtime.New("2018-08-08 08:08:08") + t := gt.Round(time.Duration(10) * time.Second) + + fmt.Println(t) + + // Output: + // 2018-08-08 08:08:10 +} + +// Truncate returns the result of rounding t down to a multiple of d (since the zero time). +// If d <= 0, Truncate returns t stripped of any monotonic clock reading but otherwise unchanged. +// +// Truncate operates on the time as an absolute duration since the +// zero time; it does not operate on the presentation form of the +// time. Thus, Truncate(Hour) may return a time with a non-zero +// minute, depending on the time's Location. +func ExampleTime_Truncate() { + gt := gtime.New("2018-08-08 08:08:08") + t := gt.Truncate(time.Duration(10) * time.Second) + + fmt.Println(t) + + // Output: + // 2018-08-08 08:08:00 +} + +// Equal reports whether t and u represent the same time instant. +// Two times can be equal even if they are in different locations. +// For example, 6:00 +0200 CEST and 4:00 UTC are Equal. +// See the documentation on the Time type for the pitfalls of using == with +// Time values; most code should use Equal instead. +func ExampleTime_Equal() { + gt1 := gtime.New("2018-08-08 08:08:08") + gt2 := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt1.Equal(gt2)) + + // Output: + // true +} + +// Before reports whether the time instant t is before u. +func ExampleTime_Before() { + gt1 := gtime.New("2018-08-07") + gt2 := gtime.New("2018-08-08") + + fmt.Println(gt1.Before(gt2)) + + // Output: + // true +} + +// After reports whether the time instant t is after u. +func ExampleTime_After() { + gt1 := gtime.New("2018-08-07") + gt2 := gtime.New("2018-08-08") + + fmt.Println(gt1.After(gt2)) + + // Output: + // false +} + +// Sub returns the duration t-u. If the result exceeds the maximum (or minimum) +// value that can be stored in a Duration, the maximum (or minimum) duration +// will be returned. +// To compute t-d for a duration d, use t.Add(-d). +func ExampleTime_Sub() { + gt1 := gtime.New("2018-08-08 08:08:08") + gt2 := gtime.New("2018-08-08 08:08:10") + + fmt.Println(gt2.Sub(gt1)) + + // Output: + // 2s +} + +// StartOfMinute clones and returns a new time of which the seconds is set to 0. +func ExampleTime_StartOfMinute() { + gt1 := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt1.StartOfMinute()) + + // Output: + // 2018-08-08 08:08:00 +} + +func ExampleTime_StartOfHour() { + gt1 := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt1.StartOfHour()) + + // Output: + // 2018-08-08 08:00:00 +} + +func ExampleTime_StartOfDay() { + gt1 := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt1.StartOfDay()) + + // Output: + // 2018-08-08 00:00:00 +} + +func ExampleTime_StartOfWeek() { + gt1 := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt1.StartOfWeek()) + + // Output: + // 2018-08-05 00:00:00 +} + +func ExampleTime_StartOfQuarter() { + gt1 := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt1.StartOfQuarter()) + + // Output: + // 2018-07-01 00:00:00 +} + +func ExampleTime_StartOfHalf() { + gt1 := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt1.StartOfHalf()) + + // Output: + // 2018-07-01 00:00:00 +} + +func ExampleTime_StartOfYear() { + gt1 := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt1.StartOfYear()) + + // Output: + // 2018-01-01 00:00:00 +} + +func ExampleTime_EndOfMinute() { + gt1 := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt1.EndOfMinute()) + + // Output: + // 2018-08-08 08:08:59 +} + +func ExampleTime_EndOfHour() { + gt1 := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt1.EndOfHour()) + + // Output: + // 2018-08-08 08:59:59 +} + +func ExampleTime_EndOfDay() { + gt1 := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt1.EndOfDay()) + + // Output: + // 2018-08-08 23:59:59 +} + +func ExampleTime_EndOfWeek() { + gt1 := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt1.EndOfWeek()) + + // Output: + // 2018-08-11 23:59:59 +} + +func ExampleTime_EndOfMonth() { + gt1 := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt1.EndOfMonth()) + + // Output: + // 2018-08-31 23:59:59 +} + +func ExampleTime_EndOfQuarter() { + gt1 := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt1.EndOfQuarter()) + + // Output: + // 2018-09-30 23:59:59 +} + +func ExampleTime_EndOfHalf() { + gt1 := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt1.EndOfHalf()) + + // Output: + // 2018-12-31 23:59:59 +} + +func ExampleTime_EndOfYear() { + gt1 := gtime.New("2018-08-08 08:08:08") + + fmt.Println(gt1.EndOfYear()) + + // Output: + // 2018-12-31 23:59:59 +} + +func ExampleTime_MarshalJSON() { + gt1 := gtime.New("2018-08-08 08:08:08") + + json, _ := gt1.MarshalJSON() + fmt.Println(string(json)) + + // Output: + // "2018-08-08 08:08:08" +} diff --git a/os/gtime/gtime_z_unit_json_test.go b/os/gtime/gtime_z_unit_feature_json_test.go similarity index 99% rename from os/gtime/gtime_z_unit_json_test.go rename to os/gtime/gtime_z_unit_feature_json_test.go index 490a4e54e..1704ff926 100644 --- a/os/gtime/gtime_z_unit_json_test.go +++ b/os/gtime/gtime_z_unit_feature_json_test.go @@ -7,10 +7,11 @@ package gtime_test import ( + "testing" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" - "testing" ) func Test_Json_Pointer(t *testing.T) { diff --git a/os/gtime/gtime_z_unit_sql_test.go b/os/gtime/gtime_z_unit_feature_sql_test.go similarity index 92% rename from os/gtime/gtime_z_unit_sql_test.go rename to os/gtime/gtime_z_unit_feature_sql_test.go index 332dd1fdc..b4133daad 100644 --- a/os/gtime/gtime_z_unit_sql_test.go +++ b/os/gtime/gtime_z_unit_feature_sql_test.go @@ -1,23 +1,24 @@ package gtime_test import ( + "testing" + "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" - "testing" ) func TestTime_Scan(t1 *testing.T) { gtest.C(t1, func(t *gtest.T) { tt := gtime.Time{} - //test string + // test string s := gtime.Now().String() t.Assert(tt.Scan(s), nil) t.Assert(tt.String(), s) - //test nano + // test nano n := gtime.TimestampNano() t.Assert(tt.Scan(n), nil) t.Assert(tt.TimestampNano(), n) - //test nil + // test nil none := (*gtime.Time)(nil) t.Assert(none.Scan(nil), nil) t.Assert(none, nil) @@ -31,7 +32,7 @@ func TestTime_Value(t1 *testing.T) { s, err := tt.Value() t.Assert(err, nil) t.Assert(s, tt.Time) - //test nil + // test nil none := (*gtime.Time)(nil) s, err = none.Value() t.Assert(err, nil) diff --git a/os/gtime/gtime_z_unit_basic_test.go b/os/gtime/gtime_z_unit_test.go similarity index 95% rename from os/gtime/gtime_z_unit_basic_test.go rename to os/gtime/gtime_z_unit_test.go index f3ca948d6..a65635507 100644 --- a/os/gtime/gtime_z_unit_basic_test.go +++ b/os/gtime/gtime_z_unit_test.go @@ -7,10 +7,10 @@ package gtime_test import ( - "github.com/gogf/gf/v2/frame/g" "testing" "time" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" ) @@ -18,7 +18,7 @@ import ( func Test_SetTimeZone(t *testing.T) { gtest.C(t, func(t *gtest.T) { t.Assert(gtime.SetTimeZone("Asia/Shanghai"), nil) - //t.Assert(time.Local.String(), "Asia/Shanghai") + // t.Assert(time.Local.String(), "Asia/Shanghai") }) } @@ -174,7 +174,7 @@ func Test_StrToTime(t *testing.T) { } } - //test err + // test err _, err := gtime.StrToTime("2006-01-02 15:04:05", "aabbccdd") if err == nil { t.Error("test fail") @@ -184,44 +184,44 @@ func Test_StrToTime(t *testing.T) { func Test_ConvertZone(t *testing.T) { gtest.C(t, func(t *gtest.T) { - //现行时间 + // 现行时间 nowUTC := time.Now().UTC() testZone := "America/Los_Angeles" - //转换为洛杉矶时间 + // 转换为洛杉矶时间 t1, err := gtime.ConvertZone(nowUTC.Format("2006-01-02 15:04:05"), testZone, "") if err != nil { t.Error("test fail") } - //使用洛杉矶时区解析上面转换后的时间 + // 使用洛杉矶时区解析上面转换后的时间 laStr := t1.Time.Format("2006-01-02 15:04:05") loc, err := time.LoadLocation(testZone) t2, err := time.ParseInLocation("2006-01-02 15:04:05", laStr, loc) - //判断是否与现行时间匹配 + // 判断是否与现行时间匹配 t.Assert(t2.UTC().Unix(), nowUTC.Unix()) }) - //test err + // test err gtest.C(t, func(t *gtest.T) { - //现行时间 + // 现行时间 nowUTC := time.Now().UTC() - //t.Log(nowUTC.Unix()) + // t.Log(nowUTC.Unix()) testZone := "errZone" - //错误时间输入 + // 错误时间输入 _, err := gtime.ConvertZone(nowUTC.Format("06..02 15:04:05"), testZone, "") if err == nil { t.Error("test fail") } - //错误时区输入 + // 错误时区输入 _, err = gtime.ConvertZone(nowUTC.Format("2006-01-02 15:04:05"), testZone, "") if err == nil { t.Error("test fail") } - //错误时区输入 + // 错误时区输入 _, err = gtime.ConvertZone(nowUTC.Format("2006-01-02 15:04:05"), testZone, testZone) if err == nil { t.Error("test fail") @@ -269,7 +269,7 @@ func Test_ParseTimeFromContent(t *testing.T) { timeTemp2 := gtime.ParseTimeFromContent("我是中文02.jan.2006 15:04:05我也是中文") t.Assert(timeTemp2.Time.Format("2006-01-02 15:04:05"), "2006-01-02 15:04:05") - //test err + // test err timeTempErr := gtime.ParseTimeFromContent("我是中文", "Y-m-d H:i:s") if timeTempErr != nil { t.Error("test fail") diff --git a/os/gtimer/gtimer.go b/os/gtimer/gtimer.go index 6d543c90a..f2af5133a 100644 --- a/os/gtimer/gtimer.go +++ b/os/gtimer/gtimer.go @@ -20,10 +20,10 @@ package gtimer import ( "context" - "github.com/gogf/gf/v2/container/gtype" "sync" "time" + "github.com/gogf/gf/v2/container/gtype" "github.com/gogf/gf/v2/os/gcmd" ) diff --git a/os/gtimer/gtimer_entry.go b/os/gtimer/gtimer_entry.go index 9f645a4d9..98f85f6d0 100644 --- a/os/gtimer/gtimer_entry.go +++ b/os/gtimer/gtimer_entry.go @@ -8,6 +8,7 @@ package gtimer import ( "context" + "github.com/gogf/gf/v2/container/gtype" ) diff --git a/os/gtimer/gtimer_queue.go b/os/gtimer/gtimer_queue.go index 1a1577da8..08fdd46f3 100644 --- a/os/gtimer/gtimer_queue.go +++ b/os/gtimer/gtimer_queue.go @@ -8,9 +8,10 @@ package gtimer import ( "container/heap" - "github.com/gogf/gf/v2/container/gtype" "math" "sync" + + "github.com/gogf/gf/v2/container/gtype" ) // priorityQueue is an abstract data type similar to a regular queue or stack data structure in which diff --git a/os/gtimer/gtimer_timer.go b/os/gtimer/gtimer_timer.go index 385883f65..88859f935 100644 --- a/os/gtimer/gtimer_timer.go +++ b/os/gtimer/gtimer_timer.go @@ -8,8 +8,9 @@ package gtimer import ( "context" - "github.com/gogf/gf/v2/container/gtype" "time" + + "github.com/gogf/gf/v2/container/gtype" ) func New(options ...TimerOptions) *Timer { diff --git a/os/gtimer/gtimer_z_unit_timer_internal_test.go b/os/gtimer/gtimer_z_unit_internal_test.go similarity index 99% rename from os/gtimer/gtimer_z_unit_timer_internal_test.go rename to os/gtimer/gtimer_z_unit_internal_test.go index 5748cf908..fda89b155 100644 --- a/os/gtimer/gtimer_z_unit_timer_internal_test.go +++ b/os/gtimer/gtimer_z_unit_internal_test.go @@ -8,10 +8,11 @@ package gtimer import ( "context" - "github.com/gogf/gf/v2/container/garray" - "github.com/gogf/gf/v2/test/gtest" "testing" "time" + + "github.com/gogf/gf/v2/container/garray" + "github.com/gogf/gf/v2/test/gtest" ) func TestTimer_Proceed(t *testing.T) { diff --git a/os/gtimer/gtimer_z_unit_api_test.go b/os/gtimer/gtimer_z_unit_test.go similarity index 100% rename from os/gtimer/gtimer_z_unit_api_test.go rename to os/gtimer/gtimer_z_unit_test.go diff --git a/os/gview/gview.go b/os/gview/gview.go index 3d9848d74..47a0f8a8c 100644 --- a/os/gview/gview.go +++ b/os/gview/gview.go @@ -12,11 +12,11 @@ package gview import ( "context" - "github.com/gogf/gf/v2/container/gmap" - "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2" "github.com/gogf/gf/v2/container/garray" + "github.com/gogf/gf/v2/container/gmap" + "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/os/gcmd" "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/glog" diff --git a/os/gview/gview_buildin.go b/os/gview/gview_buildin.go index 3da297f9a..2728b76ed 100644 --- a/os/gview/gview_buildin.go +++ b/os/gview/gview_buildin.go @@ -9,17 +9,16 @@ package gview import ( "context" "fmt" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/util/gutil" + htmltpl "html/template" "strings" "github.com/gogf/gf/v2/encoding/ghtml" "github.com/gogf/gf/v2/encoding/gurl" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" - - htmltpl "html/template" + "github.com/gogf/gf/v2/util/gutil" ) // buildInFuncDump implements build-in template function: dump diff --git a/os/gview/gview_config.go b/os/gview/gview_config.go index 25cc2aa77..d00beb5c7 100644 --- a/os/gview/gview_config.go +++ b/os/gview/gview_config.go @@ -8,6 +8,7 @@ package gview import ( "context" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/i18n/gi18n" @@ -146,7 +147,7 @@ func (view *View) SetPath(path string) error { view.paths.Clear() view.paths.Append(realPath) view.fileCacheMap.Clear() - //glog.Debug("[gview] SetPath:", realPath) + // glog.Debug("[gview] SetPath:", realPath) return nil } diff --git a/os/gview/gview_i18n.go b/os/gview/gview_i18n.go index d406ed118..7b3f93cf7 100644 --- a/os/gview/gview_i18n.go +++ b/os/gview/gview_i18n.go @@ -8,6 +8,7 @@ package gview import ( "context" + "github.com/gogf/gf/v2/i18n/gi18n" "github.com/gogf/gf/v2/util/gconv" ) diff --git a/os/gview/gview_instance.go b/os/gview/gview_instance.go index 5f61fdc34..9670b4a56 100644 --- a/os/gview/gview_instance.go +++ b/os/gview/gview_instance.go @@ -9,7 +9,7 @@ package gview import "github.com/gogf/gf/v2/container/gmap" const ( - // Default group name for instance usage. + // DefaultName Default group name for instance usage. DefaultName = "default" ) diff --git a/os/gview/gview_parse.go b/os/gview/gview_parse.go index f060f951f..3fadb3d24 100644 --- a/os/gview/gview_parse.go +++ b/os/gview/gview_parse.go @@ -10,6 +10,11 @@ import ( "bytes" "context" "fmt" + htmltpl "html/template" + "strconv" + "strings" + texttpl "text/template" + "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/encoding/ghash" "github.com/gogf/gf/v2/errors/gcode" @@ -23,10 +28,6 @@ import ( "github.com/gogf/gf/v2/os/gspath" "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gutil" - htmltpl "html/template" - "strconv" - "strings" - texttpl "text/template" ) const ( diff --git a/os/gview/gview_unit_config_test.go b/os/gview/gview_z_unit_config_test.go similarity index 99% rename from os/gview/gview_unit_config_test.go rename to os/gview/gview_z_unit_config_test.go index 0da2cfa82..ea70d0a08 100644 --- a/os/gview/gview_unit_config_test.go +++ b/os/gview/gview_z_unit_config_test.go @@ -8,11 +8,12 @@ package gview_test import ( "context" + "testing" + "github.com/gogf/gf/v2/debug/gdebug" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gview" "github.com/gogf/gf/v2/test/gtest" - "testing" ) func Test_Config(t *testing.T) { diff --git a/os/gview/gview_unit_encode_test.go b/os/gview/gview_z_unit_feature_encode_test.go similarity index 99% rename from os/gview/gview_unit_encode_test.go rename to os/gview/gview_z_unit_feature_encode_test.go index 6e20b9af2..dc7913de5 100644 --- a/os/gview/gview_unit_encode_test.go +++ b/os/gview/gview_z_unit_feature_encode_test.go @@ -8,12 +8,13 @@ package gview_test import ( "context" + "testing" + "github.com/gogf/gf/v2/debug/gdebug" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/gview" "github.com/gogf/gf/v2/test/gtest" - "testing" ) func Test_Encode_Parse(t *testing.T) { diff --git a/os/gview/gview_unit_i18n_test.go b/os/gview/gview_z_unit_i18n_test.go similarity index 99% rename from os/gview/gview_unit_i18n_test.go rename to os/gview/gview_z_unit_i18n_test.go index 35fe0431c..58c1c27d5 100644 --- a/os/gview/gview_unit_i18n_test.go +++ b/os/gview/gview_z_unit_i18n_test.go @@ -11,9 +11,8 @@ import ( "testing" "github.com/gogf/gf/v2/debug/gdebug" - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/test/gtest" ) diff --git a/os/gview/gview_unit_basic_test.go b/os/gview/gview_z_unit_test.go similarity index 99% rename from os/gview/gview_unit_basic_test.go rename to os/gview/gview_z_unit_test.go index 8f5cac4f6..6311f7ad7 100644 --- a/os/gview/gview_unit_basic_test.go +++ b/os/gview/gview_z_unit_test.go @@ -8,21 +8,21 @@ package gview_test import ( "context" - "github.com/gogf/gf/v2/encoding/ghtml" - "github.com/gogf/gf/v2/os/gctx" - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/util/gconv" "io/ioutil" "os" "strings" "testing" "time" + "github.com/gogf/gf/v2/encoding/ghtml" "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/os/gctx" "github.com/gogf/gf/v2/os/gfile" + "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/os/gview" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/text/gstr" + "github.com/gogf/gf/v2/util/gconv" ) func init() { @@ -45,13 +45,13 @@ func Test_Basic(t *testing.T) { t.Assert(err != nil, false) t.Assert(result, "hello gf,version:1.7.0;hello gf,version:1.7.0;that's all") - //测试api方法 + // 测试api方法 str = `hello {{.name}}` result, err = gview.ParseContent(context.TODO(), str, g.Map{"name": "gf"}) t.Assert(err != nil, false) t.Assert(result, "hello gf") - //测试instance方法 + // 测试instance方法 result, err = gview.Instance().ParseContent(context.TODO(), str, g.Map{"name": "gf"}) t.Assert(err != nil, false) t.Assert(result, "hello gf") @@ -224,7 +224,7 @@ func Test_FuncInclude(t *testing.T) { templatePath := gfile.Pwd() + gfile.Separator + "template" gfile.Mkdir(templatePath) defer gfile.Remove(templatePath) - //headerFile, _ := gfile.Create(templatePath + gfile.Separator + "header.html") + // headerFile, _ := gfile.Create(templatePath + gfile.Separator + "header.html") err := ioutil.WriteFile(templatePath+gfile.Separator+"header.html", []byte(header), 0644) if err != nil { t.Error(err) diff --git a/protocol/goai/goai.go b/protocol/goai/goai.go index 1f9036c57..58158e462 100644 --- a/protocol/goai/goai.go +++ b/protocol/goai/goai.go @@ -12,12 +12,13 @@ package goai import ( "context" "fmt" + "reflect" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/intlog" "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/text/gstr" - "reflect" ) // OpenApiV3 is the structure defined from: @@ -82,6 +83,7 @@ const ( TagNameMethod = `method` TagNameMime = `mime` TagNameType = `type` + TagNameDomain = `domain` TagNameValidate = `v` ) diff --git a/protocol/goai/goai_parameter.go b/protocol/goai/goai_parameter.go index 23ca40314..234b9a00a 100644 --- a/protocol/goai/goai_parameter.go +++ b/protocol/goai/goai_parameter.go @@ -8,6 +8,7 @@ package goai import ( "fmt" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/json" diff --git a/protocol/goai/goai_path.go b/protocol/goai/goai_path.go index cd1346761..b9aaeedc6 100644 --- a/protocol/goai/goai_path.go +++ b/protocol/goai/goai_path.go @@ -7,13 +7,14 @@ package goai import ( + "reflect" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/structs" "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/gmeta" - "reflect" ) type Path struct { diff --git a/protocol/goai/goai_requestbody.go b/protocol/goai/goai_requestbody.go index 86ff0504e..d159a6ed2 100644 --- a/protocol/goai/goai_requestbody.go +++ b/protocol/goai/goai_requestbody.go @@ -7,10 +7,11 @@ package goai import ( + "reflect" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/structs" "github.com/gogf/gf/v2/text/gstr" - "reflect" ) // RequestBody is specified by OpenAPI/Swagger 3.0 standard. diff --git a/protocol/goai/goai_response.go b/protocol/goai/goai_response.go index a5337bda9..5c9940158 100644 --- a/protocol/goai/goai_response.go +++ b/protocol/goai/goai_response.go @@ -7,10 +7,11 @@ package goai import ( + "reflect" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/structs" "github.com/gogf/gf/v2/text/gstr" - "reflect" ) // Response is specified by OpenAPI/Swagger 3.0 standard. diff --git a/protocol/goai/goai_shema.go b/protocol/goai/goai_shema.go index 7558762ec..1a6192750 100644 --- a/protocol/goai/goai_shema.go +++ b/protocol/goai/goai_shema.go @@ -7,13 +7,14 @@ package goai import ( + "reflect" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/structs" "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/gmeta" - "reflect" ) type Schemas map[string]SchemaRef diff --git a/protocol/goai/goai_shemaref.go b/protocol/goai/goai_shemaref.go index fcd15df2c..9dcd97ff1 100644 --- a/protocol/goai/goai_shemaref.go +++ b/protocol/goai/goai_shemaref.go @@ -7,11 +7,12 @@ package goai import ( + "reflect" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/util/gconv" - "reflect" ) type SchemaRefs []SchemaRef diff --git a/protocol/goai/goai_test.go b/protocol/goai/goai_z_unit_test.go similarity index 98% rename from protocol/goai/goai_test.go rename to protocol/goai/goai_z_unit_test.go index e079884fb..9acda5b21 100644 --- a/protocol/goai/goai_test.go +++ b/protocol/goai/goai_z_unit_test.go @@ -9,11 +9,12 @@ package goai_test import ( "context" "fmt" + "testing" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/protocol/goai" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gmeta" - "testing" ) func Test_Basic(t *testing.T) { @@ -105,7 +106,7 @@ func TestOpenApiV3_Add(t *testing.T) { Object: f, }) t.AssertNil(err) - //fmt.Println(oai.String()) + // fmt.Println(oai.String()) // Schema asserts. t.Assert(len(oai.Components.Schemas), 3) t.Assert(oai.Components.Schemas[`github.com.gogf.gf.v2.protocol.goai_test.CreateResourceReq`].Value.Type, goai.TypeObject) @@ -317,7 +318,7 @@ func TestOpenApiV3_CommonRequest_WithoutDataField_Setting(t *testing.T) { }) t.AssertNil(err) // Schema asserts. - //fmt.Println(oai.String()) + // fmt.Println(oai.String()) t.Assert(len(oai.Components.Schemas), 3) t.Assert(len(oai.Paths), 1) t.Assert(len(oai.Paths["/index"].Put.RequestBody.Value.Content["application/json"].Schema.Value.Properties), 5) @@ -357,7 +358,7 @@ func TestOpenApiV3_CommonRequest_EmptyRequest(t *testing.T) { }) t.AssertNil(err) // Schema asserts. - //fmt.Println(oai.String()) + // fmt.Println(oai.String()) t.Assert(len(oai.Components.Schemas), 3) t.Assert(len(oai.Paths), 1) t.Assert(len(oai.Paths["/index"].Put.RequestBody.Value.Content["application/json"].Schema.Value.Properties), 3) @@ -412,7 +413,7 @@ func TestOpenApiV3_CommonRequest_SubDataField(t *testing.T) { }) t.AssertNil(err) // Schema asserts. - //fmt.Println(oai.String()) + // fmt.Println(oai.String()) t.Assert(len(oai.Components.Schemas), 4) t.Assert(len(oai.Paths), 1) t.Assert(len(oai.Paths["/index"].Put.RequestBody.Value.Content["application/json"].Schema.Value.Properties), 1) @@ -543,7 +544,7 @@ func TestOpenApiV3_CommonResponse_EmptyResponse(t *testing.T) { }) t.AssertNil(err) // Schema asserts. - //fmt.Println(oai.String()) + // fmt.Println(oai.String()) t.Assert(len(oai.Components.Schemas), 3) t.Assert(len(oai.Paths), 1) t.Assert(oai.Paths["/index"].Put.RequestBody.Value.Content["application/json"].Schema.Ref, `github.com.gogf.gf.v2.protocol.goai_test.Req`) @@ -599,7 +600,7 @@ func TestOpenApiV3_CommonResponse_SubDataField(t *testing.T) { }) t.AssertNil(err) // Schema asserts. - //fmt.Println(oai.String()) + // fmt.Println(oai.String()) t.Assert(len(oai.Components.Schemas), 4) t.Assert(len(oai.Paths), 1) t.Assert(len(oai.Paths["/index"].Get.Responses["200"].Value.Content["application/json"].Schema.Value.Properties), 1) @@ -654,7 +655,7 @@ func TestOpenApiV3_ShortTags(t *testing.T) { Object: f, }) t.AssertNil(err) - //fmt.Println(oai.String()) + // fmt.Println(oai.String()) // Schema asserts. t.Assert(len(oai.Components.Schemas), 3) t.Assert(oai.Paths[`/test1/{appId}`].Summary, `CreateResourceReq sum`) @@ -690,7 +691,7 @@ func TestOpenApiV3_HtmlResponse(t *testing.T) { }) t.AssertNil(err) - //fmt.Println(oai.String()) + // fmt.Println(oai.String()) t.Assert(oai.Components.Schemas[`github.com.gogf.gf.v2.protocol.goai_test.Res`].Value.Type, goai.TypeString) }) } @@ -737,7 +738,7 @@ func TestOpenApiV3_HtmlResponseWithCommonResponse(t *testing.T) { }) t.AssertNil(err) - //fmt.Println(oai.String()) + // fmt.Println(oai.String()) t.Assert(oai.Components.Schemas[`github.com.gogf.gf.v2.protocol.goai_test.Res`].Value.Type, goai.TypeString) }) } diff --git a/test/gtest/gtest_util.go b/test/gtest/gtest_util.go index 387a24c33..8f2913fe8 100644 --- a/test/gtest/gtest_util.go +++ b/test/gtest/gtest_util.go @@ -8,7 +8,6 @@ package gtest import ( "fmt" - "github.com/gogf/gf/v2/internal/empty" "io/ioutil" "os" "path/filepath" @@ -16,7 +15,7 @@ import ( "testing" "github.com/gogf/gf/v2/debug/gdebug" - + "github.com/gogf/gf/v2/internal/empty" "github.com/gogf/gf/v2/util/gconv" ) diff --git a/text/gregex/gregex.go b/text/gregex/gregex.go index f23fe5936..a1dfc9686 100644 --- a/text/gregex/gregex.go +++ b/text/gregex/gregex.go @@ -75,7 +75,7 @@ func MatchAllString(pattern string, src string) ([][]string, error) { } } -// Replace replace all matched `pattern` in bytes `src` with bytes `replace`. +// Replace replaces all matched `pattern` in bytes `src` with bytes `replace`. func Replace(pattern string, replace, src []byte) ([]byte, error) { if r, err := getRegexp(pattern); err == nil { return r.ReplaceAll(src, replace), nil diff --git a/text/gregex/gregex_z_example_test.go b/text/gregex/gregex_z_example_test.go new file mode 100644 index 000000000..afcefbe37 --- /dev/null +++ b/text/gregex/gregex_z_example_test.go @@ -0,0 +1,279 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. +package gregex_test + +import ( + "bytes" + "fmt" + "strings" + + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/text/gregex" +) + +func ExampleIsMatch() { + patternStr := `\d+` + g.Dump(gregex.IsMatch(patternStr, []byte("hello 2022! hello gf!"))) + g.Dump(gregex.IsMatch(patternStr, nil)) + g.Dump(gregex.IsMatch(patternStr, []byte("hello gf!"))) + + // Output: + // true + // false + // false +} + +func ExampleIsMatchString() { + patternStr := `\d+` + g.Dump(gregex.IsMatchString(patternStr, "hello 2022! hello gf!")) + g.Dump(gregex.IsMatchString(patternStr, "hello gf!")) + g.Dump(gregex.IsMatchString(patternStr, "")) + + // Output: + // true + // false + // false +} + +func ExampleMatch() { + patternStr := `(\w+)=(\w+)` + matchStr := "https://goframe.org/pages/viewpage.action?pageId=1114219&searchId=8QC5D1D2E!" + // This method looks for the first match index + result, err := gregex.Match(patternStr, []byte(matchStr)) + g.Dump(result) + g.Dump(err) + + // Output: + // [ + // "pageId=1114219", + // "pageId", + // "1114219", + // ] + // +} + +func ExampleMatchString() { + patternStr := `(\w+)=(\w+)` + matchStr := "https://goframe.org/pages/viewpage.action?pageId=1114219&searchId=8QC5D1D2E!" + // This method looks for the first match index + result, err := gregex.MatchString(patternStr, matchStr) + g.Dump(result) + g.Dump(err) + + // Output: + // [ + // "pageId=1114219", + // "pageId", + // "1114219", + // ] + // +} + +func ExampleMatchAll() { + patternStr := `(\w+)=(\w+)` + matchStr := "https://goframe.org/pages/viewpage.action?pageId=1114219&searchId=8QC5D1D2E!" + result, err := gregex.MatchAll(patternStr, []byte(matchStr)) + g.Dump(result) + g.Dump(err) + + // Output: + // [ + // [ + // "pageId=1114219", + // "pageId", + // "1114219", + // ], + // [ + // "searchId=8QC5D1D2E", + // "searchId", + // "8QC5D1D2E", + // ], + // ] + // +} + +func ExampleMatchAllString() { + patternStr := `(\w+)=(\w+)` + matchStr := "https://goframe.org/pages/viewpage.action?pageId=1114219&searchId=8QC5D1D2E!" + result, err := gregex.MatchAllString(patternStr, matchStr) + g.Dump(result) + g.Dump(err) + + // Output: + // [ + // [ + // "pageId=1114219", + // "pageId", + // "1114219", + // ], + // [ + // "searchId=8QC5D1D2E", + // "searchId", + // "8QC5D1D2E", + // ], + // ] + // +} + +func ExampleQuote() { + result := gregex.Quote(`[1-9]\d+`) + fmt.Println(result) + + // Output: + // \[1-9\]\\d\+ +} + +func ExampleReplace() { + var ( + patternStr = `\d+` + str = "hello gf 2020!" + repStr = "2021" + result, err = gregex.Replace(patternStr, []byte(repStr), []byte(str)) + ) + g.Dump(err) + g.Dump(result) + + // Output: + // + // "hello gf 2021!" +} + +func ExampleReplaceFunc() { + // In contrast to [ExampleReplaceFunc] + // the result contains the `pattern' of all subpattern that use the matching function + result, err := gregex.ReplaceFuncMatch(`(\d+)~(\d+)`, []byte("hello gf 2018~2020!"), func(match [][]byte) []byte { + g.Dump(match) + match[2] = []byte("2021") + return bytes.Join(match[1:], []byte("~")) + }) + g.Dump(result) + g.Dump(err) + + // Output: + // [ + // "2018~2020", + // "2018", + // "2020", + // ] + // "hello gf 2018~2021!" + // +} + +func ExampleReplaceFuncMatch() { + var ( + patternStr = `(\d+)~(\d+)` + str = "hello gf 2018~2020!" + ) + // In contrast to [ExampleReplaceFunc] + // the result contains the `pattern' of all subpatterns that use the matching function + result, err := gregex.ReplaceFuncMatch(patternStr, []byte(str), func(match [][]byte) []byte { + g.Dump(match) + match[2] = []byte("2021") + return bytes.Join(match[1:], []byte("-")) + }) + g.Dump(result) + g.Dump(err) + + // Output: + // [ + // "2018~2020", + // "2018", + // "2020", + // ] + // "hello gf 2018-2021!" + // +} + +func ExampleReplaceString() { + patternStr := `\d+` + str := "hello gf 2020!" + replaceStr := "2021" + result, err := gregex.ReplaceString(patternStr, replaceStr, str) + + g.Dump(result) + g.Dump(err) + + // Output: + // "hello gf 2021!" + // +} + +func ExampleReplaceStringFunc() { + replaceStrMap := map[string]string{ + "2020": "2021", + } + // When the regular statement can match multiple results + // func can be used to further control the value that needs to be modified + result, err := gregex.ReplaceStringFunc(`\d+`, `hello gf 2018~2020!`, func(b string) string { + g.Dump(b) + if replaceStr, ok := replaceStrMap[b]; ok { + return replaceStr + } + return b + }) + g.Dump(result) + g.Dump(err) + + result, err = gregex.ReplaceStringFunc(`[a-z]*`, "gf@goframe.org", strings.ToUpper) + g.Dump(result) + g.Dump(err) + + // Output: + // "2018" + // "2020" + // "hello gf 2018~2021!" + // + // "GF@GOFRAME.ORG" + // +} + +func ExampleReplaceStringFuncMatch() { + var ( + patternStr = `([A-Z])\w+` + str = "hello Golang 2018~2021!" + ) + // In contrast to [ExampleReplaceFunc] + // the result contains the `pattern' of all subpatterns that use the matching function + result, err := gregex.ReplaceStringFuncMatch(patternStr, str, func(match []string) string { + g.Dump(match) + match[0] = "Gf" + return match[0] + }) + g.Dump(result) + g.Dump(err) + + // Output: + // [ + // "Golang", + // "G", + // ] + // "hello Gf 2018~2021!" + // +} + +func ExampleSplit() { + patternStr := `\d+` + str := "hello2020gf" + result := gregex.Split(patternStr, str) + g.Dump(result) + + // Output: + // [ + // "hello", + // "gf", + // ] +} + +func ExampleValidate() { + // Valid match statement + fmt.Println(gregex.Validate(`\d+`)) + // Mismatched statement + fmt.Println(gregex.Validate(`[a-9]\d+`)) + + // Output: + // + // error parsing regexp: invalid character class range: `a-9` +} diff --git a/text/gstr/gstr.go b/text/gstr/gstr.go index 7a08c0cf4..e783a9a0b 100644 --- a/text/gstr/gstr.go +++ b/text/gstr/gstr.go @@ -17,9 +17,7 @@ import ( "unicode/utf8" "github.com/gogf/gf/v2/internal/utils" - "github.com/gogf/gf/v2/util/gconv" - "github.com/gogf/gf/v2/util/grand" ) @@ -327,14 +325,7 @@ func Split(str, delimiter string) []string { // and calls Trim to every element of this array. It ignores the elements // which are empty after Trim. func SplitAndTrim(str, delimiter string, characterMask ...string) []string { - array := make([]string, 0) - for _, v := range strings.Split(str, delimiter) { - v = Trim(v, characterMask...) - if v != "" { - array = append(array, v) - } - } - return array + return utils.SplitAndTrim(str, delimiter, characterMask...) } // Join concatenates the elements of `array` to create a single string. The separator string diff --git a/text/gstr/gstr_trim.go b/text/gstr/gstr_trim.go index bdd937ebf..ea46102f1 100644 --- a/text/gstr/gstr_trim.go +++ b/text/gstr/gstr_trim.go @@ -7,8 +7,9 @@ package gstr import ( - "github.com/gogf/gf/v2/internal/utils" "strings" + + "github.com/gogf/gf/v2/internal/utils" ) // Trim strips whitespace (or other characters) from the beginning and end of a string. diff --git a/util/gconv/gconv.go b/util/gconv/gconv.go index a0809d13a..60c4b3252 100644 --- a/util/gconv/gconv.go +++ b/util/gconv/gconv.go @@ -11,8 +11,6 @@ package gconv import ( "fmt" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/os/gtime" "math" "reflect" "strconv" @@ -20,6 +18,8 @@ import ( "time" "github.com/gogf/gf/v2/encoding/gbinary" + "github.com/gogf/gf/v2/internal/json" + "github.com/gogf/gf/v2/os/gtime" ) var ( diff --git a/util/gconv/gconv_map.go b/util/gconv/gconv_map.go index 811153499..13f7d5e8f 100644 --- a/util/gconv/gconv_map.go +++ b/util/gconv/gconv_map.go @@ -7,11 +7,11 @@ package gconv import ( - "github.com/gogf/gf/v2/internal/json" "reflect" "strings" "github.com/gogf/gf/v2/internal/empty" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/utils" ) diff --git a/util/gconv/gconv_maptomap.go b/util/gconv/gconv_maptomap.go index 498a22082..51eb0efda 100644 --- a/util/gconv/gconv_maptomap.go +++ b/util/gconv/gconv_maptomap.go @@ -7,10 +7,11 @@ package gconv import ( + "reflect" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/json" - "reflect" ) // MapToMap converts any map type variable `params` to another map type variable `pointer` diff --git a/util/gconv/gconv_maptomaps.go b/util/gconv/gconv_maptomaps.go index 28289a0e2..6ab8e2199 100644 --- a/util/gconv/gconv_maptomaps.go +++ b/util/gconv/gconv_maptomaps.go @@ -7,10 +7,11 @@ package gconv import ( + "reflect" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/json" - "reflect" ) // MapToMaps converts any slice type variable `params` to another map slice type variable `pointer`. diff --git a/util/gconv/gconv_scan.go b/util/gconv/gconv_scan.go index 8df73d0e7..25555da65 100644 --- a/util/gconv/gconv_scan.go +++ b/util/gconv/gconv_scan.go @@ -7,9 +7,13 @@ package gconv import ( + "database/sql" + "reflect" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" - "reflect" + "github.com/gogf/gf/v2/internal/structs" + "github.com/gogf/gf/v2/internal/utils" ) // Scan automatically checks the type of `pointer` and converts `params` to `pointer`. It supports `pointer` @@ -38,7 +42,18 @@ func Scan(params interface{}, pointer interface{}, mapping ...map[string]string) } pointerKind = pointerType.Kind() if pointerKind != reflect.Ptr { - return gerror.NewCodef(gcode.CodeInvalidParameter, "params should be type of pointer, but got type: %v", pointerKind) + if pointerValue.CanAddr() { + pointerValue = pointerValue.Addr() + pointerType = pointerValue.Type() + pointerKind = pointerType.Kind() + } else { + return gerror.NewCodef( + gcode.CodeInvalidParameter, + "params should be type of pointer, but got type: %v", + pointerType, + ) + } + } // Direct assignment checks! var ( @@ -94,3 +109,410 @@ func Scan(params interface{}, pointer interface{}, mapping ...map[string]string) return doStruct(params, pointer, keyToAttributeNameMapping, "") } } + +// ScanList converts `structSlice` to struct slice which contains other complex struct attributes. +// Note that the parameter `structSlicePointer` should be type of *[]struct/*[]*struct. +// +// Usage example 1: Normal attribute struct relation: +// type EntityUser struct { +// Uid int +// Name string +// } +// type EntityUserDetail struct { +// Uid int +// Address string +// } +// type EntityUserScores struct { +// Id int +// Uid int +// Score int +// Course string +// } +// type Entity struct { +// User *EntityUser +// UserDetail *EntityUserDetail +// UserScores []*EntityUserScores +// } +// var users []*Entity +// ScanList(records, &users, "User") +// ScanList(records, &users, "User", "uid") +// ScanList(records, &users, "UserDetail", "User", "uid:Uid") +// ScanList(records, &users, "UserScores", "User", "uid:Uid") +// ScanList(records, &users, "UserScores", "User", "uid") +// +// +// Usage example 2: Embedded attribute struct relation: +// type EntityUser struct { +// Uid int +// Name string +// } +// type EntityUserDetail struct { +// Uid int +// Address string +// } +// type EntityUserScores struct { +// Id int +// Uid int +// Score int +// } +// type Entity struct { +// EntityUser +// UserDetail EntityUserDetail +// UserScores []EntityUserScores +// } +// +// var users []*Entity +// ScanList(records, &users) +// ScanList(records, &users, "UserDetail", "uid") +// ScanList(records, &users, "UserScores", "uid") +// +// +// The parameters "User/UserDetail/UserScores" in the example codes specify the target attribute struct +// that current result will be bound to. +// +// The "uid" in the example codes is the table field name of the result, and the "Uid" is the relational +// struct attribute name - not the attribute name of the bound to target. In the example codes, it's attribute +// name "Uid" of "User" of entity "Entity". It automatically calculates the HasOne/HasMany relationship with +// given `relation` parameter. +// +// See the example or unit testing cases for clear understanding for this function. +func ScanList(structSlice interface{}, structSlicePointer interface{}, bindToAttrName string, relationAttrNameAndFields ...string) (err error) { + var ( + relationAttrName string + relationFields string + ) + switch len(relationAttrNameAndFields) { + case 2: + relationAttrName = relationAttrNameAndFields[0] + relationFields = relationAttrNameAndFields[1] + case 1: + relationFields = relationAttrNameAndFields[0] + } + return doScanList(structSlice, structSlicePointer, bindToAttrName, relationAttrName, relationFields) +} + +// doScanList converts `structSlice` to struct slice which contains other complex struct attributes recursively. +// Note that the parameter `structSlicePointer` should be type of *[]struct/*[]*struct. +func doScanList(structSlice interface{}, structSlicePointer interface{}, bindToAttrName, relationAttrName, relationFields string) (err error) { + var ( + maps = Maps(structSlice) + ) + if len(maps) == 0 { + return nil + } + // Necessary checks for parameters. + if bindToAttrName == "" { + return gerror.NewCode(gcode.CodeInvalidParameter, `bindToAttrName should not be empty`) + } + + if relationAttrName == "." { + relationAttrName = "" + } + + var ( + reflectValue = reflect.ValueOf(structSlicePointer) + reflectKind = reflectValue.Kind() + ) + if reflectKind == reflect.Interface { + reflectValue = reflectValue.Elem() + reflectKind = reflectValue.Kind() + } + if reflectKind != reflect.Ptr { + return gerror.NewCodef( + gcode.CodeInvalidParameter, + "structSlicePointer should be type of *[]struct/*[]*struct, but got: %v", + reflectKind, + ) + } + reflectValue = reflectValue.Elem() + reflectKind = reflectValue.Kind() + if reflectKind != reflect.Slice && reflectKind != reflect.Array { + return gerror.NewCodef( + gcode.CodeInvalidParameter, + "structSlicePointer should be type of *[]struct/*[]*struct, but got: %v", + reflectKind, + ) + } + length := len(maps) + if length == 0 { + // The pointed slice is not empty. + if reflectValue.Len() > 0 { + // It here checks if it has struct item, which is already initialized. + // It then returns error to warn the developer its empty and no conversion. + if v := reflectValue.Index(0); v.Kind() != reflect.Ptr { + return sql.ErrNoRows + } + } + // Do nothing for empty struct slice. + return nil + } + var ( + arrayValue reflect.Value // Like: []*Entity + arrayItemType reflect.Type // Like: *Entity + reflectType = reflect.TypeOf(structSlicePointer) + ) + if reflectValue.Len() > 0 { + arrayValue = reflectValue + } else { + arrayValue = reflect.MakeSlice(reflectType.Elem(), length, length) + } + + // Slice element item. + arrayItemType = arrayValue.Index(0).Type() + + // Relation variables. + var ( + relationDataMap map[string]interface{} + relationFromFieldName string // Eg: relationKV: id:uid -> id + relationBindToFieldName string // Eg: relationKV: id:uid -> uid + ) + if len(relationFields) > 0 { + // The relation key string of table filed name and attribute name + // can be joined with char '=' or ':'. + array := utils.SplitAndTrim(relationFields, "=") + if len(array) == 1 { + // Compatible with old splitting char ':'. + array = utils.SplitAndTrim(relationFields, ":") + } + if len(array) == 1 { + // The relation names are the same. + array = []string{relationFields, relationFields} + } + if len(array) == 2 { + // Defined table field to relation attribute name. + // Like: + // uid:Uid + // uid:UserId + relationFromFieldName = array[0] + relationBindToFieldName = array[1] + if key, _ := utils.MapPossibleItemByKey(maps[0], relationFromFieldName); key == "" { + return gerror.NewCodef( + gcode.CodeInvalidParameter, + `cannot find possible related table field name "%s" from given relation fields "%s"`, + relationFromFieldName, + relationFields, + ) + } else { + relationFromFieldName = key + } + } else { + return gerror.NewCode( + gcode.CodeInvalidParameter, + `parameter relationKV should be format of "ResultFieldName:BindToAttrName"`, + ) + } + if relationFromFieldName != "" { + // Note that the value might be type of slice. + relationDataMap = utils.ListToMapByKey(maps, relationFromFieldName) + } + if len(relationDataMap) == 0 { + return gerror.NewCodef( + gcode.CodeInvalidParameter, + `cannot find the relation data map, maybe invalid relation fields given "%v"`, + relationFields, + ) + } + } + // Bind to target attribute. + var ( + ok bool + bindToAttrValue reflect.Value + bindToAttrKind reflect.Kind + bindToAttrType reflect.Type + bindToAttrField reflect.StructField + ) + if arrayItemType.Kind() == reflect.Ptr { + if bindToAttrField, ok = arrayItemType.Elem().FieldByName(bindToAttrName); !ok { + return gerror.NewCodef( + gcode.CodeInvalidParameter, + `invalid parameter bindToAttrName: cannot find attribute with name "%s" from slice element`, + bindToAttrName, + ) + } + } else { + if bindToAttrField, ok = arrayItemType.FieldByName(bindToAttrName); !ok { + return gerror.NewCodef( + gcode.CodeInvalidParameter, + `invalid parameter bindToAttrName: cannot find attribute with name "%s" from slice element`, + bindToAttrName, + ) + } + } + bindToAttrType = bindToAttrField.Type + bindToAttrKind = bindToAttrType.Kind() + + // Bind to relation conditions. + var ( + relationFromAttrValue reflect.Value + relationFromAttrField reflect.Value + relationBindToFieldNameChecked bool + ) + for i := 0; i < arrayValue.Len(); i++ { + arrayElemValue := arrayValue.Index(i) + // The FieldByName should be called on non-pointer reflect.Value. + if arrayElemValue.Kind() == reflect.Ptr { + // Like: []*Entity + arrayElemValue = arrayElemValue.Elem() + if !arrayElemValue.IsValid() { + // The element is nil, then create one and set it to the slice. + // The "reflect.New(itemType.Elem())" creates a new element and returns the address of it. + // For example: + // reflect.New(itemType.Elem()) => *Entity + // reflect.New(itemType.Elem()).Elem() => Entity + arrayElemValue = reflect.New(arrayItemType.Elem()).Elem() + arrayValue.Index(i).Set(arrayElemValue.Addr()) + } + } else { + // Like: []Entity + } + bindToAttrValue = arrayElemValue.FieldByName(bindToAttrName) + if relationAttrName != "" { + // Attribute value of current slice element. + relationFromAttrValue = arrayElemValue.FieldByName(relationAttrName) + if relationFromAttrValue.Kind() == reflect.Ptr { + relationFromAttrValue = relationFromAttrValue.Elem() + } + } else { + // Current slice element. + relationFromAttrValue = arrayElemValue + } + if len(relationDataMap) > 0 && !relationFromAttrValue.IsValid() { + return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid relation fields specified: "%v"`, relationFields) + } + // Check and find possible bind to attribute name. + if relationFields != "" && !relationBindToFieldNameChecked { + relationFromAttrField = relationFromAttrValue.FieldByName(relationBindToFieldName) + if !relationFromAttrField.IsValid() { + var ( + filedMap, _ = structs.FieldMap(structs.FieldMapInput{ + Pointer: relationFromAttrValue, + RecursiveOption: structs.RecursiveOptionEmbeddedNoTag, + }) + ) + if key, _ := utils.MapPossibleItemByKey(Map(filedMap), relationBindToFieldName); key == "" { + return gerror.NewCodef( + gcode.CodeInvalidParameter, + `cannot find possible related attribute name "%s" from given relation fields "%s"`, + relationBindToFieldName, + relationFields, + ) + } else { + relationBindToFieldName = key + } + } + relationBindToFieldNameChecked = true + } + switch bindToAttrKind { + case reflect.Array, reflect.Slice: + if len(relationDataMap) > 0 { + relationFromAttrField = relationFromAttrValue.FieldByName(relationBindToFieldName) + if relationFromAttrField.IsValid() { + // results := make(Result, 0) + results := make([]interface{}, 0) + for _, v := range SliceAny(relationDataMap[String(relationFromAttrField.Interface())]) { + item := v + results = append(results, item) + } + if err = Structs(results, bindToAttrValue.Addr()); err != nil { + return err + } + } else { + // Maybe the attribute does not exist yet. + return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid relation fields specified: "%v"`, relationFields) + } + } else { + return gerror.NewCodef( + gcode.CodeInvalidParameter, + `relationKey should not be empty as field "%s" is slice`, + bindToAttrName, + ) + } + + case reflect.Ptr: + var element reflect.Value + if bindToAttrValue.IsNil() { + element = reflect.New(bindToAttrType.Elem()).Elem() + } else { + element = bindToAttrValue.Elem() + } + if len(relationDataMap) > 0 { + relationFromAttrField = relationFromAttrValue.FieldByName(relationBindToFieldName) + if relationFromAttrField.IsValid() { + v := relationDataMap[String(relationFromAttrField.Interface())] + if v == nil { + // There's no relational data. + continue + } + if utils.IsSlice(v) { + if err = Struct(SliceAny(v)[0], element); err != nil { + return err + } + } else { + if err = Struct(v, element); err != nil { + return err + } + } + } else { + // Maybe the attribute does not exist yet. + return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid relation fields specified: "%v"`, relationFields) + } + } else { + if i >= len(maps) { + // There's no relational data. + continue + } + v := maps[i] + if v == nil { + // There's no relational data. + continue + } + if err = Struct(v, element); err != nil { + return err + } + } + bindToAttrValue.Set(element.Addr()) + + case reflect.Struct: + if len(relationDataMap) > 0 { + relationFromAttrField = relationFromAttrValue.FieldByName(relationBindToFieldName) + if relationFromAttrField.IsValid() { + relationDataItem := relationDataMap[String(relationFromAttrField.Interface())] + if relationDataItem == nil { + // There's no relational data. + continue + } + if utils.IsSlice(relationDataItem) { + if err = Struct(SliceAny(relationDataItem)[0], bindToAttrValue); err != nil { + return err + } + } else { + if err = Struct(relationDataItem, bindToAttrValue); err != nil { + return err + } + } + } else { + // Maybe the attribute does not exist yet. + return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid relation fields specified: "%v"`, relationFields) + } + } else { + if i >= len(maps) { + // There's no relational data. + continue + } + relationDataItem := maps[i] + if relationDataItem == nil { + // There's no relational data. + continue + } + if err = Struct(relationDataItem, bindToAttrValue); err != nil { + return err + } + } + + default: + return gerror.NewCodef(gcode.CodeInvalidParameter, `unsupported attribute type: %s`, bindToAttrKind.String()) + } + } + reflect.ValueOf(structSlicePointer).Elem().Set(arrayValue) + return nil +} diff --git a/util/gconv/gconv_slice.go b/util/gconv/gconv_slice.go deleted file mode 100644 index a5c4126a5..000000000 --- a/util/gconv/gconv_slice.go +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. -// -// This Source Code Form is subject to the terms of the MIT License. -// If a copy of the MIT was not distributed with this file, -// You can obtain one at https://github.com/gogf/gf. - -package gconv diff --git a/util/gconv/gconv_slice_any.go b/util/gconv/gconv_slice_any.go index 6eb142c65..d4f73f610 100644 --- a/util/gconv/gconv_slice_any.go +++ b/util/gconv/gconv_slice_any.go @@ -8,6 +8,8 @@ package gconv import ( "reflect" + + "github.com/gogf/gf/v2/internal/utils" ) // SliceAny is alias of Interfaces. @@ -22,100 +24,108 @@ func Interfaces(any interface{}) []interface{} { } if r, ok := any.([]interface{}); ok { return r - } else if r, ok := any.(iInterfaces); ok { - return r.Interfaces() - } else { - var array []interface{} - switch value := any.(type) { - case []string: - array = make([]interface{}, len(value)) - for k, v := range value { - array[k] = v - } - case []int: - array = make([]interface{}, len(value)) - for k, v := range value { - array[k] = v - } - case []int8: - array = make([]interface{}, len(value)) - for k, v := range value { - array[k] = v - } - case []int16: - array = make([]interface{}, len(value)) - for k, v := range value { - array[k] = v - } - case []int32: - array = make([]interface{}, len(value)) - for k, v := range value { - array[k] = v - } - case []int64: - array = make([]interface{}, len(value)) - for k, v := range value { - array[k] = v - } - case []uint: - array = make([]interface{}, len(value)) - for k, v := range value { - array[k] = v - } - case []uint8: - array = make([]interface{}, len(value)) - for k, v := range value { - array[k] = v - } - case []uint16: - array = make([]interface{}, len(value)) - for k, v := range value { - array[k] = v - } - case []uint32: - for _, v := range value { - array = append(array, v) - } - case []uint64: - array = make([]interface{}, len(value)) - for k, v := range value { - array[k] = v - } - case []bool: - array = make([]interface{}, len(value)) - for k, v := range value { - array[k] = v - } - case []float32: - array = make([]interface{}, len(value)) - for k, v := range value { - array[k] = v - } - case []float64: - array = make([]interface{}, len(value)) - for k, v := range value { - array[k] = v - } - default: - // Finally we use reflection. - var ( - reflectValue = reflect.ValueOf(any) - reflectKind = reflectValue.Kind() - ) - for reflectKind == reflect.Ptr { - reflectValue = reflectValue.Elem() - reflectKind = reflectValue.Kind() - } - switch reflectKind { - case reflect.Slice, reflect.Array: - array = make([]interface{}, reflectValue.Len()) - for i := 0; i < reflectValue.Len(); i++ { - array[i] = reflectValue.Index(i).Interface() - } - default: - return []interface{}{any} - } + } + var ( + array []interface{} = nil + ) + switch value := any.(type) { + case []string: + array = make([]interface{}, len(value)) + for k, v := range value { + array[k] = v } + case []int: + array = make([]interface{}, len(value)) + for k, v := range value { + array[k] = v + } + case []int8: + array = make([]interface{}, len(value)) + for k, v := range value { + array[k] = v + } + case []int16: + array = make([]interface{}, len(value)) + for k, v := range value { + array[k] = v + } + case []int32: + array = make([]interface{}, len(value)) + for k, v := range value { + array[k] = v + } + case []int64: + array = make([]interface{}, len(value)) + for k, v := range value { + array[k] = v + } + case []uint: + array = make([]interface{}, len(value)) + for k, v := range value { + array[k] = v + } + case []uint8: + array = make([]interface{}, len(value)) + for k, v := range value { + array[k] = v + } + case []uint16: + array = make([]interface{}, len(value)) + for k, v := range value { + array[k] = v + } + case []uint32: + for _, v := range value { + array = append(array, v) + } + case []uint64: + array = make([]interface{}, len(value)) + for k, v := range value { + array[k] = v + } + case []bool: + array = make([]interface{}, len(value)) + for k, v := range value { + array[k] = v + } + case []float32: + array = make([]interface{}, len(value)) + for k, v := range value { + array[k] = v + } + case []float64: + array = make([]interface{}, len(value)) + for k, v := range value { + array[k] = v + } + } + if array != nil { return array } + if v, ok := any.(iInterfaces); ok { + return v.Interfaces() + } + // JSON format string value converting. + if checkJsonAndUnmarshalUseNumber(any, &array) { + return array + } + // Not a common type, it then uses reflection for conversion. + originValueAndKind := utils.OriginValueAndKind(any) + switch originValueAndKind.OriginKind { + case reflect.Slice, reflect.Array: + var ( + length = originValueAndKind.OriginValue.Len() + slice = make([]interface{}, length) + ) + for i := 0; i < length; i++ { + slice[i] = originValueAndKind.OriginValue.Index(i).Interface() + } + return slice + + default: + if originValueAndKind.OriginValue.IsZero() { + return []interface{}{} + } + return []interface{}{any} + } } diff --git a/util/gconv/gconv_slice_float.go b/util/gconv/gconv_slice_float.go index 8b0f9f101..56c774e33 100644 --- a/util/gconv/gconv_slice_float.go +++ b/util/gconv/gconv_slice_float.go @@ -6,7 +6,11 @@ package gconv -import "reflect" +import ( + "reflect" + + "github.com/gogf/gf/v2/internal/utils" +) // SliceFloat is alias of Floats. func SliceFloat(any interface{}) []float64 { @@ -33,7 +37,9 @@ func Float32s(any interface{}) []float32 { if any == nil { return nil } - var array []float32 + var ( + array []float32 = nil + ) switch value := any.(type) { case string: if value == "" { @@ -111,49 +117,39 @@ func Float32s(any interface{}) []float32 { for k, v := range value { array[k] = Float32(v) } - default: - if v, ok := any.(iFloats); ok { - return Float32s(v.Floats()) - } - if v, ok := any.(iInterfaces); ok { - return Float32s(v.Interfaces()) - } - // JSON format string value converting. - var result []float32 - if checkJsonAndUnmarshalUseNumber(any, &result) { - return result - } - // Not a common type, it then uses reflection for conversion. - var reflectValue reflect.Value - if v, ok := value.(reflect.Value); ok { - reflectValue = v - } else { - reflectValue = reflect.ValueOf(value) - } - reflectKind := reflectValue.Kind() - for reflectKind == reflect.Ptr { - reflectValue = reflectValue.Elem() - reflectKind = reflectValue.Kind() - } - switch reflectKind { - case reflect.Slice, reflect.Array: - var ( - length = reflectValue.Len() - slice = make([]float32, length) - ) - for i := 0; i < length; i++ { - slice[i] = Float32(reflectValue.Index(i).Interface()) - } - return slice - - default: - if reflectValue.IsZero() { - return []float32{} - } - return []float32{Float32(any)} - } } - return array + if array != nil { + return array + } + if v, ok := any.(iFloats); ok { + return Float32s(v.Floats()) + } + if v, ok := any.(iInterfaces); ok { + return Float32s(v.Interfaces()) + } + // JSON format string value converting. + if checkJsonAndUnmarshalUseNumber(any, &array) { + return array + } + // Not a common type, it then uses reflection for conversion. + originValueAndKind := utils.OriginValueAndKind(any) + switch originValueAndKind.OriginKind { + case reflect.Slice, reflect.Array: + var ( + length = originValueAndKind.OriginValue.Len() + slice = make([]float32, length) + ) + for i := 0; i < length; i++ { + slice[i] = Float32(originValueAndKind.OriginValue.Index(i).Interface()) + } + return slice + + default: + if originValueAndKind.OriginValue.IsZero() { + return []float32{} + } + return []float32{Float32(any)} + } } // Float64s converts `any` to []float64. @@ -161,7 +157,9 @@ func Float64s(any interface{}) []float64 { if any == nil { return nil } - var array []float64 + var ( + array []float64 = nil + ) switch value := any.(type) { case string: if value == "" { @@ -239,48 +237,37 @@ func Float64s(any interface{}) []float64 { for k, v := range value { array[k] = Float64(v) } - default: - if v, ok := any.(iFloats); ok { - return v.Floats() - } - if v, ok := any.(iInterfaces); ok { - return Floats(v.Interfaces()) - } - // JSON format string value converting. - var result []float64 - if checkJsonAndUnmarshalUseNumber(any, &result) { - return result - } - // Not a common type, it then uses reflection for conversion. - var reflectValue reflect.Value - if v, ok := value.(reflect.Value); ok { - reflectValue = v - } else { - reflectValue = reflect.ValueOf(value) - } - reflectKind := reflectValue.Kind() - for reflectKind == reflect.Ptr { - reflectValue = reflectValue.Elem() - reflectKind = reflectValue.Kind() - } - switch reflectKind { - case reflect.Slice, reflect.Array: - var ( - length = reflectValue.Len() - slice = make([]float64, length) - ) - for i := 0; i < length; i++ { - slice[i] = Float64(reflectValue.Index(i).Interface()) - } - return slice - - default: - if reflectValue.IsZero() { - return []float64{} - } - return []float64{Float64(any)} - } } - return array + if array != nil { + return array + } + if v, ok := any.(iFloats); ok { + return v.Floats() + } + if v, ok := any.(iInterfaces); ok { + return Floats(v.Interfaces()) + } + // JSON format string value converting. + if checkJsonAndUnmarshalUseNumber(any, &array) { + return array + } + // Not a common type, it then uses reflection for conversion. + originValueAndKind := utils.OriginValueAndKind(any) + switch originValueAndKind.OriginKind { + case reflect.Slice, reflect.Array: + var ( + length = originValueAndKind.OriginValue.Len() + slice = make([]float64, length) + ) + for i := 0; i < length; i++ { + slice[i] = Float64(originValueAndKind.OriginValue.Index(i).Interface()) + } + return slice + default: + if originValueAndKind.OriginValue.IsZero() { + return []float64{} + } + return []float64{Float64(any)} + } } diff --git a/util/gconv/gconv_slice_int.go b/util/gconv/gconv_slice_int.go index 17371dad4..c34701bb9 100644 --- a/util/gconv/gconv_slice_int.go +++ b/util/gconv/gconv_slice_int.go @@ -8,6 +8,8 @@ package gconv import ( "reflect" + + "github.com/gogf/gf/v2/internal/utils" ) // SliceInt is alias of Ints. @@ -30,7 +32,9 @@ func Ints(any interface{}) []int { if any == nil { return nil } - var array []int + var ( + array []int = nil + ) switch value := any.(type) { case []string: array = make([]int, len(value)) @@ -113,49 +117,39 @@ func Ints(any interface{}) []int { for k, v := range value { array[k] = Int(v) } - default: - if v, ok := any.(iInts); ok { - return v.Ints() - } - if v, ok := any.(iInterfaces); ok { - return Ints(v.Interfaces()) - } - // JSON format string value converting. - var result []int - if checkJsonAndUnmarshalUseNumber(any, &result) { - return result - } - // Not a common type, it then uses reflection for conversion. - var reflectValue reflect.Value - if v, ok := value.(reflect.Value); ok { - reflectValue = v - } else { - reflectValue = reflect.ValueOf(value) - } - reflectKind := reflectValue.Kind() - for reflectKind == reflect.Ptr { - reflectValue = reflectValue.Elem() - reflectKind = reflectValue.Kind() - } - switch reflectKind { - case reflect.Slice, reflect.Array: - var ( - length = reflectValue.Len() - slice = make([]int, length) - ) - for i := 0; i < length; i++ { - slice[i] = Int(reflectValue.Index(i).Interface()) - } - return slice - - default: - if reflectValue.IsZero() { - return []int{} - } - return []int{Int(any)} - } } - return array + if array != nil { + return array + } + if v, ok := any.(iInts); ok { + return v.Ints() + } + if v, ok := any.(iInterfaces); ok { + return Ints(v.Interfaces()) + } + // JSON format string value converting. + if checkJsonAndUnmarshalUseNumber(any, &array) { + return array + } + // Not a common type, it then uses reflection for conversion. + originValueAndKind := utils.OriginValueAndKind(any) + switch originValueAndKind.OriginKind { + case reflect.Slice, reflect.Array: + var ( + length = originValueAndKind.OriginValue.Len() + slice = make([]int, length) + ) + for i := 0; i < length; i++ { + slice[i] = Int(originValueAndKind.OriginValue.Index(i).Interface()) + } + return slice + + default: + if originValueAndKind.OriginValue.IsZero() { + return []int{} + } + return []int{Int(any)} + } } // Int32s converts `any` to []int32. @@ -163,7 +157,9 @@ func Int32s(any interface{}) []int32 { if any == nil { return nil } - var array []int32 + var ( + array []int32 = nil + ) switch value := any.(type) { case []string: array = make([]int32, len(value)) @@ -246,49 +242,39 @@ func Int32s(any interface{}) []int32 { for k, v := range value { array[k] = Int32(v) } - default: - if v, ok := any.(iInts); ok { - return Int32s(v.Ints()) - } - if v, ok := any.(iInterfaces); ok { - return Int32s(v.Interfaces()) - } - // JSON format string value converting. - var result []int32 - if checkJsonAndUnmarshalUseNumber(any, &result) { - return result - } - // Not a common type, it then uses reflection for conversion. - var reflectValue reflect.Value - if v, ok := value.(reflect.Value); ok { - reflectValue = v - } else { - reflectValue = reflect.ValueOf(value) - } - reflectKind := reflectValue.Kind() - for reflectKind == reflect.Ptr { - reflectValue = reflectValue.Elem() - reflectKind = reflectValue.Kind() - } - switch reflectKind { - case reflect.Slice, reflect.Array: - var ( - length = reflectValue.Len() - slice = make([]int32, length) - ) - for i := 0; i < length; i++ { - slice[i] = Int32(reflectValue.Index(i).Interface()) - } - return slice - - default: - if reflectValue.IsZero() { - return []int32{} - } - return []int32{Int32(any)} - } } - return array + if array != nil { + return array + } + if v, ok := any.(iInts); ok { + return Int32s(v.Ints()) + } + if v, ok := any.(iInterfaces); ok { + return Int32s(v.Interfaces()) + } + // JSON format string value converting. + if checkJsonAndUnmarshalUseNumber(any, &array) { + return array + } + // Not a common type, it then uses reflection for conversion. + originValueAndKind := utils.OriginValueAndKind(any) + switch originValueAndKind.OriginKind { + case reflect.Slice, reflect.Array: + var ( + length = originValueAndKind.OriginValue.Len() + slice = make([]int32, length) + ) + for i := 0; i < length; i++ { + slice[i] = Int32(originValueAndKind.OriginValue.Index(i).Interface()) + } + return slice + + default: + if originValueAndKind.OriginValue.IsZero() { + return []int32{} + } + return []int32{Int32(any)} + } } // Int64s converts `any` to []int64. @@ -296,7 +282,9 @@ func Int64s(any interface{}) []int64 { if any == nil { return nil } - var array []int64 + var ( + array []int64 = nil + ) switch value := any.(type) { case []string: array = make([]int64, len(value)) @@ -379,47 +367,37 @@ func Int64s(any interface{}) []int64 { for k, v := range value { array[k] = Int64(v) } - default: - if v, ok := any.(iInts); ok { - return Int64s(v.Ints()) - } - if v, ok := any.(iInterfaces); ok { - return Int64s(v.Interfaces()) - } - // JSON format string value converting. - var result []int64 - if checkJsonAndUnmarshalUseNumber(any, &result) { - return result - } - // Not a common type, it then uses reflection for conversion. - var reflectValue reflect.Value - if v, ok := value.(reflect.Value); ok { - reflectValue = v - } else { - reflectValue = reflect.ValueOf(value) - } - reflectKind := reflectValue.Kind() - for reflectKind == reflect.Ptr { - reflectValue = reflectValue.Elem() - reflectKind = reflectValue.Kind() - } - switch reflectKind { - case reflect.Slice, reflect.Array: - var ( - length = reflectValue.Len() - slice = make([]int64, length) - ) - for i := 0; i < length; i++ { - slice[i] = Int64(reflectValue.Index(i).Interface()) - } - return slice - - default: - if reflectValue.IsZero() { - return []int64{} - } - return []int64{Int64(any)} - } } - return array + if array != nil { + return array + } + if v, ok := any.(iInts); ok { + return Int64s(v.Ints()) + } + if v, ok := any.(iInterfaces); ok { + return Int64s(v.Interfaces()) + } + // JSON format string value converting. + if checkJsonAndUnmarshalUseNumber(any, &array) { + return array + } + // Not a common type, it then uses reflection for conversion. + originValueAndKind := utils.OriginValueAndKind(any) + switch originValueAndKind.OriginKind { + case reflect.Slice, reflect.Array: + var ( + length = originValueAndKind.OriginValue.Len() + slice = make([]int64, length) + ) + for i := 0; i < length; i++ { + slice[i] = Int64(originValueAndKind.OriginValue.Index(i).Interface()) + } + return slice + + default: + if originValueAndKind.OriginValue.IsZero() { + return []int64{} + } + return []int64{Int64(any)} + } } diff --git a/util/gconv/gconv_slice_str.go b/util/gconv/gconv_slice_str.go index 070546fc7..9118bd522 100644 --- a/util/gconv/gconv_slice_str.go +++ b/util/gconv/gconv_slice_str.go @@ -8,6 +8,8 @@ package gconv import ( "reflect" + + "github.com/gogf/gf/v2/internal/utils" ) // SliceStr is alias of Strings. @@ -20,7 +22,9 @@ func Strings(any interface{}) []string { if any == nil { return nil } - var array []string + var ( + array []string = nil + ) switch value := any.(type) { case []int: array = make([]string, len(value)) @@ -99,47 +103,37 @@ func Strings(any interface{}) []string { for k, v := range value { array[k] = String(v) } - default: - if v, ok := any.(iStrings); ok { - return v.Strings() - } - if v, ok := any.(iInterfaces); ok { - return Strings(v.Interfaces()) - } - // JSON format string value converting. - var result []string - if checkJsonAndUnmarshalUseNumber(any, &result) { - return result - } - // Not a common type, it then uses reflection for conversion. - var reflectValue reflect.Value - if v, ok := value.(reflect.Value); ok { - reflectValue = v - } else { - reflectValue = reflect.ValueOf(value) - } - reflectKind := reflectValue.Kind() - for reflectKind == reflect.Ptr { - reflectValue = reflectValue.Elem() - reflectKind = reflectValue.Kind() - } - switch reflectKind { - case reflect.Slice, reflect.Array: - var ( - length = reflectValue.Len() - slice = make([]string, length) - ) - for i := 0; i < length; i++ { - slice[i] = String(reflectValue.Index(i).Interface()) - } - return slice - - default: - if reflectValue.IsZero() { - return []string{} - } - return []string{String(any)} - } } - return array + if array != nil { + return array + } + if v, ok := any.(iStrings); ok { + return v.Strings() + } + if v, ok := any.(iInterfaces); ok { + return Strings(v.Interfaces()) + } + // JSON format string value converting. + if checkJsonAndUnmarshalUseNumber(any, &array) { + return array + } + // Not a common type, it then uses reflection for conversion. + originValueAndKind := utils.OriginValueAndKind(any) + switch originValueAndKind.OriginKind { + case reflect.Slice, reflect.Array: + var ( + length = originValueAndKind.OriginValue.Len() + slice = make([]string, length) + ) + for i := 0; i < length; i++ { + slice[i] = String(originValueAndKind.OriginValue.Index(i).Interface()) + } + return slice + + default: + if originValueAndKind.OriginValue.IsZero() { + return []string{} + } + return []string{String(any)} + } } diff --git a/util/gconv/gconv_slice_uint.go b/util/gconv/gconv_slice_uint.go index 863ac33a8..01d7a1d97 100644 --- a/util/gconv/gconv_slice_uint.go +++ b/util/gconv/gconv_slice_uint.go @@ -6,7 +6,12 @@ package gconv -import "reflect" +import ( + "reflect" + "strings" + + "github.com/gogf/gf/v2/internal/utils" +) // SliceUint is alias of Uints. func SliceUint(any interface{}) []uint { @@ -29,13 +34,19 @@ func Uints(any interface{}) []uint { return nil } - var array []uint + var ( + array []uint = nil + ) switch value := any.(type) { case string: + value = strings.TrimSpace(value) if value == "" { return []uint{} } - return []uint{Uint(value)} + if utils.IsNumeric(value) { + return []uint{Uint(value)} + } + case []string: array = make([]uint, len(value)) for k, v := range value { @@ -112,49 +123,42 @@ func Uints(any interface{}) []uint { for k, v := range value { array[k] = Uint(v) } - default: - if v, ok := any.(iUints); ok { - return v.Uints() - } - if v, ok := any.(iInterfaces); ok { - return Uints(v.Interfaces()) - } - // JSON format string value converting. - var result []uint - if checkJsonAndUnmarshalUseNumber(any, &result) { - return result - } - // Not a common type, it then uses reflection for conversion. - var reflectValue reflect.Value - if v, ok := value.(reflect.Value); ok { - reflectValue = v - } else { - reflectValue = reflect.ValueOf(value) - } - reflectKind := reflectValue.Kind() - for reflectKind == reflect.Ptr { - reflectValue = reflectValue.Elem() - reflectKind = reflectValue.Kind() - } - switch reflectKind { - case reflect.Slice, reflect.Array: - var ( - length = reflectValue.Len() - slice = make([]uint, length) - ) - for i := 0; i < length; i++ { - slice[i] = Uint(reflectValue.Index(i).Interface()) - } - return slice - - default: - if reflectValue.IsZero() { - return []uint{} - } - return []uint{Uint(any)} - } } - return array + + if array != nil { + return array + } + + // Default handler. + if v, ok := any.(iUints); ok { + return v.Uints() + } + if v, ok := any.(iInterfaces); ok { + return Uints(v.Interfaces()) + } + // JSON format string value converting. + if checkJsonAndUnmarshalUseNumber(any, &array) { + return array + } + // Not a common type, it then uses reflection for conversion. + originValueAndKind := utils.OriginValueAndKind(any) + switch originValueAndKind.OriginKind { + case reflect.Slice, reflect.Array: + var ( + length = originValueAndKind.OriginValue.Len() + slice = make([]uint, length) + ) + for i := 0; i < length; i++ { + slice[i] = Uint(originValueAndKind.OriginValue.Index(i).Interface()) + } + return slice + + default: + if originValueAndKind.OriginValue.IsZero() { + return []uint{} + } + return []uint{Uint(any)} + } } // Uint32s converts `any` to []uint32. @@ -162,13 +166,18 @@ func Uint32s(any interface{}) []uint32 { if any == nil { return nil } - var array []uint32 + var ( + array []uint32 = nil + ) switch value := any.(type) { case string: + value = strings.TrimSpace(value) if value == "" { return []uint32{} } - return []uint32{Uint32(value)} + if utils.IsNumeric(value) { + return []uint32{Uint32(value)} + } case []string: array = make([]uint32, len(value)) for k, v := range value { @@ -245,49 +254,41 @@ func Uint32s(any interface{}) []uint32 { for k, v := range value { array[k] = Uint32(v) } - default: - if v, ok := any.(iUints); ok { - return Uint32s(v.Uints()) - } - if v, ok := any.(iInterfaces); ok { - return Uint32s(v.Interfaces()) - } - // JSON format string value converting. - var result []uint32 - if checkJsonAndUnmarshalUseNumber(any, &result) { - return result - } - // Not a common type, it then uses reflection for conversion. - var reflectValue reflect.Value - if v, ok := value.(reflect.Value); ok { - reflectValue = v - } else { - reflectValue = reflect.ValueOf(value) - } - reflectKind := reflectValue.Kind() - for reflectKind == reflect.Ptr { - reflectValue = reflectValue.Elem() - reflectKind = reflectValue.Kind() - } - switch reflectKind { - case reflect.Slice, reflect.Array: - var ( - length = reflectValue.Len() - slice = make([]uint32, length) - ) - for i := 0; i < length; i++ { - slice[i] = Uint32(reflectValue.Index(i).Interface()) - } - return slice - - default: - if reflectValue.IsZero() { - return []uint32{} - } - return []uint32{Uint32(any)} - } } - return array + if array != nil { + return array + } + + // Default handler. + if v, ok := any.(iUints); ok { + return Uint32s(v.Uints()) + } + if v, ok := any.(iInterfaces); ok { + return Uint32s(v.Interfaces()) + } + // JSON format string value converting. + if checkJsonAndUnmarshalUseNumber(any, &array) { + return array + } + // Not a common type, it then uses reflection for conversion. + originValueAndKind := utils.OriginValueAndKind(any) + switch originValueAndKind.OriginKind { + case reflect.Slice, reflect.Array: + var ( + length = originValueAndKind.OriginValue.Len() + slice = make([]uint32, length) + ) + for i := 0; i < length; i++ { + slice[i] = Uint32(originValueAndKind.OriginValue.Index(i).Interface()) + } + return slice + + default: + if originValueAndKind.OriginValue.IsZero() { + return []uint32{} + } + return []uint32{Uint32(any)} + } } // Uint64s converts `any` to []uint64. @@ -295,13 +296,19 @@ func Uint64s(any interface{}) []uint64 { if any == nil { return nil } - var array []uint64 + var ( + array []uint64 = nil + ) switch value := any.(type) { case string: + value = strings.TrimSpace(value) if value == "" { return []uint64{} } - return []uint64{Uint64(value)} + if utils.IsNumeric(value) { + return []uint64{Uint64(value)} + } + case []string: array = make([]uint64, len(value)) for k, v := range value { @@ -378,47 +385,38 @@ func Uint64s(any interface{}) []uint64 { for k, v := range value { array[k] = Uint64(v) } - default: - if v, ok := any.(iUints); ok { - return Uint64s(v.Uints()) - } - if v, ok := any.(iInterfaces); ok { - return Uint64s(v.Interfaces()) - } - // JSON format string value converting. - var result []uint64 - if checkJsonAndUnmarshalUseNumber(any, &result) { - return result - } - // Not a common type, it then uses reflection for conversion. - var reflectValue reflect.Value - if v, ok := value.(reflect.Value); ok { - reflectValue = v - } else { - reflectValue = reflect.ValueOf(value) - } - reflectKind := reflectValue.Kind() - for reflectKind == reflect.Ptr { - reflectValue = reflectValue.Elem() - reflectKind = reflectValue.Kind() - } - switch reflectKind { - case reflect.Slice, reflect.Array: - var ( - length = reflectValue.Len() - slice = make([]uint64, length) - ) - for i := 0; i < length; i++ { - slice[i] = Uint64(reflectValue.Index(i).Interface()) - } - return slice - - default: - if reflectValue.IsZero() { - return []uint64{} - } - return []uint64{Uint64(any)} - } } - return array + if array != nil { + return array + } + // Default handler. + if v, ok := any.(iUints); ok { + return Uint64s(v.Uints()) + } + if v, ok := any.(iInterfaces); ok { + return Uint64s(v.Interfaces()) + } + // JSON format string value converting. + if checkJsonAndUnmarshalUseNumber(any, &array) { + return array + } + // Not a common type, it then uses reflection for conversion. + originValueAndKind := utils.OriginValueAndKind(any) + switch originValueAndKind.OriginKind { + case reflect.Slice, reflect.Array: + var ( + length = originValueAndKind.OriginValue.Len() + slice = make([]uint64, length) + ) + for i := 0; i < length; i++ { + slice[i] = Uint64(originValueAndKind.OriginValue.Index(i).Interface()) + } + return slice + + default: + if originValueAndKind.OriginValue.IsZero() { + return []uint64{} + } + return []uint64{Uint64(any)} + } } diff --git a/util/gconv/gconv_struct.go b/util/gconv/gconv_struct.go index 1546efae4..ad400507a 100644 --- a/util/gconv/gconv_struct.go +++ b/util/gconv/gconv_struct.go @@ -7,14 +7,14 @@ package gconv import ( + "reflect" + "strings" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/empty" "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/internal/structs" - "reflect" - "strings" - "github.com/gogf/gf/v2/internal/utils" ) @@ -162,9 +162,9 @@ func doStruct(params interface{}, pointer interface{}, mapping map[string]string e := reflect.New(pointerElemReflectValue.Type().Elem()).Elem() pointerElemReflectValue.Set(e.Addr()) } - //if v, ok := pointerElemReflectValue.Interface().(iUnmarshalValue); ok { + // if v, ok := pointerElemReflectValue.Interface().(iUnmarshalValue); ok { // return v.UnmarshalValue(params) - //} + // } // Note that it's `pointerElemReflectValue` here not `pointerReflectValue`. if err, ok := bindVarToReflectValueWithInterfaceCheck(pointerElemReflectValue, paramsInterface); ok { return err diff --git a/util/gconv/gconv_structs.go b/util/gconv/gconv_structs.go index 83db3548b..bb73319fe 100644 --- a/util/gconv/gconv_structs.go +++ b/util/gconv/gconv_structs.go @@ -7,10 +7,11 @@ package gconv import ( + "reflect" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/json" - "reflect" ) // Structs converts any slice to given struct slice. diff --git a/util/gconv/gconv_z_unit_scan_test.go b/util/gconv/gconv_z_unit_scan_test.go index 65248bced..e34f91d99 100644 --- a/util/gconv/gconv_z_unit_scan_test.go +++ b/util/gconv/gconv_z_unit_scan_test.go @@ -319,3 +319,285 @@ func Test_Scan_SameType_Just_Assign(t *testing.T) { t.Assert(*m1["int"], *m2["int"]) }) } + +func Test_ScanList_Basic(t *testing.T) { + // Struct attribute. + gtest.C(t, func(t *gtest.T) { + type EntityUser struct { + Uid int + Name string + } + + type EntityUserDetail struct { + Uid int + Address string + } + + type EntityUserScores struct { + Id int + Uid int + Score int + } + + type Entity struct { + User EntityUser + UserDetail EntityUserDetail + UserScores []EntityUserScores + } + + var ( + err error + entities []Entity + entityUsers = []EntityUser{ + {Uid: 1, Name: "name1"}, + {Uid: 2, Name: "name2"}, + {Uid: 3, Name: "name3"}, + } + userDetails = []EntityUserDetail{ + {Uid: 1, Address: "address1"}, + {Uid: 2, Address: "address2"}, + } + userScores = []EntityUserScores{ + {Id: 10, Uid: 1, Score: 100}, + {Id: 11, Uid: 1, Score: 60}, + {Id: 20, Uid: 2, Score: 99}, + } + ) + err = gconv.ScanList(entityUsers, &entities, "User") + t.AssertNil(err) + + err = gconv.ScanList(userDetails, &entities, "UserDetail", "User", "uid") + t.AssertNil(err) + + err = gconv.ScanList(userScores, &entities, "UserScores", "User", "uid") + t.AssertNil(err) + + t.Assert(len(entities), 3) + t.Assert(entities[0].User, entityUsers[0]) + t.Assert(entities[1].User, entityUsers[1]) + t.Assert(entities[2].User, entityUsers[2]) + + t.Assert(entities[0].UserDetail, userDetails[0]) + t.Assert(entities[1].UserDetail, userDetails[1]) + t.Assert(entities[2].UserDetail, EntityUserDetail{}) + + t.Assert(len(entities[0].UserScores), 2) + t.Assert(entities[0].UserScores[0], userScores[0]) + t.Assert(entities[0].UserScores[1], userScores[1]) + + t.Assert(len(entities[1].UserScores), 1) + t.Assert(entities[1].UserScores[0], userScores[2]) + + t.Assert(len(entities[2].UserScores), 0) + }) + // Pointer attribute. + gtest.C(t, func(t *gtest.T) { + type EntityUser struct { + Uid int + Name string + } + + type EntityUserDetail struct { + Uid int + Address string + } + + type EntityUserScores struct { + Id int + Uid int + Score int + } + + type Entity struct { + User *EntityUser + UserDetail *EntityUserDetail + UserScores []*EntityUserScores + } + + var ( + err error + entities []*Entity + entityUsers = []*EntityUser{ + {Uid: 1, Name: "name1"}, + {Uid: 2, Name: "name2"}, + {Uid: 3, Name: "name3"}, + } + userDetails = []*EntityUserDetail{ + {Uid: 1, Address: "address1"}, + {Uid: 2, Address: "address2"}, + } + userScores = []*EntityUserScores{ + {Id: 10, Uid: 1, Score: 100}, + {Id: 11, Uid: 1, Score: 60}, + {Id: 20, Uid: 2, Score: 99}, + } + ) + err = gconv.ScanList(entityUsers, &entities, "User") + t.AssertNil(err) + + err = gconv.ScanList(userDetails, &entities, "UserDetail", "User", "uid") + t.AssertNil(err) + + err = gconv.ScanList(userScores, &entities, "UserScores", "User", "uid") + t.AssertNil(err) + + t.Assert(len(entities), 3) + t.Assert(entities[0].User, entityUsers[0]) + t.Assert(entities[1].User, entityUsers[1]) + t.Assert(entities[2].User, entityUsers[2]) + + t.Assert(entities[0].UserDetail, userDetails[0]) + t.Assert(entities[1].UserDetail, userDetails[1]) + t.Assert(entities[2].UserDetail, nil) + + t.Assert(len(entities[0].UserScores), 2) + t.Assert(entities[0].UserScores[0], userScores[0]) + t.Assert(entities[0].UserScores[1], userScores[1]) + + t.Assert(len(entities[1].UserScores), 1) + t.Assert(entities[1].UserScores[0], userScores[2]) + + t.Assert(len(entities[2].UserScores), 0) + }) +} + +func Test_ScanList_Embedded(t *testing.T) { + // Struct attribute. + gtest.C(t, func(t *gtest.T) { + type EntityUser struct { + Uid int + Name string + } + + type EntityUserDetail struct { + Uid int + Address string + } + + type EntityUserScores struct { + Id int + Uid int + Score int + } + + type Entity struct { + EntityUser + UserDetail EntityUserDetail + UserScores []EntityUserScores + } + + var ( + err error + entities []Entity + entityUsers = []EntityUser{ + {Uid: 1, Name: "name1"}, + {Uid: 2, Name: "name2"}, + {Uid: 3, Name: "name3"}, + } + userDetails = []EntityUserDetail{ + {Uid: 1, Address: "address1"}, + {Uid: 2, Address: "address2"}, + } + userScores = []EntityUserScores{ + {Id: 10, Uid: 1, Score: 100}, + {Id: 11, Uid: 1, Score: 60}, + {Id: 20, Uid: 2, Score: 99}, + } + ) + err = gconv.Scan(entityUsers, &entities) + t.AssertNil(err) + + err = gconv.ScanList(userDetails, &entities, "UserDetail", "uid") + t.AssertNil(err) + + err = gconv.ScanList(userScores, &entities, "UserScores", "uid") + t.AssertNil(err) + + t.Assert(len(entities), 3) + t.Assert(entities[0].EntityUser, entityUsers[0]) + t.Assert(entities[1].EntityUser, entityUsers[1]) + t.Assert(entities[2].EntityUser, entityUsers[2]) + + t.Assert(entities[0].UserDetail, userDetails[0]) + t.Assert(entities[1].UserDetail, userDetails[1]) + t.Assert(entities[2].UserDetail, EntityUserDetail{}) + + t.Assert(len(entities[0].UserScores), 2) + t.Assert(entities[0].UserScores[0], userScores[0]) + t.Assert(entities[0].UserScores[1], userScores[1]) + + t.Assert(len(entities[1].UserScores), 1) + t.Assert(entities[1].UserScores[0], userScores[2]) + + t.Assert(len(entities[2].UserScores), 0) + }) + // Pointer attribute. + gtest.C(t, func(t *gtest.T) { + type EntityUser struct { + Uid int + Name string + } + + type EntityUserDetail struct { + Uid int + Address string + } + + type EntityUserScores struct { + Id int + Uid int + Score int + } + + type Entity struct { + *EntityUser + UserDetail *EntityUserDetail + UserScores []*EntityUserScores + } + + var ( + err error + entities []Entity + entityUsers = []EntityUser{ + {Uid: 1, Name: "name1"}, + {Uid: 2, Name: "name2"}, + {Uid: 3, Name: "name3"}, + } + userDetails = []EntityUserDetail{ + {Uid: 1, Address: "address1"}, + {Uid: 2, Address: "address2"}, + } + userScores = []EntityUserScores{ + {Id: 10, Uid: 1, Score: 100}, + {Id: 11, Uid: 1, Score: 60}, + {Id: 20, Uid: 2, Score: 99}, + } + ) + err = gconv.Scan(entityUsers, &entities) + t.AssertNil(err) + + err = gconv.ScanList(userDetails, &entities, "UserDetail", "uid") + t.AssertNil(err) + + err = gconv.ScanList(userScores, &entities, "UserScores", "uid") + t.AssertNil(err) + + t.Assert(len(entities), 3) + t.Assert(entities[0].EntityUser, entityUsers[0]) + t.Assert(entities[1].EntityUser, entityUsers[1]) + t.Assert(entities[2].EntityUser, entityUsers[2]) + + t.Assert(entities[0].UserDetail, userDetails[0]) + t.Assert(entities[1].UserDetail, userDetails[1]) + t.Assert(entities[2].UserDetail, nil) + + t.Assert(len(entities[0].UserScores), 2) + t.Assert(entities[0].UserScores[0], userScores[0]) + t.Assert(entities[0].UserScores[1], userScores[1]) + + t.Assert(len(entities[1].UserScores), 1) + t.Assert(entities[1].UserScores[0], userScores[2]) + + t.Assert(len(entities[2].UserScores), 0) + }) +} diff --git a/util/gconv/gconv_z_unit_slice_test.go b/util/gconv/gconv_z_unit_slice_test.go index c60749fb1..750711daa 100644 --- a/util/gconv/gconv_z_unit_slice_test.go +++ b/util/gconv/gconv_z_unit_slice_test.go @@ -7,9 +7,10 @@ package gconv_test import ( - "github.com/gogf/gf/v2/container/gvar" "testing" + "github.com/gogf/gf/v2/container/gvar" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gconv" @@ -35,6 +36,22 @@ func Test_Slice(t *testing.T) { }) } +func Test_Slice_Ints(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + t.AssertEQ(gconv.Ints(nil), nil) + t.AssertEQ(gconv.Ints("[26, 27]"), []int{26, 27}) + t.AssertEQ(gconv.Ints(" [26, 27] "), []int{26, 27}) + }) +} + +func Test_Slice_Uint64s(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + t.AssertEQ(gconv.Uint64s(nil), nil) + t.AssertEQ(gconv.Uint64s("[26, 27]"), []uint64{26, 27}) + t.AssertEQ(gconv.Uint64s(" [26, 27] "), []uint64{26, 27}) + }) +} + func Test_Slice_Empty(t *testing.T) { // Int. gtest.C(t, func(t *gtest.T) { diff --git a/util/gmeta/gmeta_bench_test.go b/util/gmeta/gmeta_z_bench_test.go similarity index 100% rename from util/gmeta/gmeta_bench_test.go rename to util/gmeta/gmeta_z_bench_test.go diff --git a/util/gmeta/gmeta_unit_test.go b/util/gmeta/gmeta_z_unit_test.go similarity index 100% rename from util/gmeta/gmeta_unit_test.go rename to util/gmeta/gmeta_z_unit_test.go index db167b2b4..d65e284a7 100644 --- a/util/gmeta/gmeta_unit_test.go +++ b/util/gmeta/gmeta_z_unit_test.go @@ -7,12 +7,12 @@ package gmeta_test import ( - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/util/gconv" - "github.com/gogf/gf/v2/util/gmeta" "testing" + "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gconv" + "github.com/gogf/gf/v2/util/gmeta" ) func TestMeta_Basic(t *testing.T) { diff --git a/util/gmode/gmode_test.go b/util/gmode/gmode_z_unit_test.go similarity index 100% rename from util/gmode/gmode_test.go rename to util/gmode/gmode_z_unit_test.go index 507cfaeb1..bbc019160 100644 --- a/util/gmode/gmode_test.go +++ b/util/gmode/gmode_z_unit_test.go @@ -9,10 +9,10 @@ package gmode_test import ( - "github.com/gogf/gf/v2/util/gmode" "testing" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gmode" ) func Test_AutoCheckSourceCodes(t *testing.T) { diff --git a/util/gpage/gpage.go b/util/gpage/gpage.go index 118fdb9cb..af400d9b7 100644 --- a/util/gpage/gpage.go +++ b/util/gpage/gpage.go @@ -9,9 +9,10 @@ package gpage import ( "fmt" + "math" + "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" - "math" ) // Page is the pagination implementer. diff --git a/util/gpage/gpage_unit_test.go b/util/gpage/gpage_z_unit_test.go similarity index 100% rename from util/gpage/gpage_unit_test.go rename to util/gpage/gpage_z_unit_test.go index 3b9e9832c..798813305 100644 --- a/util/gpage/gpage_unit_test.go +++ b/util/gpage/gpage_z_unit_test.go @@ -9,10 +9,10 @@ package gpage_test import ( - "github.com/gogf/gf/v2/util/gpage" "testing" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gpage" ) func Test_New(t *testing.T) { diff --git a/util/grand/grand_z_bench_test.go b/util/grand/grand_z_bench_test.go index 2fccac4ad..d52cdef7d 100644 --- a/util/grand/grand_z_bench_test.go +++ b/util/grand/grand_z_bench_test.go @@ -10,11 +10,11 @@ package grand_test import ( cryptoRand "crypto/rand" - mathRand "math/rand" - "encoding/binary" - "github.com/gogf/gf/v2/util/grand" + mathRand "math/rand" "testing" + + "github.com/gogf/gf/v2/util/grand" ) var ( diff --git a/util/grand/grand_z_unit_test.go b/util/grand/grand_z_unit_test.go index cea08a076..1a4a095ad 100644 --- a/util/grand/grand_z_unit_test.go +++ b/util/grand/grand_z_unit_test.go @@ -9,11 +9,11 @@ package grand_test import ( - "github.com/gogf/gf/v2/text/gstr" "testing" "time" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/grand" ) diff --git a/util/guid/guid.go b/util/guid/guid.go index 8686f31be..2259abb81 100644 --- a/util/guid/guid.go +++ b/util/guid/guid.go @@ -7,13 +7,14 @@ package guid import ( + "os" + "strconv" + "time" + "github.com/gogf/gf/v2/container/gtype" "github.com/gogf/gf/v2/encoding/ghash" "github.com/gogf/gf/v2/net/gipv4" "github.com/gogf/gf/v2/util/grand" - "os" - "strconv" - "time" ) const ( diff --git a/util/guid/guid_z_bench_test.go b/util/guid/guid_z_bench_test.go index c5b88a650..282bc76ad 100644 --- a/util/guid/guid_z_bench_test.go +++ b/util/guid/guid_z_bench_test.go @@ -9,8 +9,9 @@ package guid_test import ( - "github.com/gogf/gf/v2/util/guid" "testing" + + "github.com/gogf/gf/v2/util/guid" ) func Benchmark_S(b *testing.B) { diff --git a/util/guid/guid_z_unit_test.go b/util/guid/guid_z_unit_test.go index cbd667f0c..52d106f64 100644 --- a/util/guid/guid_z_unit_test.go +++ b/util/guid/guid_z_unit_test.go @@ -9,11 +9,11 @@ package guid_test import ( - "github.com/gogf/gf/v2/container/gset" - "github.com/gogf/gf/v2/util/guid" "testing" + "github.com/gogf/gf/v2/container/gset" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/guid" ) func Test_S(t *testing.T) { diff --git a/util/gutil/gutil.go b/util/gutil/gutil.go index b7a3ed32e..172798b1c 100644 --- a/util/gutil/gutil.go +++ b/util/gutil/gutil.go @@ -9,11 +9,12 @@ package gutil import ( "fmt" + "reflect" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/empty" "github.com/gogf/gf/v2/util/gconv" - "reflect" ) const ( diff --git a/util/gutil/gutil_dump.go b/util/gutil/gutil_dump.go index 06ed56fd5..7f264e36a 100644 --- a/util/gutil/gutil_dump.go +++ b/util/gutil/gutil_dump.go @@ -9,12 +9,24 @@ package gutil import ( "bytes" "fmt" - "github.com/gogf/gf/v2/internal/structs" - "github.com/gogf/gf/v2/text/gstr" + "io" "reflect" "strings" + + "github.com/gogf/gf/v2/internal/structs" + "github.com/gogf/gf/v2/text/gstr" ) +// iString is used for type assert api for String(). +type iString interface { + String() string +} + +// iMarshalJSON is the interface for custom Json marshaling. +type iMarshalJSON interface { + MarshalJSON() ([]byte, error) +} + // ExportOption specifies the behavior of function Export. type ExportOption struct { WithoutType bool // WithoutType specifies exported content has no type information. @@ -46,12 +58,21 @@ func DumpWithType(values ...interface{}) { // Export returns variables `values` as a string with more manually readable. func Export(value interface{}, option ExportOption) string { buffer := bytes.NewBuffer(nil) - doExport(value, "", buffer, doExportOption{ + ExportTo(buffer, value, ExportOption{ WithoutType: option.WithoutType, }) return buffer.String() } +// ExportTo writes variables `values` as a string in to `writer` with more manually readable +func ExportTo(writer io.Writer, value interface{}, option ExportOption) { + buffer := bytes.NewBuffer(nil) + doExport(value, "", buffer, doExportOption{ + WithoutType: option.WithoutType, + }) + _, _ = writer.Write(buffer.Bytes()) +} + type doExportOption struct { WithoutType bool } @@ -77,15 +98,15 @@ func doExport(value interface{}, indent string, buffer *bytes.Buffer, option doE } switch reflectKind { case reflect.Slice, reflect.Array: - if _, ok := value.([]byte); ok { + if b, ok := value.([]byte); ok { if option.WithoutType { - buffer.WriteString(fmt.Sprintf(`"%s"`, value)) + buffer.WriteString(fmt.Sprintf(`"%s"`, gstr.AddSlashes(string(b)))) } else { buffer.WriteString(fmt.Sprintf( `%s(%d) "%s"`, reflectTypeName, len(reflectValue.String()), - value, + string(b), )) } return @@ -151,7 +172,7 @@ func doExport(value interface{}, indent string, buffer *bytes.Buffer, option doE "%s%v:%s", newIndent, mapKeyStr, - gstr.Repeat(" ", maxSpaceNum-tmpSpaceNum+1), + strings.Repeat(" ", maxSpaceNum-tmpSpaceNum+1), )) } else { buffer.WriteString(fmt.Sprintf( @@ -159,7 +180,7 @@ func doExport(value interface{}, indent string, buffer *bytes.Buffer, option doE newIndent, mapKey.Type().String(), mapKeyStr, - gstr.Repeat(" ", maxSpaceNum-tmpSpaceNum+1), + strings.Repeat(" ", maxSpaceNum-tmpSpaceNum+1), )) } doExport(reflectValue.MapIndex(mapKey).Interface(), newIndent, buffer, option) @@ -173,10 +194,31 @@ func doExport(value interface{}, indent string, buffer *bytes.Buffer, option doE RecursiveOption: structs.RecursiveOptionEmbeddedNoTag, }) if len(structFields) == 0 { - if option.WithoutType { - buffer.WriteString("{}") + var ( + structContentStr = "" + attributeCountStr = "0" + ) + if v, ok := value.(iString); ok { + structContentStr = v.String() + } else if v, ok := value.(iMarshalJSON); ok { + b, _ := v.MarshalJSON() + structContentStr = string(b) + } + if structContentStr == "" { + structContentStr = "{}" } else { - buffer.WriteString(fmt.Sprintf("%s(0) {}", reflectTypeName)) + structContentStr = fmt.Sprintf(`"%s"`, gstr.AddSlashes(structContentStr)) + attributeCountStr = fmt.Sprintf(`%d`, len(structContentStr)-2) + } + if option.WithoutType { + buffer.WriteString(structContentStr) + } else { + buffer.WriteString(fmt.Sprintf( + "%s(%s) %s", + reflectTypeName, + attributeCountStr, + structContentStr, + )) } return } @@ -202,7 +244,7 @@ func doExport(value interface{}, indent string, buffer *bytes.Buffer, option doE "%s%s:%s", newIndent, field.Name(), - gstr.Repeat(" ", maxSpaceNum-tmpSpaceNum+1), + strings.Repeat(" ", maxSpaceNum-tmpSpaceNum+1), )) doExport(field.Value.Interface(), newIndent, buffer, option) buffer.WriteString(",\n") @@ -210,14 +252,15 @@ func doExport(value interface{}, indent string, buffer *bytes.Buffer, option doE buffer.WriteString(fmt.Sprintf("%s}", indent)) case reflect.String: + s, _ := value.(string) if option.WithoutType { - buffer.WriteString(fmt.Sprintf("\"%v\"", value)) + buffer.WriteString(fmt.Sprintf(`"%v"`, gstr.AddSlashes(s))) } else { buffer.WriteString(fmt.Sprintf( - "%s(%d) \"%v\"", + `%s(%d) "%v"`, reflectTypeName, len(reflectValue.String()), - value, + gstr.AddSlashes(s), )) } diff --git a/util/gutil/gutil_list.go b/util/gutil/gutil_list.go index 14fd8e2f6..9a60a3182 100644 --- a/util/gutil/gutil_list.go +++ b/util/gutil/gutil_list.go @@ -8,6 +8,8 @@ package gutil import ( "reflect" + + "github.com/gogf/gf/v2/internal/utils" ) // ListItemValues retrieves and returns the elements of all item struct/map with key `key`. @@ -130,3 +132,9 @@ func ListItemValuesUnique(list interface{}, key string, subKey ...interface{}) [ } return values } + +// ListToMapByKey converts `list` to a map[string]interface{} of which key is specified by `key`. +// Note that the item value may be type of slice. +func ListToMapByKey(list []map[string]interface{}, key string) map[string]interface{} { + return utils.ListToMapByKey(list, key) +} diff --git a/util/gutil/gutil_map.go b/util/gutil/gutil_map.go index 1a9b96029..8be8af5a6 100644 --- a/util/gutil/gutil_map.go +++ b/util/gutil/gutil_map.go @@ -7,8 +7,9 @@ package gutil import ( - "github.com/gogf/gf/v2/internal/utils" "reflect" + + "github.com/gogf/gf/v2/internal/utils" ) // MapCopy does a shallow copy from map `data` to `copy` for most commonly used map type @@ -67,19 +68,7 @@ func MapMergeCopy(src ...map[string]interface{}) (copy map[string]interface{}) { // // Note that this function might be of low performance. func MapPossibleItemByKey(data map[string]interface{}, key string) (foundKey string, foundValue interface{}) { - if len(data) == 0 { - return - } - if v, ok := data[key]; ok { - return key, v - } - // Loop checking. - for k, v := range data { - if utils.EqualFoldWithoutChars(k, key) { - return k, v - } - } - return "", nil + return utils.MapPossibleItemByKey(data, key) } // MapContainsPossibleKey checks if the given `key` is contained in given map `data`. diff --git a/util/gutil/gutil_slice.go b/util/gutil/gutil_slice.go index 67b61ddab..a9af34220 100644 --- a/util/gutil/gutil_slice.go +++ b/util/gutil/gutil_slice.go @@ -7,8 +7,9 @@ package gutil import ( - "github.com/gogf/gf/v2/util/gconv" "reflect" + + "github.com/gogf/gf/v2/util/gconv" ) // SliceCopy does a shallow copy of slice `data` for most commonly used slice type diff --git a/util/gutil/gutil_struct.go b/util/gutil/gutil_struct.go index e02c3e471..bd856fc4b 100644 --- a/util/gutil/gutil_struct.go +++ b/util/gutil/gutil_struct.go @@ -7,8 +7,9 @@ package gutil import ( - "github.com/gogf/gf/v2/util/gconv" "reflect" + + "github.com/gogf/gf/v2/util/gconv" ) // StructToSlice converts struct to slice of which all keys and values are its items. diff --git a/util/gutil/gutil_z_unit_dump_test.go b/util/gutil/gutil_z_unit_dump_test.go new file mode 100755 index 000000000..d90052643 --- /dev/null +++ b/util/gutil/gutil_z_unit_dump_test.go @@ -0,0 +1,144 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +package gutil_test + +import ( + "testing" + + "github.com/gogf/gf/v2/net/ghttp" + "github.com/gogf/gf/v2/os/gtime" + "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gmeta" + "github.com/gogf/gf/v2/util/gutil" +) + +func Test_Dump(t *testing.T) { + type CommonReq struct { + AppId int64 `json:"appId" v:"required" in:"path" des:"应用Id" sum:"应用Id Summary"` + ResourceId string `json:"resourceId" in:"query" des:"资源Id" sum:"资源Id Summary"` + } + type SetSpecInfo struct { + StorageType string `v:"required|in:CLOUD_PREMIUM,CLOUD_SSD,CLOUD_HSSD" des:"StorageType"` + Shards int32 `des:"shards 分片数" sum:"Shards Summary"` + Params []string `des:"默认参数(json 串-ClickHouseParams)" sum:"Params Summary"` + } + type CreateResourceReq struct { + CommonReq + gmeta.Meta `path:"/CreateResourceReq" method:"POST" tags:"default" sum:"CreateResourceReq sum"` + Name string + CreatedAt *gtime.Time + SetMap map[string]*SetSpecInfo + SetSlice []SetSpecInfo + Handler ghttp.HandlerFunc + internal string + } + req := &CreateResourceReq{ + CommonReq: CommonReq{ + AppId: 12345678, + ResourceId: "tdchqy-xxx", + }, + Name: "john", + CreatedAt: gtime.Now(), + SetMap: map[string]*SetSpecInfo{ + "test1": { + StorageType: "ssd", + Shards: 2, + Params: []string{"a", "b", "c"}, + }, + "test2": { + StorageType: "hssd", + Shards: 10, + Params: []string{}, + }, + }, + SetSlice: []SetSpecInfo{ + { + StorageType: "hssd", + Shards: 10, + Params: []string{"h"}, + }, + }, + } + gtest.C(t, func(t *gtest.T) { + gutil.Dump(map[int]int{ + 100: 100, + }) + gutil.Dump(req) + }) +} + +func TestDumpWithType(t *testing.T) { + type CommonReq struct { + AppId int64 `json:"appId" v:"required" in:"path" des:"应用Id" sum:"应用Id Summary"` + ResourceId string `json:"resourceId" in:"query" des:"资源Id" sum:"资源Id Summary"` + } + type SetSpecInfo struct { + StorageType string `v:"required|in:CLOUD_PREMIUM,CLOUD_SSD,CLOUD_HSSD" des:"StorageType"` + Shards int32 `des:"shards 分片数" sum:"Shards Summary"` + Params []string `des:"默认参数(json 串-ClickHouseParams)" sum:"Params Summary"` + } + type CreateResourceReq struct { + CommonReq + gmeta.Meta `path:"/CreateResourceReq" method:"POST" tags:"default" sum:"CreateResourceReq sum"` + Name string + CreatedAt *gtime.Time + SetMap map[string]*SetSpecInfo `v:"required" des:"配置Map"` + SetSlice []SetSpecInfo `v:"required" des:"配置Slice"` + Handler ghttp.HandlerFunc + internal string + } + req := &CreateResourceReq{ + CommonReq: CommonReq{ + AppId: 12345678, + ResourceId: "tdchqy-xxx", + }, + Name: "john", + CreatedAt: gtime.Now(), + SetMap: map[string]*SetSpecInfo{ + "test1": { + StorageType: "ssd", + Shards: 2, + Params: []string{"a", "b", "c"}, + }, + "test2": { + StorageType: "hssd", + Shards: 10, + Params: []string{}, + }, + }, + SetSlice: []SetSpecInfo{ + { + StorageType: "hssd", + Shards: 10, + Params: []string{"h"}, + }, + }, + } + gtest.C(t, func(t *gtest.T) { + gutil.DumpWithType(map[int]int{ + 100: 100, + }) + gutil.DumpWithType(req) + gutil.DumpWithType([][]byte{[]byte("hello")}) + }) +} + +func Test_Dump_Slashes(t *testing.T) { + type Req struct { + Content string + } + req := &Req{ + Content: `{"name":"john", "age":18}`, + } + gtest.C(t, func(t *gtest.T) { + gutil.Dump(req) + gutil.Dump(req.Content) + + gutil.DumpWithType(req) + gutil.DumpWithType(req.Content) + }) +} diff --git a/util/gutil/gutil_z_unit_list_test.go b/util/gutil/gutil_z_unit_list_test.go index a324a4a58..7b731cd14 100755 --- a/util/gutil/gutil_z_unit_list_test.go +++ b/util/gutil/gutil_z_unit_list_test.go @@ -7,9 +7,9 @@ package gutil_test import ( - "github.com/gogf/gf/v2/frame/g" "testing" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gutil" ) diff --git a/util/gutil/gutil_z_unit_map_test.go b/util/gutil/gutil_z_unit_map_test.go index c7caa5ecb..b51939e43 100755 --- a/util/gutil/gutil_z_unit_map_test.go +++ b/util/gutil/gutil_z_unit_map_test.go @@ -7,9 +7,9 @@ package gutil_test import ( - "github.com/gogf/gf/v2/frame/g" "testing" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gutil" ) diff --git a/util/gutil/gutil_z_unit_slice_test.go b/util/gutil/gutil_z_unit_slice_test.go index 5e9bb5155..08c37d480 100755 --- a/util/gutil/gutil_z_unit_slice_test.go +++ b/util/gutil/gutil_z_unit_slice_test.go @@ -7,9 +7,9 @@ package gutil_test import ( - "github.com/gogf/gf/v2/frame/g" "testing" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gutil" ) diff --git a/util/gutil/gutil_z_unit_struct_test.go b/util/gutil/gutil_z_unit_struct_test.go index cf4a1685d..20ea6dcae 100755 --- a/util/gutil/gutil_z_unit_struct_test.go +++ b/util/gutil/gutil_z_unit_struct_test.go @@ -7,9 +7,9 @@ package gutil_test import ( - "github.com/gogf/gf/v2/frame/g" "testing" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gutil" ) diff --git a/util/gutil/gutil_z_unit_test.go b/util/gutil/gutil_z_unit_test.go index 253b89373..fe69defc1 100755 --- a/util/gutil/gutil_z_unit_test.go +++ b/util/gutil/gutil_z_unit_test.go @@ -7,130 +7,13 @@ package gutil_test import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/util/gmeta" "testing" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gutil" ) -func Test_Dump(t *testing.T) { - type CommonReq struct { - AppId int64 `json:"appId" v:"required" in:"path" des:"应用Id" sum:"应用Id Summary"` - ResourceId string `json:"resourceId" in:"query" des:"资源Id" sum:"资源Id Summary"` - } - type SetSpecInfo struct { - StorageType string `v:"required|in:CLOUD_PREMIUM,CLOUD_SSD,CLOUD_HSSD" des:"StorageType"` - Shards int32 `des:"shards 分片数" sum:"Shards Summary"` - Params []string `des:"默认参数(json 串-ClickHouseParams)" sum:"Params Summary"` - } - type CreateResourceReq struct { - CommonReq - gmeta.Meta `path:"/CreateResourceReq" method:"POST" tags:"default" sum:"CreateResourceReq sum"` - Name string `des:"实例名称"` - Product string `des:"业务类型"` - Region string `v:"required" des:"区域"` - SetMap map[string]*SetSpecInfo `v:"required" des:"配置Map"` - SetSlice []SetSpecInfo `v:"required" des:"配置Slice"` - Handler ghttp.HandlerFunc - internal string - } - req := &CreateResourceReq{ - CommonReq: CommonReq{ - AppId: 12345678, - ResourceId: "tdchqy-xxx", - }, - Name: "john", - Product: "goframe", - Region: "cd", - SetMap: map[string]*SetSpecInfo{ - "test1": { - StorageType: "ssd", - Shards: 2, - Params: []string{"a", "b", "c"}, - }, - "test2": { - StorageType: "hssd", - Shards: 10, - Params: []string{}, - }, - }, - SetSlice: []SetSpecInfo{ - { - StorageType: "hssd", - Shards: 10, - Params: []string{"h"}, - }, - }, - } - gtest.C(t, func(t *gtest.T) { - gutil.Dump(map[int]int{ - 100: 100, - }) - gutil.Dump(req) - }) -} - -func TestDumpWithType(t *testing.T) { - type CommonReq struct { - AppId int64 `json:"appId" v:"required" in:"path" des:"应用Id" sum:"应用Id Summary"` - ResourceId string `json:"resourceId" in:"query" des:"资源Id" sum:"资源Id Summary"` - } - type SetSpecInfo struct { - StorageType string `v:"required|in:CLOUD_PREMIUM,CLOUD_SSD,CLOUD_HSSD" des:"StorageType"` - Shards int32 `des:"shards 分片数" sum:"Shards Summary"` - Params []string `des:"默认参数(json 串-ClickHouseParams)" sum:"Params Summary"` - } - type CreateResourceReq struct { - CommonReq - gmeta.Meta `path:"/CreateResourceReq" method:"POST" tags:"default" sum:"CreateResourceReq sum"` - Name string `des:"实例名称"` - Product string `des:"业务类型"` - Region string `v:"required" des:"区域"` - SetMap map[string]*SetSpecInfo `v:"required" des:"配置Map"` - SetSlice []SetSpecInfo `v:"required" des:"配置Slice"` - Handler ghttp.HandlerFunc - internal string - } - req := &CreateResourceReq{ - CommonReq: CommonReq{ - AppId: 12345678, - ResourceId: "tdchqy-xxx", - }, - Name: "john", - Product: "goframe", - Region: "cd", - SetMap: map[string]*SetSpecInfo{ - "test1": { - StorageType: "ssd", - Shards: 2, - Params: []string{"a", "b", "c"}, - }, - "test2": { - StorageType: "hssd", - Shards: 10, - Params: []string{}, - }, - }, - SetSlice: []SetSpecInfo{ - { - StorageType: "hssd", - Shards: 10, - Params: []string{"h"}, - }, - }, - } - gtest.C(t, func(t *gtest.T) { - gutil.DumpWithType(map[int]int{ - 100: 100, - }) - gutil.DumpWithType(req) - gutil.DumpWithType([][]byte{[]byte("hello")}) - }) -} - func Test_Try(t *testing.T) { gtest.C(t, func(t *gtest.T) { s := `gutil Try test` diff --git a/util/gvalid/gvalid.go b/util/gvalid/gvalid.go index f1fa06bcd..5c358ee9f 100644 --- a/util/gvalid/gvalid.go +++ b/util/gvalid/gvalid.go @@ -186,52 +186,51 @@ var ( // defaultMessages is the default error messages. // Note that these messages are synchronized from ./i18n/en/validation.toml . defaultMessages = map[string]string{ - "required": "The :attribute field is required", - "required-if": "The :attribute field is required", - "required-unless": "The :attribute field is required", - "required-with": "The :attribute field is required", - "required-with-all": "The :attribute field is required", - "required-without": "The :attribute field is required", - "required-without-all": "The :attribute field is required", - "date": "The :attribute value is not a valid date", - "datetime": "The :attribute value is not a valid datetime", - "date-format": "The :attribute value does not match the format :format", - "email": "The :attribute value must be a valid email address", - "phone": "The :attribute value must be a valid phone number", - "telephone": "The :attribute value must be a valid telephone number", - "passport": "The :attribute value is not a valid passport format", - "password": "The :attribute value is not a valid passport format", - "password2": "The :attribute value is not a valid passport format", - "password3": "The :attribute value is not a valid passport format", - "postcode": "The :attribute value is not a valid passport format", - "resident-id": "The :attribute value is not a valid resident id number", - "bank-card": "The :attribute value must be a valid bank card number", - "qq": "The :attribute value must be a valid QQ number", - "ip": "The :attribute value must be a valid IP address", - "ipv4": "The :attribute value must be a valid IPv4 address", - "ipv6": "The :attribute value must be a valid IPv6 address", - "mac": "The :attribute value must be a valid MAC address", - "url": "The :attribute value must be a valid URL address", - "domain": "The :attribute value must be a valid domain format", - "length": "The :attribute value length must be between :min and :max", - "min-length": "The :attribute value length must be equal or greater than :min", - "max-length": "The :attribute value length must be equal or lesser than :max", - "size": "The :attribute value length must be :size", - "between": "The :attribute value must be between :min and :max", - "min": "The :attribute value must be equal or greater than :min", - "max": "The :attribute value must be equal or lesser than :max", - "json": "The :attribute value must be a valid JSON string", - "xml": "The :attribute value must be a valid XML string", - "array": "The :attribute value must be an array", - "integer": "The :attribute value must be an integer", - "float": "The :attribute value must be a float", - "boolean": "The :attribute value field must be true or false", - "same": "The :attribute value must be the same as field :field", - "different": "The :attribute value must be different from field :field", - "in": "The :attribute value is not in acceptable range", - "not-in": "The :attribute value is not in acceptable range", - "regex": "The :attribute value is invalid", - internalDefaultRuleName: "The :attribute value is invalid", + "required": "The {attribute} field is required", + "required-if": "The {attribute} field is required", + "required-unless": "The {attribute} field is required", + "required-with": "The {attribute} field is required", + "required-with-all": "The {attribute} field is required", + "required-without": "The {attribute} field is required", + "required-without-all": "The {attribute} field is required", + "date": "The {attribute} value `{value}` is not a valid date", + "datetime": "The {attribute} value `{value}` is not a valid datetime", + "date-format": "The {attribute} value `{value}` does not match the format: {pattern}", + "email": "The {attribute} value `{value}` is not a valid email address", + "phone": "The {attribute} value `{value}` is not a valid phone number", + "telephone": "The {attribute} value `{value}` is not a valid telephone number", + "passport": "The {attribute} value `{value}` is not a valid passport format", + "password": "The {attribute} value `{value}` is not a valid password format", + "password2": "The {attribute} value `{value}` is not a valid password format", + "password3": "The {attribute} value `{value}` is not a valid password format", + "postcode": "The {attribute} value `{value}` is not a valid postcode format", + "resident-id": "The {attribute} value `{value}` is not a valid resident id number", + "bank-card": "The {attribute} value `{value}` is not a valid bank card number", + "qq": "The {attribute} value `{value}` is not a valid QQ number", + "ip": "The {attribute} value `{value}` is not a valid IP address", + "ipv4": "The {attribute} value `{value}` is not a valid IPv4 address", + "ipv6": "The {attribute} value `{value}` is not a valid IPv6 address", + "mac": "The {attribute} value `{value}` is not a valid MAC address", + "url": "The {attribute} value `{value}` is not a valid URL address", + "domain": "The {attribute} value `{value}` is not a valid domain format", + "length": "The {attribute} value `{value}` length must be between {min} and {max}", + "min-length": "The {attribute} value `{value}` length must be equal or greater than {min}", + "max-length": "The {attribute} value `{value}` length must be equal or lesser than {max}", + "size": "The {attribute} value `{value}` length must be {size}", + "between": "The {attribute} value `{value}` must be between {min} and {max}", + "min": "The {attribute} value `{value}` must be equal or greater than {min}", + "max": "The {attribute} value `{value}` must be equal or lesser than {max}", + "json": "The {attribute} value `{value}` is not a valid JSON string", + "xml": "The {attribute} value `{value}` is not a valid XML string", + "array": "The {attribute} value `{value}` is not an array", + "integer": "The {attribute} value `{value}` is not an integer", + "boolean": "The {attribute} value `{value}` field must be true or false", + "same": "The {attribute} value `{value}` must be the same as field {pattern}", + "different": "The {attribute} value `{value}` must be different from field {pattern}", + "in": "The {attribute} value `{value}` is not in acceptable range: {pattern}", + "not-in": "The {attribute} value `{value}` must not be in range: {pattern}", + "regex": "The {attribute} value `{value}` must be in regex of: {pattern}", + internalDefaultRuleName: "The {attribute} value `{value}` is invalid", } // markedRuleMap defines all rules that are just marked rules which have neither functional meaning // nor error messages. diff --git a/util/gvalid/gvalid_custom_rule.go b/util/gvalid/gvalid_custom_rule.go index 418e9f95f..73dc0e648 100644 --- a/util/gvalid/gvalid_custom_rule.go +++ b/util/gvalid/gvalid_custom_rule.go @@ -6,16 +6,30 @@ package gvalid -import "context" +import ( + "context" + + "github.com/gogf/gf/v2/container/gvar" +) // RuleFunc is the custom function for data validation. -// -// The parameter `rule` specifies the validation rule string, like "required", "between:1,100", etc. -// The parameter `value` specifies the value for this rule to validate. -// The parameter `message` specifies the custom error message or configured i18n message for this rule. -// The parameter `data` specifies the `data` which is passed to the Validator. It might be a type of map/struct or a nil value. -// You can ignore the parameter `data` if you do not really need it in your custom validation rule. -type RuleFunc func(ctx context.Context, rule string, value interface{}, message string, data interface{}) error +type RuleFunc func(ctx context.Context, in RuleFuncInput) error + +// RuleFuncInput holds the input parameters that passed to custom rule function RuleFunc. +type RuleFuncInput struct { + // Rule specifies the validation rule string, like "required", "between:1,100", etc. + Rule string + + // Message specifies the custom error message or configured i18n message for this rule. + Message string + + // Value specifies the value for this rule to validate. + Value *gvar.Var + + // Data specifies the `data` which is passed to the Validator. It might be a type of map/struct or a nil value. + // You can ignore the parameter `Data` if you do not really need it in your custom validation rule. + Data *gvar.Var +} var ( // customRuleFuncMap stores the custom rule functions. @@ -24,13 +38,20 @@ var ( ) // RegisterRule registers custom validation rule and function for package. -// It returns error if there's already the same rule registered previously. -func RegisterRule(rule string, f RuleFunc) error { +func RegisterRule(rule string, f RuleFunc) { customRuleFuncMap[rule] = f - return nil } -// DeleteRule deletes custom defined validation rule and its function from global package. -func DeleteRule(rule string) { - delete(customRuleFuncMap, rule) +// RegisterRuleByMap registers custom validation rules using map for package. +func RegisterRuleByMap(m map[string]RuleFunc) { + for k, v := range m { + customRuleFuncMap[k] = v + } +} + +// DeleteRule deletes custom defined validation one or more rules and associated functions from global package. +func DeleteRule(rules ...string) { + for _, rule := range rules { + delete(customRuleFuncMap, rule) + } } diff --git a/util/gvalid/gvalid_error.go b/util/gvalid/gvalid_error.go index 08f553fd7..ba252d8c6 100644 --- a/util/gvalid/gvalid_error.go +++ b/util/gvalid/gvalid_error.go @@ -7,11 +7,11 @@ package gvalid import ( + "strings" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/text/gregex" "github.com/gogf/gf/v2/text/gstr" - "strings" ) // Error is the validation error for validation result. @@ -19,50 +19,57 @@ type Error interface { Code() gcode.Code Current() error Error() string - FirstItem() (key string, messages map[string]string) - FirstRule() (rule string, err string) - FirstString() (err string) - Items() (items []map[string]map[string]string) - Map() map[string]string - Maps() map[string]map[string]string + FirstItem() (key string, messages map[string]error) + FirstRule() (rule string, err error) + FirstError() (err error) + Items() (items []map[string]map[string]error) + Map() map[string]error + Maps() map[string]map[string]error String() string Strings() (errs []string) } // validationError is the validation error for validation result. type validationError struct { - code gcode.Code // Error code. - rules []fieldRule // Rules by sequence, which is used for keeping error sequence. - errors map[string]map[string]string // Error map:map[field]map[rule]message - firstKey string // The first error rule key(empty in default). - firstItem map[string]string // The first error rule value(nil in default). + code gcode.Code // Error code. + rules []fieldRule // Rules by sequence, which is used for keeping error sequence. + errors map[string]map[string]error // Error map:map[field]map[rule]message + firstKey string // The first error rule key(empty in default). + firstItem map[string]error // The first error rule value(nil in default). } -// newError creates and returns a validation error. -func newError(code gcode.Code, rules []fieldRule, errors map[string]map[string]string) *validationError { - for field, m := range errors { - for k, v := range m { - v = strings.Replace(v, ":attribute", field, -1) - v, _ = gregex.ReplaceString(`\s{2,}`, ` `, v) - v = gstr.Trim(v) - m[k] = v +// newValidationError creates and returns a validation error. +func newValidationError(code gcode.Code, rules []fieldRule, fieldRuleErrorMap map[string]map[string]error) *validationError { + for field, ruleErrorMap := range fieldRuleErrorMap { + for rule, err := range ruleErrorMap { + if !gerror.HasStack(err) { + ruleErrorMap[rule] = gerror.NewOption(gerror.Option{ + Stack: false, + Text: gstr.Trim(err.Error()), + Code: code, + }) + } } - errors[field] = m + fieldRuleErrorMap[field] = ruleErrorMap } return &validationError{ code: code, rules: rules, - errors: errors, + errors: fieldRuleErrorMap, } } -// newErrorStr creates and returns a validation error by string. -func newErrorStr(key, err string) *validationError { - return newError(gcode.CodeInternalError, nil, map[string]map[string]string{ - internalErrorMapKey: { - key: err, +// newValidationErrorByStr creates and returns a validation error by string. +func newValidationErrorByStr(key string, err error) *validationError { + return newValidationError( + gcode.CodeInternalError, + nil, + map[string]map[string]error{ + internalErrorMapKey: { + key: err, + }, }, - }) + ) } // Code returns the error code of current validation error. @@ -74,16 +81,16 @@ func (e *validationError) Code() gcode.Code { } // Map returns the first error message as map. -func (e *validationError) Map() map[string]string { +func (e *validationError) Map() map[string]error { if e == nil { - return map[string]string{} + return map[string]error{} } _, m := e.FirstItem() return m } // Maps returns all error messages as map. -func (e *validationError) Maps() map[string]map[string]string { +func (e *validationError) Maps() map[string]map[string]error { if e == nil { return nil } @@ -92,16 +99,16 @@ func (e *validationError) Maps() map[string]map[string]string { // Items retrieves and returns error items array in sequence if possible, // or else it returns error items with no sequence . -func (e *validationError) Items() (items []map[string]map[string]string) { +func (e *validationError) Items() (items []map[string]map[string]error) { if e == nil { - return []map[string]map[string]string{} + return []map[string]map[string]error{} } - items = make([]map[string]map[string]string, 0) + items = make([]map[string]map[string]error, 0) // By sequence. if len(e.rules) > 0 { for _, v := range e.rules { if errorItemMap, ok := e.errors[v.Name]; ok { - items = append(items, map[string]map[string]string{ + items = append(items, map[string]map[string]error{ v.Name: errorItemMap, }) } @@ -110,7 +117,7 @@ func (e *validationError) Items() (items []map[string]map[string]string) { } // No sequence. for name, errorRuleMap := range e.errors { - items = append(items, map[string]map[string]string{ + items = append(items, map[string]map[string]error{ name: errorRuleMap, }) } @@ -118,9 +125,9 @@ func (e *validationError) Items() (items []map[string]map[string]string) { } // FirstItem returns the field name and error messages for the first validation rule error. -func (e *validationError) FirstItem() (key string, messages map[string]string) { +func (e *validationError) FirstItem() (key string, messages map[string]error) { if e == nil { - return "", map[string]string{} + return "", map[string]error{} } if e.firstItem != nil { return e.firstKey, e.firstItem @@ -145,9 +152,9 @@ func (e *validationError) FirstItem() (key string, messages map[string]string) { } // FirstRule returns the first error rule and message string. -func (e *validationError) FirstRule() (rule string, err string) { +func (e *validationError) FirstRule() (rule string, err error) { if e == nil { - return "", "" + return "", nil } // By sequence. if len(e.rules) > 0 { @@ -169,26 +176,22 @@ func (e *validationError) FirstRule() (rule string, err string) { return k, v } } - return "", "" + return "", nil } -// FirstString returns the first error message as string. +// FirstError returns the first error message as string. // Note that the returned message might be different if it has no sequence. -func (e *validationError) FirstString() (err string) { +func (e *validationError) FirstError() (err error) { if e == nil { - return "" + return nil } _, err = e.FirstRule() return } -// Current is alis of FirstString, which implements interface gerror.iCurrent. +// Current is alis of FirstError, which implements interface gerror.iCurrent. func (e *validationError) Current() error { - if e == nil { - return nil - } - _, err := e.FirstRule() - return gerror.NewCode(e.code, err) + return e.FirstError() } // String returns all error messages as string, multiple error messages joined using char ';'. @@ -221,13 +224,13 @@ func (e *validationError) Strings() (errs []string) { for _, ruleItem := range strings.Split(v.Rule, "|") { ruleItem = strings.TrimSpace(strings.Split(ruleItem, ":")[0]) if err, ok := errorItemMap[ruleItem]; ok { - errs = append(errs, err) + errs = append(errs, err.Error()) } } // internal error checks. for k, _ := range internalErrKeyMap { if err, ok := errorItemMap[k]; ok { - errs = append(errs, err) + errs = append(errs, err.Error()) } } } @@ -237,7 +240,7 @@ func (e *validationError) Strings() (errs []string) { // No sequence. for _, errorItemMap := range e.errors { for _, err := range errorItemMap { - errs = append(errs, err) + errs = append(errs, err.Error()) } } return diff --git a/util/gvalid/gvalid_validator_check_map.go b/util/gvalid/gvalid_validator_check_map.go index e3f10fa56..9bbf3d62a 100644 --- a/util/gvalid/gvalid_validator_check_map.go +++ b/util/gvalid/gvalid_validator_check_map.go @@ -8,9 +8,11 @@ package gvalid import ( "context" + "errors" + "strings" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/util/gconv" - "strings" ) // CheckMap validates map and returns the error result. It returns nil if with successful validation. @@ -27,7 +29,7 @@ func (v *Validator) doCheckMap(ctx context.Context, params interface{}) Error { var ( checkRules = make([]fieldRule, 0) customMessage = make(CustomMsg) // map[RuleKey]ErrorMsg. - errorMaps = make(map[string]map[string]string) + errorMaps = make(map[string]map[string]error) ) switch assertValue := v.rules.(type) { // Sequence tag: []sequence tag @@ -80,9 +82,9 @@ func (v *Validator) doCheckMap(ctx context.Context, params interface{}) Error { } data := gconv.Map(params) if data == nil { - return newErrorStr( + return newValidationErrorByStr( internalParamsErrRuleName, - "invalid params type: convert to map failed", + errors.New("invalid params type: convert to map failed"), ) } if msg, ok := v.messages.(CustomMsg); ok && len(msg) > 0 { @@ -116,8 +118,9 @@ func (v *Validator) doCheckMap(ctx context.Context, params interface{}) Error { }); validatedError != nil { _, errorItem := validatedError.FirstItem() // =========================================================== - // Only in map and struct validations, if value is nil or empty - // string and has no required* rules, it clears the error message. + // Only in map and struct validations: + // If value is nil or empty string and has no required* rules, + // it clears the error message. // =========================================================== if gconv.String(value) == "" { required := false @@ -128,21 +131,16 @@ func (v *Validator) doCheckMap(ctx context.Context, params interface{}) Error { required = true break } - // Custom rules are also required in default. - if f := v.getRuleFunc(ruleKey); f != nil { - required = true - break - } } if !required { continue } } if _, ok := errorMaps[checkRuleItem.Name]; !ok { - errorMaps[checkRuleItem.Name] = make(map[string]string) + errorMaps[checkRuleItem.Name] = make(map[string]error) } - for ruleKey, errorItemMsgMap := range errorItem { - errorMaps[checkRuleItem.Name][ruleKey] = errorItemMsgMap + for ruleKey, ruleError := range errorItem { + errorMaps[checkRuleItem.Name][ruleKey] = ruleError } if v.bail { break @@ -150,7 +148,7 @@ func (v *Validator) doCheckMap(ctx context.Context, params interface{}) Error { } } if len(errorMaps) > 0 { - return newError(gcode.CodeValidationFailed, checkRules, errorMaps) + return newValidationError(gcode.CodeValidationFailed, checkRules, errorMaps) } return nil } diff --git a/util/gvalid/gvalid_validator_check_struct.go b/util/gvalid/gvalid_validator_check_struct.go index 878e8a728..7b6c1d5bc 100644 --- a/util/gvalid/gvalid_validator_check_struct.go +++ b/util/gvalid/gvalid_validator_check_struct.go @@ -8,11 +8,12 @@ package gvalid import ( "context" + "strings" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/internal/structs" "github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/gutil" - "strings" ) // CheckStruct validates struct and returns the error result. @@ -23,8 +24,8 @@ func (v *Validator) CheckStruct(ctx context.Context, object interface{}) Error { func (v *Validator) doCheckStruct(ctx context.Context, object interface{}) Error { var ( - errorMaps = make(map[string]map[string]string) // Returning error. - fieldToAliasNameMap = make(map[string]string) // Field names to alias name map. + errorMaps = make(map[string]map[string]error) // Returning error. + fieldToAliasNameMap = make(map[string]string) // Field names to alias name map. ) fieldMap, err := structs.FieldMap(structs.FieldMapInput{ Pointer: object, @@ -32,7 +33,7 @@ func (v *Validator) doCheckStruct(ctx context.Context, object interface{}) Error RecursiveOption: structs.RecursiveOptionEmbedded, }) if err != nil { - return newErrorStr(internalObjectErrRuleName, err.Error()) + return newValidationErrorByStr(internalObjectErrRuleName, err) } // It checks the struct recursively if its attribute is an embedded struct. for _, field := range fieldMap { @@ -59,7 +60,7 @@ func (v *Validator) doCheckStruct(ctx context.Context, object interface{}) Error // It here must use structs.TagFields not structs.FieldMap to ensure error sequence. tagField, err := structs.TagFields(object, structTagPriority) if err != nil { - return newErrorStr(internalObjectErrRuleName, err.Error()) + return newValidationErrorByStr(internalObjectErrRuleName, err) } // If there's no struct tag and validation rules, it does nothing and returns quickly. if len(tagField) == 0 && v.messages == nil { @@ -178,7 +179,7 @@ func (v *Validator) doCheckStruct(ctx context.Context, object interface{}) Error } if _, ok := nameToRuleMap[name]; !ok { - if _, ok := nameToRuleMap[fieldName]; ok { + if _, ok = nameToRuleMap[fieldName]; ok { // If there's alias name, // use alias name as its key and remove the field name key. nameToRuleMap[name] = nameToRuleMap[fieldName] @@ -254,10 +255,11 @@ func (v *Validator) doCheckStruct(ctx context.Context, object interface{}) Error DataMap: inputParamMap, }); validatedError != nil { _, errorItem := validatedError.FirstItem() - // =================================================================== - // Only in map and struct validations, if value is nil or empty string - // and has no required* rules, it clears the error message. - // =================================================================== + // ============================================================ + // Only in map and struct validations: + // If value is nil or empty string and has no required* rules, + // it clears the error message. + // ============================================================ if value == nil || gconv.String(value) == "" { required := false // rule => error @@ -267,18 +269,13 @@ func (v *Validator) doCheckStruct(ctx context.Context, object interface{}) Error required = true break } - // Custom rules are also required in default. - if f := v.getRuleFunc(ruleKey); f != nil { - required = true - break - } } if !required { continue } } if _, ok := errorMaps[checkRuleItem.Name]; !ok { - errorMaps[checkRuleItem.Name] = make(map[string]string) + errorMaps[checkRuleItem.Name] = make(map[string]error) } for ruleKey, errorItemMsgMap := range errorItem { errorMaps[checkRuleItem.Name][ruleKey] = errorItemMsgMap @@ -289,7 +286,7 @@ func (v *Validator) doCheckStruct(ctx context.Context, object interface{}) Error } } if len(errorMaps) > 0 { - return newError(gcode.CodeValidationFailed, checkRules, errorMaps) + return newValidationError(gcode.CodeValidationFailed, checkRules, errorMaps) } return nil } diff --git a/util/gvalid/gvalid_validator_check_value.go b/util/gvalid/gvalid_validator_check_value.go index 36176f361..0cfa78fcc 100644 --- a/util/gvalid/gvalid_validator_check_value.go +++ b/util/gvalid/gvalid_validator_check_value.go @@ -8,18 +8,20 @@ package gvalid import ( "context" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/text/gstr" + "errors" "strconv" "strings" "time" + "github.com/gogf/gf/v2/container/gvar" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/net/gipv4" "github.com/gogf/gf/v2/net/gipv6" "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/text/gregex" + "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/gutil" ) @@ -60,19 +62,19 @@ func (v *Validator) doCheckValue(ctx context.Context, input doCheckValueInput) E // It converts value to string and then does the validation. var ( // Do not trim it as the space is also part of the value. - errorMsgArray = make(map[string]string) + ruleErrorMap = make(map[string]error) ) // Custom error messages handling. var ( msgArray = make([]string, 0) customMsgMap = make(map[string]string) ) - switch v := input.Messages.(type) { + switch messages := input.Messages.(type) { case string: - msgArray = strings.Split(v, "|") + msgArray = strings.Split(messages, "|") default: - for k, v := range gconv.Map(input.Messages) { - customMsgMap[k] = gconv.String(v) + for k, message := range gconv.Map(input.Messages) { + customMsgMap[k] = gconv.String(message) } } // Handle the char '|' in the rule, @@ -86,9 +88,9 @@ func (v *Validator) doCheckValue(ctx context.Context, input doCheckValueInput) E ruleItems[i-1] += "|" + ruleItems[i] ruleItems = append(ruleItems[:i], ruleItems[i+1:]...) } else { - return newErrorStr( + return newValidationErrorByStr( internalRulesErrRuleName, - internalRulesErrRuleName+": "+input.Rule, + errors.New(internalRulesErrRuleName+": "+input.Rule), ) } } else { @@ -106,8 +108,8 @@ func (v *Validator) doCheckValue(ctx context.Context, input doCheckValueInput) E err error match = false // whether this rule is matched(has no error) results = ruleRegex.FindStringSubmatch(ruleItems[index]) // split single rule. - ruleKey = strings.TrimSpace(results[1]) // rule name like "max" in rule "max: 6" - rulePattern = strings.TrimSpace(results[2]) // rule value if any like "6" in rule:"max:6" + ruleKey = gstr.Trim(results[1]) // rule key like "max" in rule "max: 6" + rulePattern = gstr.Trim(results[2]) // rule pattern is like "6" in rule:"max:6" customRuleFunc RuleFunc ) @@ -133,15 +135,30 @@ func (v *Validator) doCheckValue(ctx context.Context, input doCheckValueInput) E if customRuleFunc != nil { // It checks custom validation rules with most priority. message := v.getErrorMessageByRule(ctx, ruleKey, customMsgMap) - if err := customRuleFunc(ctx, ruleItems[index], input.Value, message, input.DataRaw); err != nil { + if err = customRuleFunc(ctx, RuleFuncInput{ + Rule: ruleItems[index], + Message: message, + Value: gvar.New(input.Value), + Data: gvar.New(input.DataRaw), + }); err != nil { match = false - errorMsgArray[ruleKey] = err.Error() + // The error should have stack info to indicate the error position. + if !gerror.HasStack(err) { + err = gerror.NewCodeSkip(gcode.CodeValidationFailed, 1, err.Error()) + } + // The error should have error code that is `gcode.CodeValidationFailed`. + if gerror.Code(err) == gcode.CodeNil { + if e, ok := err.(*gerror.Error); ok { + e.SetCode(gcode.CodeValidationFailed) + } + } + ruleErrorMap[ruleKey] = err } else { match = true } } else { // It checks build-in validation rules if there's no custom rule. - match, err = v.doCheckBuildInRules( + match, err = v.doCheckSingleBuildInRules( ctx, doCheckBuildInRulesInput{ Index: index, @@ -154,7 +171,7 @@ func (v *Validator) doCheckValue(ctx context.Context, input doCheckValueInput) E }, ) if !match && err != nil { - errorMsgArray[ruleKey] = err.Error() + ruleErrorMap[ruleKey] = err } } @@ -162,9 +179,22 @@ func (v *Validator) doCheckValue(ctx context.Context, input doCheckValueInput) E if !match { // It does nothing if the error message for this rule // is already set in previous validation. - if _, ok := errorMsgArray[ruleKey]; !ok { - errorMsgArray[ruleKey] = v.getErrorMessageByRule(ctx, ruleKey, customMsgMap) + if _, ok := ruleErrorMap[ruleKey]; !ok { + ruleErrorMap[ruleKey] = errors.New(v.getErrorMessageByRule(ctx, ruleKey, customMsgMap)) } + + // Error variable replacement for error message. + if err = ruleErrorMap[ruleKey]; !gerror.HasStack(err) { + var s string + s = gstr.ReplaceByMap(err.Error(), map[string]string{ + "{value}": gconv.String(input.Value), + "{pattern}": rulePattern, + "{attribute}": input.Name, + }) + s, _ = gregex.ReplaceString(`\s{2,}`, ` `, s) + ruleErrorMap[ruleKey] = errors.New(s) + } + // If it is with error and there's bail rule, // it then does not continue validating for left rules. if hasBailRule { @@ -173,12 +203,12 @@ func (v *Validator) doCheckValue(ctx context.Context, input doCheckValueInput) E } index++ } - if len(errorMsgArray) > 0 { - return newError( + if len(ruleErrorMap) > 0 { + return newValidationError( gcode.CodeValidationFailed, []fieldRule{{Name: input.Name, Rule: input.Rule}}, - map[string]map[string]string{ - input.Name: errorMsgArray, + map[string]map[string]error{ + input.Name: ruleErrorMap, }, ) } @@ -186,16 +216,16 @@ func (v *Validator) doCheckValue(ctx context.Context, input doCheckValueInput) E } type doCheckBuildInRulesInput struct { - Index int - Value interface{} - RuleKey string - RulePattern string - RuleItems []string - DataMap map[string]interface{} - CustomMsgMap map[string]string + Index int // Index of RuleKey in RuleItems. + Value interface{} // Value to be validated. + RuleKey string // RuleKey is like the "max" in rule "max: 6" + RulePattern string // RulePattern is like "6" in rule:"max:6" + RuleItems []string // RuleItems are all the rules that should be validated on single field, like: []string{"required", "min:1"} + DataMap map[string]interface{} // Parameter map. + CustomMsgMap map[string]string // Custom error message map. } -func (v *Validator) doCheckBuildInRules(ctx context.Context, input doCheckBuildInRulesInput) (match bool, err error) { +func (v *Validator) doCheckSingleBuildInRules(ctx context.Context, input doCheckBuildInRulesInput) (match bool, err error) { valueStr := gconv.String(input.Value) switch input.RuleKey { // Required rules. @@ -217,10 +247,7 @@ func (v *Validator) doCheckBuildInRules(ctx context.Context, input doCheckBuildI "max-length", "size": if msg := v.checkLength(ctx, valueStr, input.RuleKey, input.RulePattern, input.CustomMsgMap); msg != "" { - return match, gerror.NewOption(gerror.Option{ - Text: msg, - Code: gcode.CodeValidationFailed, - }) + return match, errors.New(msg) } else { match = true } @@ -231,10 +258,7 @@ func (v *Validator) doCheckBuildInRules(ctx context.Context, input doCheckBuildI "max", "between": if msg := v.checkRange(ctx, valueStr, input.RuleKey, input.RulePattern, input.CustomMsgMap); msg != "" { - return match, gerror.NewOption(gerror.Option{ - Text: msg, - Code: gcode.CodeValidationFailed, - }) + return match, errors.New(msg) } else { match = true } @@ -281,11 +305,7 @@ func (v *Validator) doCheckBuildInRules(ctx context.Context, input doCheckBuildI msg string ) msg = v.getErrorMessageByRule(ctx, input.RuleKey, input.CustomMsgMap) - msg = strings.Replace(msg, ":format", input.RulePattern, -1) - return match, gerror.NewOption(gerror.Option{ - Text: msg, - Code: gcode.CodeValidationFailed, - }) + return match, errors.New(msg) } // Values of two fields should be equal as string. @@ -299,11 +319,7 @@ func (v *Validator) doCheckBuildInRules(ctx context.Context, input doCheckBuildI if !match { var msg string msg = v.getErrorMessageByRule(ctx, input.RuleKey, input.CustomMsgMap) - msg = strings.Replace(msg, ":field", input.RulePattern, -1) - return match, gerror.NewOption(gerror.Option{ - Text: msg, - Code: gcode.CodeValidationFailed, - }) + return match, errors.New(msg) } // Values of two fields should not be equal as string. @@ -318,11 +334,7 @@ func (v *Validator) doCheckBuildInRules(ctx context.Context, input doCheckBuildI if !match { var msg string msg = v.getErrorMessageByRule(ctx, input.RuleKey, input.CustomMsgMap) - msg = strings.Replace(msg, ":field", input.RulePattern, -1) - return match, gerror.NewOption(gerror.Option{ - Text: msg, - Code: gcode.CodeValidationFailed, - }) + return match, errors.New(msg) } // Field value should be in range of. @@ -459,13 +471,13 @@ func (v *Validator) doCheckBuildInRules(ctx context.Context, input doCheckBuildI // Integer. case "integer": - if _, err := strconv.Atoi(valueStr); err == nil { + if _, err = strconv.Atoi(valueStr); err == nil { match = true } // Float. case "float": - if _, err := strconv.ParseFloat(valueStr, 10); err == nil { + if _, err = strconv.ParseFloat(valueStr, 10); err == nil { match = true } @@ -505,10 +517,7 @@ func (v *Validator) doCheckBuildInRules(ctx context.Context, input doCheckBuildI match = gregex.IsMatchString(`^([0-9A-Fa-f]{2}[\-:]){5}[0-9A-Fa-f]{2}$`, valueStr) default: - return match, gerror.NewOption(gerror.Option{ - Text: "Invalid rule name: " + input.RuleKey, - Code: gcode.CodeInvalidParameter, - }) + return match, errors.New("Invalid rule name: " + input.RuleKey) } return match, nil } diff --git a/util/gvalid/gvalid_validator_message.go b/util/gvalid/gvalid_validator_message.go index 5a14106a2..30cab76d8 100644 --- a/util/gvalid/gvalid_validator_message.go +++ b/util/gvalid/gvalid_validator_message.go @@ -10,7 +10,7 @@ import "context" // getErrorMessageByRule retrieves and returns the error message for specified rule. // It firstly retrieves the message from custom message map, and then checks i18n manager, -// it returns the default error message if it's not found in custom message map or i18n manager. +// it returns the default error message if it's not found in neither custom message map nor i18n manager. func (v *Validator) getErrorMessageByRule(ctx context.Context, ruleKey string, customMsgMap map[string]string) string { content := customMsgMap[ruleKey] if content != "" { diff --git a/util/gvalid/gvalid_validator_rule_length.go b/util/gvalid/gvalid_validator_rule_length.go index fd9772f81..7955e5ac2 100644 --- a/util/gvalid/gvalid_validator_rule_length.go +++ b/util/gvalid/gvalid_validator_rule_length.go @@ -8,9 +8,10 @@ package gvalid import ( "context" - "github.com/gogf/gf/v2/util/gconv" "strconv" "strings" + + "github.com/gogf/gf/v2/util/gconv" ) // checkLength checks `value` using length rules. @@ -41,8 +42,8 @@ func (v *Validator) checkLength(ctx context.Context, value, ruleKey, ruleVal str } if valueLen < min || valueLen > max { msg = v.getErrorMessageByRule(ctx, ruleKey, customMsgMap) - msg = strings.Replace(msg, ":min", strconv.Itoa(min), -1) - msg = strings.Replace(msg, ":max", strconv.Itoa(max), -1) + msg = strings.Replace(msg, "{min}", strconv.Itoa(min), -1) + msg = strings.Replace(msg, "{max}", strconv.Itoa(max), -1) return msg } @@ -50,21 +51,21 @@ func (v *Validator) checkLength(ctx context.Context, value, ruleKey, ruleVal str min, err := strconv.Atoi(ruleVal) if valueLen < min || err != nil { msg = v.getErrorMessageByRule(ctx, ruleKey, customMsgMap) - msg = strings.Replace(msg, ":min", strconv.Itoa(min), -1) + msg = strings.Replace(msg, "{min}", strconv.Itoa(min), -1) } case "max-length": max, err := strconv.Atoi(ruleVal) if valueLen > max || err != nil { msg = v.getErrorMessageByRule(ctx, ruleKey, customMsgMap) - msg = strings.Replace(msg, ":max", strconv.Itoa(max), -1) + msg = strings.Replace(msg, "{max}", strconv.Itoa(max), -1) } case "size": size, err := strconv.Atoi(ruleVal) if valueLen != size || err != nil { msg = v.getErrorMessageByRule(ctx, ruleKey, customMsgMap) - msg = strings.Replace(msg, ":size", strconv.Itoa(size), -1) + msg = strings.Replace(msg, "{size}", strconv.Itoa(size), -1) } } return msg diff --git a/util/gvalid/gvalid_validator_rule_range.go b/util/gvalid/gvalid_validator_rule_range.go index 31c747075..752d857ef 100644 --- a/util/gvalid/gvalid_validator_rule_range.go +++ b/util/gvalid/gvalid_validator_rule_range.go @@ -34,8 +34,8 @@ func (v *Validator) checkRange(ctx context.Context, value, ruleKey, ruleVal stri valueF, err := strconv.ParseFloat(value, 10) if valueF < min || valueF > max || err != nil { msg = v.getErrorMessageByRule(ctx, ruleKey, customMsgMap) - msg = strings.Replace(msg, ":min", strconv.FormatFloat(min, 'f', -1, 64), -1) - msg = strings.Replace(msg, ":max", strconv.FormatFloat(max, 'f', -1, 64), -1) + msg = strings.Replace(msg, "{min}", strconv.FormatFloat(min, 'f', -1, 64), -1) + msg = strings.Replace(msg, "{max}", strconv.FormatFloat(max, 'f', -1, 64), -1) } // Min value. @@ -46,7 +46,7 @@ func (v *Validator) checkRange(ctx context.Context, value, ruleKey, ruleVal stri ) if valueN < min || err1 != nil || err2 != nil { msg = v.getErrorMessageByRule(ctx, ruleKey, customMsgMap) - msg = strings.Replace(msg, ":min", strconv.FormatFloat(min, 'f', -1, 64), -1) + msg = strings.Replace(msg, "{min}", strconv.FormatFloat(min, 'f', -1, 64), -1) } // Max value. @@ -57,7 +57,7 @@ func (v *Validator) checkRange(ctx context.Context, value, ruleKey, ruleVal stri ) if valueN > max || err1 != nil || err2 != nil { msg = v.getErrorMessageByRule(ctx, ruleKey, customMsgMap) - msg = strings.Replace(msg, ":max", strconv.FormatFloat(max, 'f', -1, 64), -1) + msg = strings.Replace(msg, "{max}", strconv.FormatFloat(max, 'f', -1, 64), -1) } } diff --git a/util/gvalid/gvalid_validator_rule_required.go b/util/gvalid/gvalid_validator_rule_required.go index 14470f96d..06de0c50d 100644 --- a/util/gvalid/gvalid_validator_rule_required.go +++ b/util/gvalid/gvalid_validator_rule_required.go @@ -7,11 +7,12 @@ package gvalid import ( + "reflect" + "strings" + "github.com/gogf/gf/v2/internal/empty" "github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/gutil" - "reflect" - "strings" ) // checkRequired checks `value` using required rules. diff --git a/util/gvalid/gvalid_validator_rule_resident_id.go b/util/gvalid/gvalid_validator_rule_resident_id.go index a991de473..df4555924 100644 --- a/util/gvalid/gvalid_validator_rule_resident_id.go +++ b/util/gvalid/gvalid_validator_rule_resident_id.go @@ -7,9 +7,10 @@ package gvalid import ( - "github.com/gogf/gf/v2/text/gregex" "strconv" "strings" + + "github.com/gogf/gf/v2/text/gregex" ) // checkResidentId checks whether given id a china resident id number. diff --git a/util/gvalid/gvalid_z_example_test.go b/util/gvalid/gvalid_z_example_test.go index f163b1b56..3f04cab1b 100644 --- a/util/gvalid/gvalid_z_example_test.go +++ b/util/gvalid/gvalid_z_example_test.go @@ -10,13 +10,15 @@ import ( "context" "errors" "fmt" + "math" + "reflect" + "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gctx" + "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/gvalid" - "math" - "reflect" ) func ExampleCheckMap() { @@ -26,14 +28,14 @@ func ExampleCheckMap() { "password2": "1234567", } rules := []string{ - "passport@required|length:6,16#账号不能为空|账号长度应当在:min到:max之间", - "password@required|length:6,16|same:password2#密码不能为空|密码长度应当在:min到:max之间|两次密码输入不相等", + "passport@required|length:6,16#账号不能为空|账号长度应当在{min}到{max}之间", + "password@required|length:6,16|same{password}2#密码不能为空|密码长度应当在{min}到{max}之间|两次密码输入不相等", "password2@required|length:6,16#", } if e := gvalid.CheckMap(gctx.New(), params, rules); e != nil { fmt.Println(e.Map()) fmt.Println(e.FirstItem()) - fmt.Println(e.FirstString()) + fmt.Println(e.FirstError()) } // May Output: // map[required:账号不能为空 length:账号长度应当在6到16之间] @@ -48,14 +50,14 @@ func ExampleCheckMap2() { "password2": "1234567", } rules := []string{ - "passport@length:6,16#账号不能为空|账号长度应当在:min到:max之间", - "password@required|length:6,16|same:password2#密码不能为空|密码长度应当在:min到:max之间|两次密码输入不相等", + "passport@length:6,16#账号不能为空|账号长度应当在{min}到{max}之间", + "password@required|length:6,16|same:password2#密码不能为空|密码长度应当在{min}到{max}之间|两次密码输入不相等", "password2@required|length:6,16#", } if e := gvalid.CheckMap(gctx.New(), params, rules); e != nil { fmt.Println(e.Map()) fmt.Println(e.FirstItem()) - fmt.Println(e.FirstString()) + fmt.Println(e.FirstError()) } // Output: // map[same:两次密码输入不相等] @@ -68,7 +70,7 @@ func ExampleCheckStruct() { type Params struct { Page int `v:"required|min:1 # page is required"` Size int `v:"required|between:1,100 # size is required"` - ProjectId string `v:"between:1,10000 # project id must between :min, :max"` + ProjectId string `v:"between:1,10000 # project id must between {min}, {max}"` } obj := &Params{ Page: 1, @@ -85,7 +87,7 @@ func ExampleCheckStruct2() { type Params struct { Page int `v:"required|min:1 # page is required"` Size int `v:"required|between:1,100 # size is required"` - ProjectId *gvar.Var `v:"between:1,10000 # project id must between :min, :max"` + ProjectId *gvar.Var `v:"between:1,10000 # project id must between {min}, {max}"` } obj := &Params{ Page: 1, @@ -102,7 +104,7 @@ func ExampleCheckStruct3() { type Params struct { Page int `v:"required|min:1 # page is required"` Size int `v:"required|between:1,100 # size is required"` - ProjectId int `v:"between:1,10000 # project id must between :min, :max"` + ProjectId int `v:"between:1,10000 # project id must between {min}, {max}"` } obj := &Params{ Page: 1, @@ -127,17 +129,17 @@ func ExampleRegisterRule() { } rule := "unique-name" - gvalid.RegisterRule(rule, func(ctx context.Context, rule string, value interface{}, message string, data interface{}) error { + gvalid.RegisterRule(rule, func(ctx context.Context, in gvalid.RuleFuncInput) error { var ( - id = data.(*User).Id - name = gconv.String(value) + id = in.Data.Val().(*User).Id + name = gconv.String(in.Value) ) n, err := g.Model("user").Where("id != ? and name = ?", id, name).Count() if err != nil { return err } if n > 0 { - return errors.New(message) + return errors.New(in.Message) } return nil }) @@ -149,8 +151,8 @@ func ExampleRegisterRule() { func ExampleRegisterRule_OverwriteRequired() { rule := "required" - gvalid.RegisterRule(rule, func(ctx context.Context, rule string, value interface{}, message string, data interface{}) error { - reflectValue := reflect.ValueOf(value) + gvalid.RegisterRule(rule, func(ctx context.Context, in gvalid.RuleFuncInput) error { + reflectValue := reflect.ValueOf(in.Value.Val()) if reflectValue.Kind() == reflect.Ptr { reflectValue = reflectValue.Elem() } @@ -171,7 +173,7 @@ func ExampleRegisterRule_OverwriteRequired() { isEmpty = reflectValue.Len() == 0 } if isEmpty { - return errors.New(message) + return errors.New(in.Message) } return nil }) @@ -229,7 +231,7 @@ func ExampleValidator_CheckMap() { "password2": "required|length:6,16", } messages := map[string]interface{}{ - "passport": "账号不能为空|账号长度应当在:min到:max之间", + "passport": "账号不能为空|账号长度应当在{min}到{max}之间", "password": map[string]string{ "required": "密码不能为空", "same": "两次密码输入不相等", @@ -244,15 +246,15 @@ func ExampleValidator_CheckMap() { } // May Output: - //{ + // { // "passport": { // "length": "账号长度应当在6到16之间", // "required": "账号不能为空" - //}, + // }, // "password": { // "same": "两次密码输入不相等" - //} - //} + // } + // } } func ExampleValidator_CheckStruct() { @@ -460,11 +462,13 @@ func ExampleValidator_Date() { } ) if err := g.Validator().CheckStruct(ctx, req); err != nil { - fmt.Print(err) + fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: - // The Date3 value is not a valid date; The Date4 value is not a valid date; The Date5 value is not a valid date + // The Date3 value `2021-Oct-31` is not a valid date + // The Date4 value `2021 Octa 31` is not a valid date + // The Date5 value `2021/Oct/31` is not a valid date } func ExampleValidator_Datetime() { @@ -485,11 +489,13 @@ func ExampleValidator_Datetime() { } ) if err := g.Validator().CheckStruct(ctx, req); err != nil { - fmt.Print(err) + fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: - // The Date2 value is not a valid datetime; The Date3 value is not a valid datetime; The Date4 value is not a valid datetime + // The Date2 value `2021-11-01 23:00` is not a valid datetime + // The Date3 value `2021/11/01 23:00:00` is not a valid datetime + // The Date4 value `2021/Dec/01 23:00:00` is not a valid datetime } func ExampleValidator_DateFormat() { @@ -510,11 +516,12 @@ func ExampleValidator_DateFormat() { } ) if err := g.Validator().CheckStruct(ctx, req); err != nil { - fmt.Print(err) + fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: - // The Date2 value does not match the format Y-m-d; The Date4 value does not match the format Y-m-d H:i:s + // The Date2 value `2021-11-01 23:00` does not match the format: Y-m-d + // The Date4 value `2021-11-01 23:00` does not match the format: Y-m-d H:i:s } func ExampleValidator_Email() { @@ -535,11 +542,12 @@ func ExampleValidator_Email() { } ) if err := g.Validator().CheckStruct(ctx, req); err != nil { - fmt.Print(err) + fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: - // The MailAddr2 value must be a valid email address; The MailAddr4 value must be a valid email address + // The MailAddr2 value `gf@goframe` is not a valid email address + // The MailAddr4 value `gf#goframe.org` is not a valid email address } func ExampleValidator_Phone() { @@ -560,11 +568,13 @@ func ExampleValidator_Phone() { } ) if err := g.Validator().CheckStruct(ctx, req); err != nil { - fmt.Print(err) + fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: - // The PhoneNumber2 value must be a valid phone number; The PhoneNumber3 value must be a valid phone number; The PhoneNumber4 value must be a valid phone number + // The PhoneNumber2 value `11578912345` is not a valid phone number + // The PhoneNumber3 value `17178912345` is not a valid phone number + // The PhoneNumber4 value `1357891234` is not a valid phone number } func ExampleValidator_PhoneLoose() { @@ -585,11 +595,12 @@ func ExampleValidator_PhoneLoose() { } ) if err := g.Validator().CheckStruct(ctx, req); err != nil { - fmt.Print(err) + fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: - // The PhoneNumber2 value must be a valid phone number; The PhoneNumber4 value must be a valid phone number + // The PhoneNumber2 value `11578912345` is invalid + // The PhoneNumber4 value `1357891234` is invalid } func ExampleValidator_Telephone() { @@ -610,11 +621,12 @@ func ExampleValidator_Telephone() { } ) if err := g.Validator().CheckStruct(ctx, req); err != nil { - fmt.Print(err) + fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: - // The Telephone3 value must be a valid telephone number; The Telephone4 value must be a valid telephone number + // The Telephone3 value `20-77542145` is not a valid telephone number + // The Telephone4 value `775421451` is not a valid telephone number } func ExampleValidator_Passport() { @@ -635,11 +647,13 @@ func ExampleValidator_Passport() { } ) if err := g.Validator().CheckStruct(ctx, req); err != nil { - fmt.Print(err) + fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: - // The Passport2 value is not a valid passport format; The Passport3 value is not a valid passport format; The Passport4 value is not a valid passport format + // The Passport2 value `1356666` is not a valid passport format + // The Passport3 value `goframe#` is not a valid passport format + // The Passport4 value `gf` is not a valid passport format } func ExampleValidator_Password() { @@ -660,7 +674,7 @@ func ExampleValidator_Password() { } // Output: - // The Password2 value is not a valid passport format + // The Password2 value `gofra` is not a valid password format } func ExampleValidator_Password2() { @@ -681,11 +695,13 @@ func ExampleValidator_Password2() { } ) if err := g.Validator().CheckStruct(ctx, req); err != nil { - fmt.Print(err) + fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: - // The Password2 value is not a valid passport format; The Password3 value is not a valid passport format; The Password4 value is not a valid passport format + // The Password2 value `gofra` is not a valid password format + // The Password3 value `Goframe` is not a valid password format + // The Password4 value `goframe123` is not a valid password format } func ExampleValidator_Password3() { @@ -704,11 +720,12 @@ func ExampleValidator_Password3() { } ) if err := g.Validator().CheckStruct(ctx, req); err != nil { - fmt.Print(err) + fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: - // The Password2 value is not a valid passport format; The Password3 value is not a valid passport format + // The Password2 value `gofra` is not a valid password format + // The Password3 value `Goframe123` is not a valid password format } func ExampleValidator_Postcode() { @@ -727,11 +744,12 @@ func ExampleValidator_Postcode() { } ) if err := g.Validator().CheckStruct(ctx, req); err != nil { - fmt.Print(err) + fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: - // The Postcode2 value is not a valid passport format; The Postcode3 value is not a valid passport format + // The Postcode2 value `10000` is not a valid postcode format + // The Postcode3 value `1000000` is not a valid postcode format } func ExampleValidator_ResidentId() { @@ -750,7 +768,7 @@ func ExampleValidator_ResidentId() { } // Output: - // The ResidentID1 value is not a valid resident id number + // The ResidentID1 value `320107199506285482` is not a valid resident id number } func ExampleValidator_BankCard() { @@ -769,7 +787,7 @@ func ExampleValidator_BankCard() { } // Output: - // The BankCard1 value must be a valid bank card number + // The BankCard1 value `6225760079930218` is not a valid bank card number } func ExampleValidator_QQ() { @@ -788,11 +806,12 @@ func ExampleValidator_QQ() { } ) if err := g.Validator().CheckStruct(ctx, req); err != nil { - fmt.Print(err) + fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: - // The QQ2 value must be a valid QQ number; The QQ3 value must be a valid QQ number + // The QQ2 value `9999` is not a valid QQ number + // The QQ3 value `514258412a` is not a valid QQ number } func ExampleValidator_IP() { @@ -813,11 +832,12 @@ func ExampleValidator_IP() { } ) if err := g.Validator().CheckStruct(ctx, req); err != nil { - fmt.Print(err) + fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: - // The IP3 value must be a valid IP address; The IP4 value must be a valid IP address + // The IP3 value `520.255.255.255` is not a valid IP address + // The IP4 value `ze80::812b:1158:1f43:f0d1` is not a valid IP address } func ExampleValidator_IPV4() { @@ -838,7 +858,7 @@ func ExampleValidator_IPV4() { } // Output: - // The IP2 value must be a valid IPv4 address + // The IP2 value `520.255.255.255` is not a valid IPv4 address } func ExampleValidator_IPV6() { @@ -859,7 +879,7 @@ func ExampleValidator_IPV6() { } // Output: - // The IP2 value must be a valid IPv6 address + // The IP2 value `ze80::812b:1158:1f43:f0d1` is not a valid IPv6 address } func ExampleValidator_Mac() { @@ -880,7 +900,7 @@ func ExampleValidator_Mac() { } // Output: - // The Mac2 value must be a valid MAC address + // The Mac2 value `Z0-CC-6A-D6-B1-1A` is not a valid MAC address } func ExampleValidator_Url() { @@ -903,7 +923,7 @@ func ExampleValidator_Url() { } // Output: - // The URL3 value must be a valid URL address + // The URL3 value `ws://goframe.org` is not a valid URL address } func ExampleValidator_Domain() { @@ -924,11 +944,12 @@ func ExampleValidator_Domain() { } ) if err := g.Validator().CheckStruct(ctx, req); err != nil { - fmt.Print(err) + fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: - // The Domain3 value must be a valid domain format; The Domain4 value must be a valid domain format + // The Domain3 value `goframe#org` is not a valid domain format + // The Domain4 value `1a.2b` is not a valid domain format } func ExampleValidator_Size() { @@ -949,7 +970,7 @@ func ExampleValidator_Size() { } // Output: - // The Size2 value length must be 5 + // The Size2 value `goframe` length must be 5 } func ExampleValidator_Length() { @@ -970,7 +991,7 @@ func ExampleValidator_Length() { } // Output: - // The Length2 value length must be between 10 and 15 + // The Length2 value `goframe` length must be between 10 and 15 } func ExampleValidator_MinLength() { @@ -991,7 +1012,7 @@ func ExampleValidator_MinLength() { } // Output: - // The MinLength2 value length must be equal or greater than 8 + // The MinLength2 value `goframe` length must be equal or greater than 8 } func ExampleValidator_MaxLength() { @@ -1012,7 +1033,7 @@ func ExampleValidator_MaxLength() { } // Output: - // The MaxLength2 value length must be equal or lesser than 5 + // The MaxLength2 value `goframe` length must be equal or lesser than 5 } func ExampleValidator_Between() { @@ -1033,11 +1054,12 @@ func ExampleValidator_Between() { } ) if err := g.Validator().CheckStruct(ctx, req); err != nil { - fmt.Print(err) + fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: - // The Age2 value must be between 1 and 100; The Score2 value must be between 0 and 10 + // The Age2 value `101` must be between 1 and 100 + // The Score2 value `-0.5` must be between 0 and 10 } func ExampleValidator_Min() { @@ -1058,11 +1080,12 @@ func ExampleValidator_Min() { } ) if err := g.Validator().CheckStruct(ctx, req); err != nil { - fmt.Print(err) + fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: - // The Age1 value must be equal or greater than 100; The Score1 value must be equal or greater than 10 + // The Age1 value `50` must be equal or greater than 100 + // The Score1 value `9.8` must be equal or greater than 10 } func ExampleValidator_Max() { @@ -1083,11 +1106,12 @@ func ExampleValidator_Max() { } ) if err := g.Validator().CheckStruct(ctx, req); err != nil { - fmt.Print(err) + fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: - // The Age2 value must be equal or lesser than 100; The Score2 value must be equal or lesser than 10 + // The Age2 value `101` must be equal or lesser than 100 + // The Score2 value `10.1` must be equal or lesser than 10 } func ExampleValidator_Json() { @@ -1108,7 +1132,7 @@ func ExampleValidator_Json() { } // Output: - // The JSON2 value must be a valid JSON string + // The JSON2 value `{"name":"goframe","author":"郭强","test"}` is not a valid JSON string } func ExampleValidator_Integer() { @@ -1127,11 +1151,12 @@ func ExampleValidator_Integer() { } ) if err := g.Validator().CheckStruct(ctx, req); err != nil { - fmt.Print(err) + fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: - // The Float value must be an integer; The Str value must be an integer + // The Float value `10.0` is not an integer + // The Str value `goframe` is not an integer } func ExampleValidator_Float() { @@ -1154,7 +1179,7 @@ func ExampleValidator_Float() { } // Output: - // The Str value must be a float + // The Str value `goframe` is invalid } func ExampleValidator_Boolean() { @@ -1179,11 +1204,12 @@ func ExampleValidator_Boolean() { } ) if err := g.Validator().CheckStruct(ctx, req); err != nil { - fmt.Print(err) + fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: - // The Float value field must be true or false; The Str3 value field must be true or false + // The Float value `10` field must be true or false + // The Str3 value `goframe` field must be true or false } func ExampleValidator_Same() { @@ -1205,7 +1231,7 @@ func ExampleValidator_Same() { } // Output: - // The Password value must be the same as field Password2 + // The Password value `goframe.org` must be the same as field Password2 } func ExampleValidator_Different() { @@ -1227,7 +1253,7 @@ func ExampleValidator_Different() { } // Output: - // The OtherMailAddr value must be different from field MailAddr + // The OtherMailAddr value `gf@goframe.org` must be different from field MailAddr } func ExampleValidator_In() { @@ -1249,7 +1275,7 @@ func ExampleValidator_In() { } // Output: - // The Gender value is not in acceptable range + // The Gender value `3` is not in acceptable range: 0,1,2 } func ExampleValidator_NotIn() { @@ -1271,7 +1297,7 @@ func ExampleValidator_NotIn() { } // Output: - // The InvalidIndex value is not in acceptable range + // The InvalidIndex value `1` must not be in range: -1,0,1 } func ExampleValidator_Regex() { @@ -1289,9 +1315,10 @@ func ExampleValidator_Regex() { } ) if err := g.Validator().CheckStruct(ctx, req); err != nil { - fmt.Println(err) + fmt.Print(gstr.Join(err.Strings(), "\n")) } // Output: - // The Regex1 value is invalid; The Regex2 value is invalid + // The Regex1 value `1234` must be in regex of: [1-9][0-9]{4,14} + // The Regex2 value `01234` must be in regex of: [1-9][0-9]{4,14} } diff --git a/util/gvalid/gvalid_z_unit_checkmap_test.go b/util/gvalid/gvalid_z_unit_feature_checkmap_test.go similarity index 82% rename from util/gvalid/gvalid_z_unit_checkmap_test.go rename to util/gvalid/gvalid_z_unit_feature_checkmap_test.go index a46ae021c..4f0849a76 100755 --- a/util/gvalid/gvalid_z_unit_checkmap_test.go +++ b/util/gvalid/gvalid_z_unit_feature_checkmap_test.go @@ -8,10 +8,10 @@ package gvalid_test import ( "context" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/frame/g" "testing" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gvalid" ) @@ -30,8 +30,8 @@ func Test_CheckMap1(t *testing.T) { t.Error("CheckMap校验失败") } else { t.Assert(len(m.Maps()), 2) - t.Assert(m.Maps()["id"]["between"], "The id value must be between 1 and 100") - t.Assert(m.Maps()["name"]["length"], "The name value length must be between 6 and 16") + t.Assert(m.Maps()["id"]["between"], "The id value `0` must be between 1 and 100") + t.Assert(m.Maps()["name"]["length"], "The name value `john` length must be between 6 and 16") } }) } @@ -53,10 +53,10 @@ func Test_CheckMap2(t *testing.T) { "name": "required|length:6,16", } msgs := gvalid.CustomMsg{ - "id": "ID不能为空|ID范围应当为:min到:max", + "id": "ID不能为空|ID范围应当为{min}到{max}", "name": map[string]string{ "required": "名称不能为空", - "length": "名称长度为:min到:max个字符", + "length": "名称长度为{min}到{max}个字符", }, } if m := gvalid.CheckMap(context.TODO(), kvmap, rules, msgs); m == nil { @@ -72,10 +72,10 @@ func Test_CheckMap2(t *testing.T) { "name": "required|length:4,16", } msgs = map[string]interface{}{ - "id": "ID不能为空|ID范围应当为:min到:max", + "id": "ID不能为空|ID范围应当为{min}到{max}", "name": map[string]string{ "required": "名称不能为空", - "length": "名称长度为:min到:max个字符", + "length": "名称长度为{min}到{max}个字符", }, } if m := gvalid.CheckMap(context.TODO(), kvmap, rules, msgs); m != nil { @@ -91,10 +91,10 @@ func Test_CheckMap2(t *testing.T) { "name": "", } msgs = map[string]interface{}{ - "id": "ID不能为空|ID范围应当为:min到:max", + "id": "ID不能为空|ID范围应当为{min}到{max}", "name": map[string]string{ "required": "名称不能为空", - "length": "名称长度为:min到:max个字符", + "length": "名称长度为{min}到{max}个字符", }, } if m := gvalid.CheckMap(context.TODO(), kvmap, rules, msgs); m != nil { @@ -110,10 +110,10 @@ func Test_CheckMap2(t *testing.T) { "@required|length:4,16", } msgs = map[string]interface{}{ - "id": "ID不能为空|ID范围应当为:min到:max", + "id": "ID不能为空|ID范围应当为{min}到{max}", "name": map[string]string{ "required": "名称不能为空", - "length": "名称长度为:min到:max个字符", + "length": "名称长度为{min}到{max}个字符", }, } if m := gvalid.CheckMap(context.TODO(), kvmap, rules2, msgs); m != nil { @@ -129,10 +129,10 @@ func Test_CheckMap2(t *testing.T) { "name@required|length:4,16#名称不能为空|", } msgs = map[string]interface{}{ - "id": "ID不能为空|ID范围应当为:min到:max", + "id": "ID不能为空|ID范围应当为{min}到{max}", "name": map[string]string{ "required": "名称不能为空", - "length": "名称长度为:min到:max个字符", + "length": "名称长度为{min}到{max}个字符", }, } if m := gvalid.CheckMap(context.TODO(), kvmap, rules2, msgs); m != nil { @@ -148,10 +148,10 @@ func Test_CheckMap2(t *testing.T) { "name@required|length:4,16#名称不能为空", } msgs = map[string]interface{}{ - "id": "ID不能为空|ID范围应当为:min到:max", + "id": "ID不能为空|ID范围应当为{min}到{max}", "name": map[string]string{ "required": "名称不能为空", - "length": "名称长度为:min到:max个字符", + "length": "名称长度为{min}到{max}个字符", }, } if m := gvalid.CheckMap(context.TODO(), kvmap, rules2, msgs); m != nil { @@ -159,7 +159,6 @@ func Test_CheckMap2(t *testing.T) { } } -// 如果值为nil,并且不需要require*验证时,其他验证失效 func Test_CheckMapWithNilAndNotRequiredField(t *testing.T) { data := map[string]interface{}{ "id": "1", @@ -181,8 +180,8 @@ func Test_Sequence(t *testing.T) { "password2": "1234567", } rules := []string{ - "passport@required|length:6,16#账号不能为空|账号长度应当在:min到:max之间", - "password@required|length:6,16|same:password2#密码不能为空|密码长度应当在:min到:max之间|两次密码输入不相等", + "passport@required|length:6,16#账号不能为空|账号长度应当在{min}到{max}之间", + "password@required|length:6,16|same:password2#密码不能为空|密码长度应当在{min}到{max}之间|两次密码输入不相等", "password2@required|length:6,16#", } err := gvalid.CheckMap(context.TODO(), params, rules) @@ -221,8 +220,8 @@ func Test_Map_Bail(t *testing.T) { "password2": "1234567", } rules := []string{ - "passport@required|length:6,16#账号不能为空|账号长度应当在:min到:max之间", - "password@required|length:6,16|same:password2#密码不能为空|密码长度应当在:min到:max之间|两次密码输入不相等", + "passport@required|length:6,16#账号不能为空|账号长度应当在{min}到{max}之间", + "password@required|length:6,16|same:password2#密码不能为空|密码长度应当在{min}到{max}之间|两次密码输入不相等", "password2@required|length:6,16#", } err := g.Validator().Bail().Rules(rules).CheckMap(ctx, params) @@ -237,8 +236,8 @@ func Test_Map_Bail(t *testing.T) { "password2": "1234567", } rules := []string{ - "passport@bail|required|length:6,16#|账号不能为空|账号长度应当在:min到:max之间", - "password@required|length:6,16|same:password2#密码不能为空|密码长度应当在:min到:max之间|两次密码输入不相等", + "passport@bail|required|length:6,16#|账号不能为空|账号长度应当在{min}到{max}之间", + "password@required|length:6,16|same:password2#密码不能为空|密码长度应当在{min}到{max}之间|两次密码输入不相等", "password2@required|length:6,16#", } err := g.Validator().Bail().Rules(rules).CheckMap(ctx, params) diff --git a/util/gvalid/gvalid_z_unit_checkstruct_test.go b/util/gvalid/gvalid_z_unit_feature_checkstruct_test.go similarity index 97% rename from util/gvalid/gvalid_z_unit_checkstruct_test.go rename to util/gvalid/gvalid_z_unit_feature_checkstruct_test.go index 3c53ef886..9b16d391f 100755 --- a/util/gvalid/gvalid_z_unit_checkstruct_test.go +++ b/util/gvalid/gvalid_z_unit_feature_checkstruct_test.go @@ -8,12 +8,11 @@ package gvalid_test import ( "context" - "github.com/gogf/gf/v2/container/gvar" - "github.com/gogf/gf/v2/os/gtime" "testing" + "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/frame/g" - + "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gvalid" ) @@ -31,7 +30,7 @@ func Test_CheckStruct(t *testing.T) { msgs := map[string]interface{}{ "Name": map[string]string{ "required": "名称不能为空", - "length": "名称长度为:min到:max个字符", + "length": "名称长度为{min}到{max}个字符", }, "Age": "年龄为18到30周岁", } @@ -52,7 +51,7 @@ func Test_CheckStruct(t *testing.T) { msgs := map[string]interface{}{ "Name": map[string]string{ "required": "名称不能为空", - "length": "名称长度为:min到:max个字符", + "length": "名称长度为{min}到{max}个字符", }, "Age": "年龄为18到30周岁", } @@ -77,7 +76,7 @@ func Test_CheckStruct(t *testing.T) { msgs := map[string]interface{}{ "Name": map[string]string{ "required": "名称不能为空", - "length": "名称长度为:min到:max个字符", + "length": "名称长度为{min}到{max}个字符", }, "Age": "年龄为18到30周岁", } @@ -102,7 +101,7 @@ func Test_CheckStruct(t *testing.T) { msgs := map[string]interface{}{ "Name": map[string]string{ "required": "名称不能为空", - "length": "名称长度为:min到:max个字符", + "length": "名称长度为{min}到{max}个字符", }, "Age": "年龄为18到30周岁", } @@ -336,7 +335,7 @@ func Test_CheckStruct_Optional(t *testing.T) { type Params struct { Page int `v:"required|min:1 # page is required"` Size int `v:"required|between:1,100 # size is required"` - ProjectId string `v:"between:1,10000 # project id must between :min, :max"` + ProjectId string `v:"between:1,10000 # project id must between {min}, {max}"` } obj := &Params{ Page: 1, @@ -349,7 +348,7 @@ func Test_CheckStruct_Optional(t *testing.T) { type Params struct { Page int `v:"required|min:1 # page is required"` Size int `v:"required|between:1,100 # size is required"` - ProjectId *gvar.Var `v:"between:1,10000 # project id must between :min, :max"` + ProjectId *gvar.Var `v:"between:1,10000 # project id must between {min}, {max}"` } obj := &Params{ Page: 1, @@ -362,7 +361,7 @@ func Test_CheckStruct_Optional(t *testing.T) { type Params struct { Page int `v:"required|min:1 # page is required"` Size int `v:"required|between:1,100 # size is required"` - ProjectId int `v:"between:1,10000 # project id must between :min, :max"` + ProjectId int `v:"between:1,10000 # project id must between {min}, {max}"` } obj := &Params{ Page: 1, diff --git a/util/gvalid/gvalid_z_unit_customerror_test.go b/util/gvalid/gvalid_z_unit_feature_custom_error_test.go similarity index 81% rename from util/gvalid/gvalid_z_unit_customerror_test.go rename to util/gvalid/gvalid_z_unit_feature_custom_error_test.go index 51941c171..9d1e0b35d 100755 --- a/util/gvalid/gvalid_z_unit_customerror_test.go +++ b/util/gvalid/gvalid_z_unit_feature_custom_error_test.go @@ -22,7 +22,7 @@ func Test_Map(t *testing.T) { val = "0.0.0" err = gvalid.CheckValue(context.TODO(), val, rule, nil) msg = map[string]string{ - "ipv4": "The value must be a valid IPv4 address", + "ipv4": "The value `0.0.0` is not a valid IPv4 address", } ) t.Assert(err.Map(), msg) @@ -35,9 +35,8 @@ func Test_FirstString(t *testing.T) { rule = "ipv4" val = "0.0.0" err = gvalid.CheckValue(context.TODO(), val, rule, nil) - n = err.FirstString() ) - t.Assert(n, "The value must be a valid IPv4 address") + t.Assert(err.FirstError(), "The value `0.0.0` is not a valid IPv4 address") }) } @@ -52,12 +51,12 @@ func Test_CustomError1(t *testing.T) { t.Error("规则校验失败") } else { if v, ok := e.Map()["integer"]; ok { - if strings.Compare(v, msgs["integer"]) != 0 { + if strings.Compare(v.Error(), msgs["integer"]) != 0 { t.Error("错误信息不匹配") } } if v, ok := e.Map()["length"]; ok { - if strings.Compare(v, msgs["length"]) != 0 { + if strings.Compare(v.Error(), msgs["length"]) != 0 { t.Error("错误信息不匹配") } } @@ -72,12 +71,12 @@ func Test_CustomError2(t *testing.T) { t.Error("规则校验失败") } else { if v, ok := e.Map()["integer"]; ok { - if strings.Compare(v, "请输入一个整数") != 0 { + if strings.Compare(v.Error(), "请输入一个整数") != 0 { t.Error("错误信息不匹配") } } if v, ok := e.Map()["length"]; ok { - if strings.Compare(v, "参数长度不对啊老铁") != 0 { + if strings.Compare(v.Error(), "参数长度不对啊老铁") != 0 { t.Error("错误信息不匹配") } } diff --git a/util/gvalid/gvalid_z_unit_custom_rule_test.go b/util/gvalid/gvalid_z_unit_feature_custom_rule_test.go similarity index 83% rename from util/gvalid/gvalid_z_unit_custom_rule_test.go rename to util/gvalid/gvalid_z_unit_feature_custom_rule_test.go index 75285813c..21ad7dcce 100644 --- a/util/gvalid/gvalid_z_unit_custom_rule_test.go +++ b/util/gvalid/gvalid_z_unit_feature_custom_rule_test.go @@ -12,29 +12,27 @@ import ( "testing" "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" - "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gvalid" ) func Test_CustomRule1(t *testing.T) { rule := "custom" - err := gvalid.RegisterRule( + gvalid.RegisterRule( rule, - func(ctx context.Context, rule string, value interface{}, message string, data interface{}) error { - pass := gconv.String(value) + func(ctx context.Context, in gvalid.RuleFuncInput) error { + pass := in.Value.String() if len(pass) != 6 { - return errors.New(message) + return errors.New(in.Message) } - m := gconv.Map(data) + m := in.Data.Map() if m["data"] != pass { - return errors.New(message) + return errors.New(in.Message) } return nil }, ) - gtest.Assert(err, nil) + gtest.C(t, func(t *gtest.T) { err := gvalid.CheckValue(context.TODO(), "123456", rule, "custom message") t.Assert(err.String(), "custom message") @@ -71,14 +69,13 @@ func Test_CustomRule1(t *testing.T) { func Test_CustomRule2(t *testing.T) { rule := "required-map" - err := gvalid.RegisterRule(rule, func(ctx context.Context, rule string, value interface{}, message string, data interface{}) error { - m := gconv.Map(value) + gvalid.RegisterRule(rule, func(ctx context.Context, in gvalid.RuleFuncInput) error { + m := in.Value.Map() if len(m) == 0 { - return errors.New(message) + return errors.New(in.Message) } return nil }) - gtest.Assert(err, nil) // Check. gtest.C(t, func(t *gtest.T) { errStr := "data map should not be empty" @@ -115,14 +112,13 @@ func Test_CustomRule2(t *testing.T) { func Test_CustomRule_AllowEmpty(t *testing.T) { rule := "allow-empty-str" - err := gvalid.RegisterRule(rule, func(ctx context.Context, rule string, value interface{}, message string, data interface{}) error { - s := gconv.String(value) + gvalid.RegisterRule(rule, func(ctx context.Context, in gvalid.RuleFuncInput) error { + s := in.Value.String() if len(s) == 0 || s == "gf" { return nil } - return errors.New(message) + return errors.New(in.Message) }) - gtest.Assert(err, nil) // Check. gtest.C(t, func(t *gtest.T) { errStr := "error" @@ -160,13 +156,13 @@ func Test_CustomRule_AllowEmpty(t *testing.T) { func TestValidator_RuleFunc(t *testing.T) { ruleName := "custom_1" - ruleFunc := func(ctx context.Context, rule string, value interface{}, message string, data interface{}) error { - pass := gconv.String(value) + ruleFunc := func(ctx context.Context, in gvalid.RuleFuncInput) error { + pass := in.Value.String() if len(pass) != 6 { - return errors.New(message) + return errors.New(in.Message) } - if m := gconv.Map(data); m["data"] != pass { - return errors.New(message) + if m := in.Data.Map(); m["data"] != pass { + return errors.New(in.Message) } return nil } @@ -214,13 +210,13 @@ func TestValidator_RuleFunc(t *testing.T) { func TestValidator_RuleFuncMap(t *testing.T) { ruleName := "custom_1" - ruleFunc := func(ctx context.Context, rule string, value interface{}, message string, data interface{}) error { - pass := gconv.String(value) + ruleFunc := func(ctx context.Context, in gvalid.RuleFuncInput) error { + pass := in.Value.String() if len(pass) != 6 { - return errors.New(message) + return errors.New(in.Message) } - if m := gconv.Map(data); m["data"] != pass { - return errors.New(message) + if m := in.Data.Map(); m["data"] != pass { + return errors.New(in.Message) } return nil } diff --git a/util/gvalid/gvalid_z_unit_i18n_test.go b/util/gvalid/gvalid_z_unit_feature_i18n_test.go similarity index 98% rename from util/gvalid/gvalid_z_unit_i18n_test.go rename to util/gvalid/gvalid_z_unit_feature_i18n_test.go index f41790acb..6e61ff636 100644 --- a/util/gvalid/gvalid_z_unit_i18n_test.go +++ b/util/gvalid/gvalid_z_unit_feature_i18n_test.go @@ -8,12 +8,12 @@ package gvalid_test import ( "context" - "github.com/gogf/gf/v2/debug/gdebug" - "github.com/gogf/gf/v2/i18n/gi18n" - "github.com/gogf/gf/v2/util/gvalid" "testing" + "github.com/gogf/gf/v2/debug/gdebug" + "github.com/gogf/gf/v2/i18n/gi18n" "github.com/gogf/gf/v2/test/gtest" + "github.com/gogf/gf/v2/util/gvalid" ) func TestValidator_I18n(t *testing.T) { @@ -38,7 +38,7 @@ func TestValidator_I18n(t *testing.T) { type Params struct { Page int `v:"required|min:1 # page is required"` Size int `v:"required|between:1,100 # size is required"` - ProjectId int `v:"between:1,10000 # project id must between :min, :max"` + ProjectId int `v:"between:1,10000 # project id must between {min}, {max}"` } obj := &Params{ Page: 1, diff --git a/util/gvalid/gvalid_z_unit_basic_all_test.go b/util/gvalid/gvalid_z_unit_feature_rule_test.go similarity index 99% rename from util/gvalid/gvalid_z_unit_basic_all_test.go rename to util/gvalid/gvalid_z_unit_feature_rule_test.go index 83741d477..af280181f 100755 --- a/util/gvalid/gvalid_z_unit_basic_all_test.go +++ b/util/gvalid/gvalid_z_unit_feature_rule_test.go @@ -8,14 +8,14 @@ package gvalid_test import ( "context" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/os/gctx" - "github.com/gogf/gf/v2/os/gtime" "testing" "time" + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/os/gctx" + "github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/util/gvalid" ) @@ -361,6 +361,7 @@ func Test_PhoneLoose(t *testing.T) { t.AssertNE(err6, nil) }) } + func Test_Telephone(t *testing.T) { gtest.C(t, func(t *gtest.T) { rule := "telephone" @@ -670,10 +671,10 @@ func Test_Domain(t *testing.T) { for k, v := range m { err = gvalid.CheckValue(context.TODO(), k, "domain", nil) if v { - //fmt.Println(k) + // fmt.Println(k) t.Assert(err, nil) } else { - //fmt.Println(k) + // fmt.Println(k) t.AssertNE(err, nil) } } @@ -693,7 +694,7 @@ func Test_Length(t *testing.T) { func Test_MinLength(t *testing.T) { rule := "min-length:6" msgs := map[string]string{ - "min-length": "地址长度至少为:min位", + "min-length": "地址长度至少为{min}位", } if m := gvalid.CheckValue(context.TODO(), "123456", rule, nil); m != nil { t.Error(m) @@ -714,7 +715,7 @@ func Test_MinLength(t *testing.T) { func Test_MaxLength(t *testing.T) { rule := "max-length:6" msgs := map[string]string{ - "max-length": "地址长度至大为:max位", + "max-length": "地址长度至大为{max}位", } if m := gvalid.CheckValue(context.TODO(), "12345", rule, nil); m != nil { t.Error(m) @@ -1037,7 +1038,7 @@ func Test_InternalError_String(t *testing.T) { t.Assert(err.String(), "InvalidRules: hh") t.Assert(err.Strings(), g.Slice{"InvalidRules: hh"}) - t.Assert(err.FirstString(), "InvalidRules: hh") + t.Assert(err.FirstError(), "InvalidRules: hh") t.Assert(gerror.Current(err), "InvalidRules: hh") }) } diff --git a/util/gvalid/i18n/cn/validation.toml b/util/gvalid/i18n/cn/validation.toml index 902fff880..0601310b9 100644 --- a/util/gvalid/i18n/cn/validation.toml +++ b/util/gvalid/i18n/cn/validation.toml @@ -1,47 +1,47 @@ -"gf.gvalid.rule.required" = ":attribute 字段不能为空" -"gf.gvalid.rule.required-if" = ":attribute 字段不能为空" -"gf.gvalid.rule.required-unless" = ":attribute 字段不能为空" -"gf.gvalid.rule.required-with" = ":attribute 字段不能为空" -"gf.gvalid.rule.required-with-all" = ":attribute 字段不能为空" -"gf.gvalid.rule.required-without" = ":attribute 字段不能为空" -"gf.gvalid.rule.required-without-all" = ":attribute 字段不能为空" -"gf.gvalid.rule.date" = ":attribute 日期格式不满足Y-m-d格式,例如: 2001-02-03" -"gf.gvalid.rule.datetime" = ":attribute 日期格式不满足Y-m-d H:i:s格式,例如: 2001-02-03 12:00:00" -"gf.gvalid.rule.date-format" = ":attribute 日期格式不满足:format" -"gf.gvalid.rule.email" = ":attribute 邮箱地址格式不正确" -"gf.gvalid.rule.phone" = ":attribute 手机号码格式不正确" -"gf.gvalid.rule.phone-loose" = ":attribute 手机号码格式不正确" -"gf.gvalid.rule.telephone" = ":attribute 电话号码格式不正确" -"gf.gvalid.rule.passport" = ":attribute 账号格式不合法,必需以字母开头,只能包含字母、数字和下划线,长度在6~18之间" -"gf.gvalid.rule.password" = ":attribute 密码格式不合法,密码格式为任意6-18位的可见字符" -"gf.gvalid.rule.password2" = ":attribute 密码格式不合法,密码格式为任意6-18位的可见字符,必须包含大小写字母和数字" -"gf.gvalid.rule.password3" = ":attribute 密码格式不合法,密码格式为任意6-18位的可见字符,必须包含大小写字母、数字和特殊字符" -"gf.gvalid.rule.postcode" = ":attribute 邮政编码不正确" -"gf.gvalid.rule.resident-id" = ":attribute 身份证号码格式不正确" -"gf.gvalid.rule.bank-card" = ":attribute 银行卡号格式不正确" -"gf.gvalid.rule.qq" = ":attribute QQ号码格式不正确" -"gf.gvalid.rule.ip" = ":attribute IP地址格式不正确" -"gf.gvalid.rule.ipv4" = ":attribute IPv4地址格式不正确" -"gf.gvalid.rule.ipv6" = ":attribute IPv6地址格式不正确" -"gf.gvalid.rule.mac" = ":attribute MAC地址格式不正确" -"gf.gvalid.rule.url" = ":attribute URL地址格式不正确" -"gf.gvalid.rule.domain" = ":attribute 域名格式不正确" -"gf.gvalid.rule.length" = ":attribute 字段长度为:min到:max个字符" -"gf.gvalid.rule.min-length" = ":attribute 字段最小长度为:min" -"gf.gvalid.rule.max-length" = ":attribute 字段最大长度为:max" -"gf.gvalid.rule.size" = ":attribute 字段长度必须为:size" -"gf.gvalid.rule.between" = ":attribute 字段大小为:min到:max" -"gf.gvalid.rule.min" = ":attribute 字段最小值为:min" -"gf.gvalid.rule.max" = ":attribute 字段最大值为:max" -"gf.gvalid.rule.json" = ":attribute 字段应当为JSON格式" -"gf.gvalid.rule.xml" = ":attribute 字段应当为XML格式" -"gf.gvalid.rule.array" = ":attribute 字段应当为数组" -"gf.gvalid.rule.integer" = ":attribute 字段应当为整数" -"gf.gvalid.rule.float" = ":attribute 字段应当为浮点数" -"gf.gvalid.rule.boolean" = ":attribute 字段应当为布尔值" -"gf.gvalid.rule.same" = ":attribute 字段值必须和:field相同" -"gf.gvalid.rule.different" = ":attribute 字段值不能与:field相同" -"gf.gvalid.rule.in" = ":attribute 字段值不合法" -"gf.gvalid.rule.not-in" = ":attribute 字段值不合法" -"gf.gvalid.rule.regex" = ":attribute 字段值不合法" -"gf.gvalid.rule.__default__" = ":attribute 字段值不合法" \ No newline at end of file +"gf.gvalid.rule.required" = "{attribute}字段不能为空" +"gf.gvalid.rule.required-if" = "{attribute}字段不能为空" +"gf.gvalid.rule.required-unless" = "{attribute}字段不能为空" +"gf.gvalid.rule.required-with" = "{attribute}字段不能为空" +"gf.gvalid.rule.required-with-all" = "{attribute}字段不能为空" +"gf.gvalid.rule.required-without" = "{attribute}字段不能为空" +"gf.gvalid.rule.required-without-all" = "{attribute}字段不能为空" +"gf.gvalid.rule.date" = "{attribute}字段值`{value}`日期格式不满足Y-m-d格式,例如: 2001-02-03" +"gf.gvalid.rule.datetime" = "{attribute}字段值`{value}`日期格式不满足Y-m-d H:i:s格式,例如: 2001-02-03 12:00:00" +"gf.gvalid.rule.date-format" = "{attribute}字段值`{value}`日期格式不满足{format}" +"gf.gvalid.rule.email" = "{attribute}字段值`{value}`邮箱地址格式不正确" +"gf.gvalid.rule.phone" = "{attribute}字段值`{value}`手机号码格式不正确" +"gf.gvalid.rule.phone-loose" = "{attribute}字段值`{value}`手机号码格式不正确" +"gf.gvalid.rule.telephone" = "{attribute}字段值`{value}`电话号码格式不正确" +"gf.gvalid.rule.passport" = "{attribute}字段值`{value}`账号格式不合法,必需以字母开头,只能包含字母、数字和下划线,长度在6~18之间" +"gf.gvalid.rule.password" = "{attribute}字段值`{value}`密码格式不合法,密码格式为任意6-18位的可见字符" +"gf.gvalid.rule.password2" = "{attribute}字段值`{value}`密码格式不合法,密码格式为任意6-18位的可见字符,必须包含大小写字母和数字" +"gf.gvalid.rule.password3" = "{attribute}字段值`{value}`密码格式不合法,密码格式为任意6-18位的可见字符,必须包含大小写字母、数字和特殊字符" +"gf.gvalid.rule.postcode" = "{attribute}字段值`{value}`邮政编码不正确" +"gf.gvalid.rule.resident-id" = "{attribute}字段值`{value}`身份证号码格式不正确" +"gf.gvalid.rule.bank-card" = "{attribute}字段值`{value}`银行卡号格式不正确" +"gf.gvalid.rule.qq" = "{attribute}字段值`{value}`QQ号码格式不正确" +"gf.gvalid.rule.ip" = "{attribute}字段值`{value}`IP地址格式不正确" +"gf.gvalid.rule.ipv4" = "{attribute}字段值`{value}`IPv4地址格式不正确" +"gf.gvalid.rule.ipv6" = "{attribute}字段值`{value}`IPv6地址格式不正确" +"gf.gvalid.rule.mac" = "{attribute}字段值`{value}`MAC地址格式不正确" +"gf.gvalid.rule.url" = "{attribute}字段值`{value}`URL地址格式不正确" +"gf.gvalid.rule.domain" = "{attribute}字段值`{value}`域名格式不正确" +"gf.gvalid.rule.length" = "{attribute}字段值`{value}`字段长度应当为{min}到{max}个字符" +"gf.gvalid.rule.min-length" = "{attribute}字段值`{value}`字段最小长度应当为{min}" +"gf.gvalid.rule.max-length" = "{attribute}字段值`{value}`字段最大长度应当为{max}" +"gf.gvalid.rule.size" = "{attribute}字段值`{value}`字段长度必须应当为{size}" +"gf.gvalid.rule.between" = "{attribute}字段值`{value}`字段大小应当为{min}到{max}" +"gf.gvalid.rule.min" = "{attribute}字段值`{value}`字段最小值应当为{min}" +"gf.gvalid.rule.max" = "{attribute}字段值`{value}`字段最大值应当为{max}" +"gf.gvalid.rule.json" = "{attribute}字段值`{value}`字段应当为JSON格式" +"gf.gvalid.rule.xml" = "{attribute}字段值`{value}`字段应当为XML格式" +"gf.gvalid.rule.array" = "{attribute}字段值`{value}`字段应当为数组" +"gf.gvalid.rule.integer" = "{attribute}字段值`{value}`字段应当为整数" +"gf.gvalid.rule.float" = "{attribute}字段值`{value}`字段应当为浮点数" +"gf.gvalid.rule.boolean" = "{attribute}字段值`{value}`字段应当为布尔值" +"gf.gvalid.rule.same" = "{attribute}字段值`{value}`字段值必须和{field}相同" +"gf.gvalid.rule.different" = "{attribute}字段值`{value}`字段值不能与{field}相同" +"gf.gvalid.rule.in" = "{attribute}字段值`{value}`字段值应当满足取值范围:{pattern}" +"gf.gvalid.rule.not-in" = "{attribute}字段值`{value}`字段值不应当满足取值范围:{pattern}" +"gf.gvalid.rule.regex" = "{attribute}字段值`{value}`字段值不满足规则:{pattern}" +"gf.gvalid.rule.__default__" = "{attribute}字段值`{value}`字段值不合法" \ No newline at end of file diff --git a/util/gvalid/i18n/en/validation.toml b/util/gvalid/i18n/en/validation.toml index 4da8cca97..90f1a7f69 100644 --- a/util/gvalid/i18n/en/validation.toml +++ b/util/gvalid/i18n/en/validation.toml @@ -1,47 +1,45 @@ -"gf.gvalid.rule.required" = "The :attribute field is required" -"gf.gvalid.rule.required-if" = "The :attribute field is required" -"gf.gvalid.rule.required-unless" = "The :attribute field is required" -"gf.gvalid.rule.required-with" = "The :attribute field is required" -"gf.gvalid.rule.required-with-all" = "The :attribute field is required" -"gf.gvalid.rule.required-without" = "The :attribute field is required" -"gf.gvalid.rule.required-without-all" = "The :attribute field is required" -"gf.gvalid.rule.date" = "The :attribute value is not a valid date" -"gf.gvalid.rule.datetime" = "The :attribute value is not a valid datetime" -"gf.gvalid.rule.date-format" = "The :attribute value does not match the format :format" -"gf.gvalid.rule.email" = "The :attribute value must be a valid email address" -"gf.gvalid.rule.phone" = "The :attribute value must be a valid phone number" -"gf.gvalid.rule.phone-loose" = "The :attribute value must be a valid phone number" -"gf.gvalid.rule.telephone" = "The :attribute value must be a valid telephone number" -"gf.gvalid.rule.passport" = "The :attribute value is not a valid passport format" -"gf.gvalid.rule.password" = "The :attribute value is not a valid passport format" -"gf.gvalid.rule.password2" = "The :attribute value is not a valid passport format" -"gf.gvalid.rule.password3" = "The :attribute value is not a valid passport format" -"gf.gvalid.rule.postcode" = "The :attribute value is not a valid passport format" -"gf.gvalid.rule.resident-id" = "The :attribute value is not a valid resident id number" -"gf.gvalid.rule.bank-card" = "The :attribute value must be a valid bank card number" -"gf.gvalid.rule.qq" = "The :attribute value must be a valid QQ number" -"gf.gvalid.rule.ip" = "The :attribute value must be a valid IP address" -"gf.gvalid.rule.ipv4" = "The :attribute value must be a valid IPv4 address" -"gf.gvalid.rule.ipv6" = "The :attribute value must be a valid IPv6 address" -"gf.gvalid.rule.mac" = "The :attribute value must be a valid MAC address" -"gf.gvalid.rule.url" = "The :attribute value must be a valid URL address" -"gf.gvalid.rule.domain" = "The :attribute value must be a valid domain format" -"gf.gvalid.rule.length" = "The :attribute value length must be between :min and :max" -"gf.gvalid.rule.min-length" = "The :attribute value length must be equal or greater than :min" -"gf.gvalid.rule.max-length" = "The :attribute value length must be equal or lesser than :max" -"gf.gvalid.rule.size" = "The :attribute value length must be :size" -"gf.gvalid.rule.between" = "The :attribute value must be between :min and :max" -"gf.gvalid.rule.min" = "The :attribute value must be equal or greater than :min" -"gf.gvalid.rule.max" = "The :attribute value must be equal or lesser than :max" -"gf.gvalid.rule.json" = "The :attribute value must be a valid JSON string" -"gf.gvalid.rule.xml" = "The :attribute value must be a valid XML string" -"gf.gvalid.rule.array" = "The :attribute value must be an array" -"gf.gvalid.rule.integer" = "The :attribute value must be an integer" -"gf.gvalid.rule.float" = "The :attribute value must be a float" -"gf.gvalid.rule.boolean" = "The :attribute value field must be true or false" -"gf.gvalid.rule.same" = "The :attribute value must be the same as field :field" -"gf.gvalid.rule.different" = "The :attribute value must be different from field :field" -"gf.gvalid.rule.in" = "The :attribute value is not in acceptable range" -"gf.gvalid.rule.not-in" = "The :attribute value is not in acceptable range" -"gf.gvalid.rule.regex" = "The :attribute value is invalid" -"gf.gvalid.rule.__default__" = "The :attribute value is invalid" \ No newline at end of file +"gf.gvalid.rule.required" = "The {attribute} field is required" +"gf.gvalid.rule.required-if" = "The {attribute} field is required" +"gf.gvalid.rule.required-unless" = "The {attribute} field is required" +"gf.gvalid.rule.required-with" = "The {attribute} field is required" +"gf.gvalid.rule.required-with-all" = "The {attribute} field is required" +"gf.gvalid.rule.required-without" = "The {attribute} field is required" +"gf.gvalid.rule.required-without-all" = "The {attribute} field is required" +"gf.gvalid.rule.date" = "The {attribute} value `{value}` is not a valid date" +"gf.gvalid.rule.datetime" = "The {attribute} value `{value}` is not a valid datetime" +"gf.gvalid.rule.date-format" = "The {attribute} value `{value}` does not match the format: {pattern}" +"gf.gvalid.rule.email" = "The {attribute} value `{value}` is not a valid email address" +"gf.gvalid.rule.phone" = "The {attribute} value `{value}` is not a valid phone number" +"gf.gvalid.rule.telephone" = "The {attribute} value `{value}` is not a valid telephone number" +"gf.gvalid.rule.passport" = "The {attribute} value `{value}` is not a valid passport format" +"gf.gvalid.rule.password" = "The {attribute} value `{value}` is not a valid password format" +"gf.gvalid.rule.password2" = "The {attribute} value `{value}` is not a valid password format" +"gf.gvalid.rule.password3" = "The {attribute} value `{value}` is not a valid password format" +"gf.gvalid.rule.postcode" = "The {attribute} value `{value}` is not a valid postcode format" +"gf.gvalid.rule.resident-id" = "The {attribute} value `{value}` is not a valid resident id number" +"gf.gvalid.rule.bank-card" = "The {attribute} value `{value}` is not a valid bank card number" +"gf.gvalid.rule.qq" = "The {attribute} value `{value}` is not a valid QQ number" +"gf.gvalid.rule.ip" = "The {attribute} value `{value}` is not a valid IP address" +"gf.gvalid.rule.ipv4" = "The {attribute} value `{value}` is not a valid IPv4 address" +"gf.gvalid.rule.ipv6" = "The {attribute} value `{value}` is not a valid IPv6 address" +"gf.gvalid.rule.mac" = "The {attribute} value `{value}` is not a valid MAC address" +"gf.gvalid.rule.url" = "The {attribute} value `{value}` is not a valid URL address" +"gf.gvalid.rule.domain" = "The {attribute} value `{value}` is not a valid domain format" +"gf.gvalid.rule.length" = "The {attribute} value `{value}` length must be between {min} and {max}" +"gf.gvalid.rule.min-length" = "The {attribute} value `{value}` length must be equal or greater than {min}" +"gf.gvalid.rule.max-length" = "The {attribute} value `{value}` length must be equal or lesser than {max}" +"gf.gvalid.rule.size" = "The {attribute} value `{value}` length must be {size}" +"gf.gvalid.rule.between" = "The {attribute} value `{value}` must be between {min} and {max}" +"gf.gvalid.rule.min" = "The {attribute} value `{value}` must be equal or greater than {min}" +"gf.gvalid.rule.max" = "The {attribute} value `{value}` must be equal or lesser than {max}" +"gf.gvalid.rule.json" = "The {attribute} value `{value}` is not a valid JSON string" +"gf.gvalid.rule.xml" = "The {attribute} value `{value}` is not a valid XML string" +"gf.gvalid.rule.array" = "The {attribute} value `{value}` is not an array" +"gf.gvalid.rule.integer" = "The {attribute} value `{value}` is not an integer" +"gf.gvalid.rule.boolean" = "The {attribute} value `{value}` field must be true or false" +"gf.gvalid.rule.same" = "The {attribute} value `{value}` must be the same as field {pattern}" +"gf.gvalid.rule.different" = "The {attribute} value `{value}` must be different from field {pattern}" +"gf.gvalid.rule.in" = "The {attribute} value `{value}` is not in acceptable range: {pattern}" +"gf.gvalid.rule.not-in" = "The {attribute} value `{value}` must not be in range: {pattern}" +"gf.gvalid.rule.regex" = "The {attribute} value `{value}` must be in regex of: {pattern}" +"gf.gvalid.rule.gf.gvalid.rule.__default__" = "The :attribute value `:value` is invalid" \ No newline at end of file diff --git a/util/gvalid/testdata/i18n/cn/validation.toml b/util/gvalid/testdata/i18n/cn/validation.toml index 531aaa2ca..851f09e30 100644 --- a/util/gvalid/testdata/i18n/cn/validation.toml +++ b/util/gvalid/testdata/i18n/cn/validation.toml @@ -1,49 +1,49 @@ -"gf.gvalid.rule.required" = ":attribute 字段不能为空" -"gf.gvalid.rule.required-if" = ":attribute 字段不能为空" -"gf.gvalid.rule.required-unless" = ":attribute 字段不能为空" -"gf.gvalid.rule.required-with" = ":attribute 字段不能为空" -"gf.gvalid.rule.required-with-all" = ":attribute 字段不能为空" -"gf.gvalid.rule.required-without" = ":attribute 字段不能为空" -"gf.gvalid.rule.required-without-all" = ":attribute 字段不能为空" -"gf.gvalid.rule.date" = ":attribute 日期格式不正确" -"gf.gvalid.rule.date-format" = ":attribute 日期格式不满足:format" -"gf.gvalid.rule.email" = ":attribute 邮箱地址格式不正确" -"gf.gvalid.rule.phone" = ":attribute 手机号码格式不正确" -"gf.gvalid.rule.phone-loose" = ":attribute 手机号码格式不正确" -"gf.gvalid.rule.telephone" = ":attribute 电话号码格式不正确" -"gf.gvalid.rule.passport" = ":attribute 账号格式不合法,必需以字母开头,只能包含字母、数字和下划线,长度在6~18之间" -"gf.gvalid.rule.password" = ":attribute 密码格式不合法,密码格式为任意6-18位的可见字符" -"gf.gvalid.rule.password2" = ":attribute 密码格式不合法,密码格式为任意6-18位的可见字符,必须包含大小写字母和数字" -"gf.gvalid.rule.password3" = ":attribute 密码格式不合法,密码格式为任意6-18位的可见字符,必须包含大小写字母、数字和特殊字符" -"gf.gvalid.rule.postcode" = ":attribute 邮政编码不正确" -"gf.gvalid.rule.resident-id" = ":attribute 身份证号码格式不正确" -"gf.gvalid.rule.bank-card" = ":attribute 银行卡号格式不正确" -"gf.gvalid.rule.qq" = ":attribute QQ号码格式不正确" -"gf.gvalid.rule.ip" = ":attribute IP地址格式不正确" -"gf.gvalid.rule.ipv4" = ":attribute IPv4地址格式不正确" -"gf.gvalid.rule.ipv6" = ":attribute IPv6地址格式不正确" -"gf.gvalid.rule.mac" = ":attribute MAC地址格式不正确" -"gf.gvalid.rule.url" = ":attribute URL地址格式不正确" -"gf.gvalid.rule.domain" = ":attribute 域名格式不正确" -"gf.gvalid.rule.length" = ":attribute 字段长度为:min到:max个字符" -"gf.gvalid.rule.min-length" = ":attribute 字段最小长度为:min" -"gf.gvalid.rule.max-length" = ":attribute 字段最大长度为:max" -"gf.gvalid.rule.size" = ":attribute 字段长度为必须为:size" -"gf.gvalid.rule.between" = ":attribute 字段大小为:min到:max" -"gf.gvalid.rule.min" = ":attribute 字段最小值为:min" -"gf.gvalid.rule.max" = ":attribute 字段最大值为:max" -"gf.gvalid.rule.json" = ":attribute 字段应当为JSON格式" -"gf.gvalid.rule.xml" = ":attribute 字段应当为XML格式" -"gf.gvalid.rule.array" = ":attribute 字段应当为数组" -"gf.gvalid.rule.integer" = ":attribute 字段应当为整数" -"gf.gvalid.rule.float" = ":attribute 字段应当为浮点数" -"gf.gvalid.rule.boolean" = ":attribute 字段应当为布尔值" -"gf.gvalid.rule.same" = ":attribute 字段值必须和:field相同" -"gf.gvalid.rule.different" = ":attribute 字段值不能与:field相同" -"gf.gvalid.rule.in" = ":attribute 字段值不合法" -"gf.gvalid.rule.not-in" = ":attribute 字段值不合法" -"gf.gvalid.rule.regex" = ":attribute 字段值不合法" -"gf.gvalid.rule.__default__" = ":attribute 字段值不合法" - +"gf.gvalid.rule.required" = "{attribute}字段不能为空" +"gf.gvalid.rule.required-if" = "{attribute}字段不能为空" +"gf.gvalid.rule.required-unless" = "{attribute}字段不能为空" +"gf.gvalid.rule.required-with" = "{attribute}字段不能为空" +"gf.gvalid.rule.required-with-all" = "{attribute}字段不能为空" +"gf.gvalid.rule.required-without" = "{attribute}字段不能为空" +"gf.gvalid.rule.required-without-all" = "{attribute}字段不能为空" +"gf.gvalid.rule.date" = "{attribute}字段值`{value}`日期格式不满足Y-m-d格式,例如: 2001-02-03" +"gf.gvalid.rule.datetime" = "{attribute}字段值`{value}`日期格式不满足Y-m-d H:i:s格式,例如: 2001-02-03 12:00:00" +"gf.gvalid.rule.date-format" = "{attribute}字段值`{value}`日期格式不满足{format}" +"gf.gvalid.rule.email" = "{attribute}字段值`{value}`邮箱地址格式不正确" +"gf.gvalid.rule.phone" = "{attribute}字段值`{value}`手机号码格式不正确" +"gf.gvalid.rule.phone-loose" = "{attribute}字段值`{value}`手机号码格式不正确" +"gf.gvalid.rule.telephone" = "{attribute}字段值`{value}`电话号码格式不正确" +"gf.gvalid.rule.passport" = "{attribute}字段值`{value}`账号格式不合法,必需以字母开头,只能包含字母、数字和下划线,长度在6~18之间" +"gf.gvalid.rule.password" = "{attribute}字段值`{value}`密码格式不合法,密码格式为任意6-18位的可见字符" +"gf.gvalid.rule.password2" = "{attribute}字段值`{value}`密码格式不合法,密码格式为任意6-18位的可见字符,必须包含大小写字母和数字" +"gf.gvalid.rule.password3" = "{attribute}字段值`{value}`密码格式不合法,密码格式为任意6-18位的可见字符,必须包含大小写字母、数字和特殊字符" +"gf.gvalid.rule.postcode" = "{attribute}字段值`{value}`邮政编码不正确" +"gf.gvalid.rule.resident-id" = "{attribute}字段值`{value}`身份证号码格式不正确" +"gf.gvalid.rule.bank-card" = "{attribute}字段值`{value}`银行卡号格式不正确" +"gf.gvalid.rule.qq" = "{attribute}字段值`{value}`QQ号码格式不正确" +"gf.gvalid.rule.ip" = "{attribute}字段值`{value}`IP地址格式不正确" +"gf.gvalid.rule.ipv4" = "{attribute}字段值`{value}`IPv4地址格式不正确" +"gf.gvalid.rule.ipv6" = "{attribute}字段值`{value}`IPv6地址格式不正确" +"gf.gvalid.rule.mac" = "{attribute}字段值`{value}`MAC地址格式不正确" +"gf.gvalid.rule.url" = "{attribute}字段值`{value}`URL地址格式不正确" +"gf.gvalid.rule.domain" = "{attribute}字段值`{value}`域名格式不正确" +"gf.gvalid.rule.length" = "{attribute}字段值`{value}`字段长度应当为{min}到{max}个字符" +"gf.gvalid.rule.min-length" = "{attribute}字段值`{value}`字段最小长度应当为{min}" +"gf.gvalid.rule.max-length" = "{attribute}字段值`{value}`字段最大长度应当为{max}" +"gf.gvalid.rule.size" = "{attribute}字段值`{value}`字段长度必须应当为{size}" +"gf.gvalid.rule.between" = "{attribute}字段值`{value}`字段大小应当为{min}到{max}" +"gf.gvalid.rule.min" = "{attribute}字段值`{value}`字段最小值应当为{min}" +"gf.gvalid.rule.max" = "{attribute}字段值`{value}`字段最大值应当为{max}" +"gf.gvalid.rule.json" = "{attribute}字段值`{value}`字段应当为JSON格式" +"gf.gvalid.rule.xml" = "{attribute}字段值`{value}`字段应当为XML格式" +"gf.gvalid.rule.array" = "{attribute}字段值`{value}`字段应当为数组" +"gf.gvalid.rule.integer" = "{attribute}字段值`{value}`字段应当为整数" +"gf.gvalid.rule.float" = "{attribute}字段值`{value}`字段应当为浮点数" +"gf.gvalid.rule.boolean" = "{attribute}字段值`{value}`字段应当为布尔值" +"gf.gvalid.rule.same" = "{attribute}字段值`{value}`字段值必须和{field}相同" +"gf.gvalid.rule.different" = "{attribute}字段值`{value}`字段值不能与{field}相同" +"gf.gvalid.rule.in" = "{attribute}字段值`{value}`字段值应当满足取值范围:{pattern}" +"gf.gvalid.rule.not-in" = "{attribute}字段值`{value}`字段值不应当满足取值范围:{pattern}" +"gf.gvalid.rule.regex" = "{attribute}字段值`{value}`字段值不满足规则:{pattern}" +"gf.gvalid.rule.__default__" = "{attribute}字段值`{value}`字段值不合法" "CustomMessage" = "自定义错误" -"project id must between :min, :max" = "项目ID必须大于等于:min并且要小于等于:max" \ No newline at end of file +"project id must between {min}, {max}" = "项目ID必须大于等于{min}并且要小于等于{max}" \ No newline at end of file diff --git a/util/gvalid/testdata/i18n/en/validation.toml b/util/gvalid/testdata/i18n/en/validation.toml index 4de5880d2..90f1a7f69 100644 --- a/util/gvalid/testdata/i18n/en/validation.toml +++ b/util/gvalid/testdata/i18n/en/validation.toml @@ -1,46 +1,45 @@ -"gf.gvalid.rule.required" = "The :attribute field is required" -"gf.gvalid.rule.required-if" = "The :attribute field is required" -"gf.gvalid.rule.required-unless" = "The :attribute field is required" -"gf.gvalid.rule.required-with" = "The :attribute field is required" -"gf.gvalid.rule.required-with-all" = "The :attribute field is required" -"gf.gvalid.rule.required-without" = "The :attribute field is required" -"gf.gvalid.rule.required-without-all" = "The :attribute field is required" -"gf.gvalid.rule.date" = "The :attribute value is not a valid date" -"gf.gvalid.rule.date-format" = "The :attribute value does not match the format :format" -"gf.gvalid.rule.email" = "The :attribute value must be a valid email address" -"gf.gvalid.rule.phone" = "The :attribute value must be a valid phone number" -"gf.gvalid.rule.phone-loose" = "The :attribute value must be a valid phone number" -"gf.gvalid.rule.telephone" = "The :attribute value must be a valid telephone number" -"gf.gvalid.rule.passport" = "The :attribute value is not a valid passport format" -"gf.gvalid.rule.password" = "The :attribute value is not a valid passport format" -"gf.gvalid.rule.password2" = "The :attribute value is not a valid passport format" -"gf.gvalid.rule.password3" = "The :attribute value is not a valid passport format" -"gf.gvalid.rule.postcode" = "The :attribute value is not a valid passport format" -"gf.gvalid.rule.resident-id" = "The :attribute value is not a valid resident id number" -"gf.gvalid.rule.bank-card" = "The :attribute value must be a valid bank card number" -"gf.gvalid.rule.qq" = "The :attribute value must be a valid QQ number" -"gf.gvalid.rule.ip" = "The :attribute value must be a valid IP address" -"gf.gvalid.rule.ipv4" = "The :attribute value must be a valid IPv4 address" -"gf.gvalid.rule.ipv6" = "The :attribute value must be a valid IPv6 address" -"gf.gvalid.rule.mac" = "The :attribute value must be a valid MAC address" -"gf.gvalid.rule.url" = "The :attribute value must be a valid URL address" -"gf.gvalid.rule.domain" = "The :attribute value must be a valid domain format" -"gf.gvalid.rule.length" = "The :attribute value length must be between :min and :max" -"gf.gvalid.rule.min-length" = "The :attribute value length must be equal or greater than :min" -"gf.gvalid.rule.max-length" = "The :attribute value length must be equal or lesser than :max" -"gf.gvalid.rule.size" = "The :attribute value length must be :size" -"gf.gvalid.rule.between" = "The :attribute value must be between :min and :max" -"gf.gvalid.rule.min" = "The :attribute value must be equal or greater than :min" -"gf.gvalid.rule.max" = "The :attribute value must be equal or lesser than :max" -"gf.gvalid.rule.json" = "The :attribute value must be a valid JSON string" -"gf.gvalid.rule.xml" = "The :attribute value must be a valid XML string" -"gf.gvalid.rule.array" = "The :attribute value must be an array" -"gf.gvalid.rule.integer" = "The :attribute value must be an integer" -"gf.gvalid.rule.float" = "The :attribute value must be a float" -"gf.gvalid.rule.boolean" = "The :attribute value field must be true or false" -"gf.gvalid.rule.same" = "The :attribute value must be the same as field :field" -"gf.gvalid.rule.different" = "The :attribute value must be different from field :field" -"gf.gvalid.rule.in" = "The :attribute value is not in acceptable range" -"gf.gvalid.rule.not-in" = "The :attribute value is not in acceptable range" -"gf.gvalid.rule.regex" = "The :attribute value is invalid" -"gf.gvalid.rule.__default__" = "The :attribute value is invalid" \ No newline at end of file +"gf.gvalid.rule.required" = "The {attribute} field is required" +"gf.gvalid.rule.required-if" = "The {attribute} field is required" +"gf.gvalid.rule.required-unless" = "The {attribute} field is required" +"gf.gvalid.rule.required-with" = "The {attribute} field is required" +"gf.gvalid.rule.required-with-all" = "The {attribute} field is required" +"gf.gvalid.rule.required-without" = "The {attribute} field is required" +"gf.gvalid.rule.required-without-all" = "The {attribute} field is required" +"gf.gvalid.rule.date" = "The {attribute} value `{value}` is not a valid date" +"gf.gvalid.rule.datetime" = "The {attribute} value `{value}` is not a valid datetime" +"gf.gvalid.rule.date-format" = "The {attribute} value `{value}` does not match the format: {pattern}" +"gf.gvalid.rule.email" = "The {attribute} value `{value}` is not a valid email address" +"gf.gvalid.rule.phone" = "The {attribute} value `{value}` is not a valid phone number" +"gf.gvalid.rule.telephone" = "The {attribute} value `{value}` is not a valid telephone number" +"gf.gvalid.rule.passport" = "The {attribute} value `{value}` is not a valid passport format" +"gf.gvalid.rule.password" = "The {attribute} value `{value}` is not a valid password format" +"gf.gvalid.rule.password2" = "The {attribute} value `{value}` is not a valid password format" +"gf.gvalid.rule.password3" = "The {attribute} value `{value}` is not a valid password format" +"gf.gvalid.rule.postcode" = "The {attribute} value `{value}` is not a valid postcode format" +"gf.gvalid.rule.resident-id" = "The {attribute} value `{value}` is not a valid resident id number" +"gf.gvalid.rule.bank-card" = "The {attribute} value `{value}` is not a valid bank card number" +"gf.gvalid.rule.qq" = "The {attribute} value `{value}` is not a valid QQ number" +"gf.gvalid.rule.ip" = "The {attribute} value `{value}` is not a valid IP address" +"gf.gvalid.rule.ipv4" = "The {attribute} value `{value}` is not a valid IPv4 address" +"gf.gvalid.rule.ipv6" = "The {attribute} value `{value}` is not a valid IPv6 address" +"gf.gvalid.rule.mac" = "The {attribute} value `{value}` is not a valid MAC address" +"gf.gvalid.rule.url" = "The {attribute} value `{value}` is not a valid URL address" +"gf.gvalid.rule.domain" = "The {attribute} value `{value}` is not a valid domain format" +"gf.gvalid.rule.length" = "The {attribute} value `{value}` length must be between {min} and {max}" +"gf.gvalid.rule.min-length" = "The {attribute} value `{value}` length must be equal or greater than {min}" +"gf.gvalid.rule.max-length" = "The {attribute} value `{value}` length must be equal or lesser than {max}" +"gf.gvalid.rule.size" = "The {attribute} value `{value}` length must be {size}" +"gf.gvalid.rule.between" = "The {attribute} value `{value}` must be between {min} and {max}" +"gf.gvalid.rule.min" = "The {attribute} value `{value}` must be equal or greater than {min}" +"gf.gvalid.rule.max" = "The {attribute} value `{value}` must be equal or lesser than {max}" +"gf.gvalid.rule.json" = "The {attribute} value `{value}` is not a valid JSON string" +"gf.gvalid.rule.xml" = "The {attribute} value `{value}` is not a valid XML string" +"gf.gvalid.rule.array" = "The {attribute} value `{value}` is not an array" +"gf.gvalid.rule.integer" = "The {attribute} value `{value}` is not an integer" +"gf.gvalid.rule.boolean" = "The {attribute} value `{value}` field must be true or false" +"gf.gvalid.rule.same" = "The {attribute} value `{value}` must be the same as field {pattern}" +"gf.gvalid.rule.different" = "The {attribute} value `{value}` must be different from field {pattern}" +"gf.gvalid.rule.in" = "The {attribute} value `{value}` is not in acceptable range: {pattern}" +"gf.gvalid.rule.not-in" = "The {attribute} value `{value}` must not be in range: {pattern}" +"gf.gvalid.rule.regex" = "The {attribute} value `{value}` must be in regex of: {pattern}" +"gf.gvalid.rule.gf.gvalid.rule.__default__" = "The :attribute value `:value` is invalid" \ No newline at end of file diff --git a/version.go b/version.go index 122362f54..de38fb4b1 100644 --- a/version.go +++ b/version.go @@ -1,4 +1,4 @@ package gf -const VERSION = "v2.0.0-alpha" +const VERSION = "v2.0.0-beta" const AUTHORS = "john"