improve example codes

This commit is contained in:
John
2019-09-24 23:41:18 +08:00
parent 6d4da529ee
commit b0f859cc91
32 changed files with 177 additions and 405 deletions

View File

@ -1,16 +0,0 @@
package main
import "fmt"
func main() {
array := []uint{1, 1, 2, 3, 3, 4, 4, 5, 5, 6, 6}
for i := 0; i < len(array)-1; i++ {
for j := i + 1; j < len(array); j++ {
if array[i] == array[j] {
array = append(array[:j], array[j+1:]...)
}
}
}
fmt.Println(array)
}

View File

@ -0,0 +1,46 @@
package main
import (
"fmt"
"github.com/gogf/gf/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())
}

View File

@ -1,59 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/container/garray"
)
func main() {
// 创建普通的int类型数组并关闭默认的并发安全特性
a := garray.NewIntArray(true)
// 添加数据项
for i := 0; i < 10; i++ {
a.Append(i)
}
// 获取当前数组长度
fmt.Println(a.Len())
// 获取当前数据项列表
fmt.Println(a.Slice())
// 获取指定索引项
fmt.Println(a.Get(6))
// 在指定索引前插入数据项
a.InsertAfter(9, 11)
// 在指定索引后插入数据项
a.InsertBefore(10, 10)
fmt.Println(a.Slice())
// 修改指定索引的数据项
a.Set(0, 100)
fmt.Println(a.Slice())
// 搜索数据项,返回搜索到的索引位置
fmt.Println(a.Search(5))
// 删除指定索引的数据项
a.Remove(0)
fmt.Println(a.Slice())
// 并发安全,写锁操作
a.LockFunc(func(array []int) {
// 将末尾项改为100
array[len(array)-1] = 100
})
// 并发安全,读锁操作
a.RLockFunc(func(array []int) {
fmt.Println(array[len(array)-1])
})
// 清空数组
fmt.Println(a.Slice())
a.Clear()
fmt.Println(a.Slice())
}

View File

@ -1,17 +0,0 @@
package main
import (
"github.com/gogf/gf/container/garray"
"github.com/gogf/gf/frame/g"
)
func main() {
a := garray.NewIntArray()
a.Append(1, 2, 3)
v := a.Slice()
v[0] = 4
g.Dump(a.Slice())
g.Dump(v)
}

View File

@ -1,20 +1,23 @@
package main
import (
"fmt"
"github.com/gogf/gf/container/garray"
"github.com/gogf/gf/frame/g"
)
func main() {
array := garray.NewSortedStringArray()
array.Add("1")
array.Add("2")
array.Add("3")
array.Add("4")
array.Add("5")
array.Add("6")
array.Add("7")
array.Add("8")
array := garray.NewSortedStrArray()
array.Add("9")
g.Dump(array.Slice())
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]
}

View File

@ -1,27 +0,0 @@
package main
import (
"fmt"
"strings"
"github.com/gogf/gf/container/garray"
"github.com/gogf/gf/frame/g"
)
func main() {
array := garray.NewSortedStringArray()
array.Add("/api/ctl/show")
array.Add("/api/ctl/post")
array.Add("/api/obj/rest")
array.Add("/api/handler")
array.Add("/api/obj/delete")
array.Add("/api/obj/show")
array.Add("/api/obj/my-show")
array.Add("/api/*")
array.Add("/api/ctl/rest")
array.Add("/api/ctl/my-show")
g.Dump(array.Slice())
fmt.Println(strings.Compare("/api/ctl/post", "/api/*"))
fmt.Println(strings.Compare("/api/*", "/api/ctl/my-show"))
}

View File

@ -8,13 +8,6 @@ import (
)
func main() {
//m := gmap.New()
//m.Set("k", "v")
//m.Set("1", "2")
//b, err := json.Marshal(m)
//fmt.Println(err)
//fmt.Println(string(b))
m := gmap.NewIntIntMap()
m.Set(1, 2)
m.Set(3, 4)

View File

@ -0,0 +1,26 @@
package main
import (
"github.com/gogf/gf/container/gmap"
"github.com/gogf/gf/frame/g"
)
func main() {
m1 := gmap.New()
m1.Set("1", "1")
m2 := m1.Map()
m2["2"] = "2"
g.Dump(m1.Clone())
g.Dump(m2)
//output:
//{
// "1": "1"
//}
//
//{
// "1": "1",
// "2": "2"
//}
}

View File

@ -1,17 +0,0 @@
package main
import (
"github.com/gogf/gf/container/gmap"
"github.com/gogf/gf/frame/g"
)
func main() {
m := gmap.New()
m.Set("1", "1")
m1 := m.Map()
m1["2"] = "2"
g.Dump(m.Clone())
g.Dump(m1)
}

View File

@ -10,9 +10,9 @@ import (
func main() {
array := g.Slice{2, 3, 1, 5, 4, 6, 8, 7, 9}
hashMap := gmap.New(true)
linkMap := gmap.NewLinkMap(true)
treeMap := gmap.NewTreeMap(gutil.ComparatorInt, true)
hashMap := gmap.New()
linkMap := gmap.NewListMap()
treeMap := gmap.NewTreeMap(gutil.ComparatorInt)
for _, v := range array {
hashMap.Set(v, v)
}

View File

@ -1,39 +0,0 @@
package main
import (
"fmt"
"sync"
"time"
)
// 验证 map 的delete方法是否并发安全
func main() {
// 创建一个初始化的map
m := make(map[int]int)
for i := 0; i < 10000; i++ {
m[i] = i
}
fmt.Println("map size:", len(m))
wg := sync.WaitGroup{}
ev := make(chan struct{}, 0)
// 创建10个并发的goroutine使用ev控制并发开始事件更容易模拟data race
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
<-ev
fmt.Println("start")
for i := 0; i < 10000; i++ {
delete(m, i)
}
wg.Done()
}()
}
time.Sleep(time.Second)
close(ev)
wg.Wait()
}

View File

@ -30,8 +30,4 @@ func main() {
s := new(Score)
v.Struct(s)
fmt.Println(s)
// 只读接口
r := v.ReadOnly()
fmt.Println(r.String())
}

View File

@ -519,7 +519,6 @@ func getQueriedSqls() {
fmt.Println("Sql :", v.Sql)
fmt.Println("Args :", v.Args)
fmt.Println("Error:", v.Error)
fmt.Println("Func :", v.Func)
}
}

View File

@ -8,9 +8,9 @@ import (
func main() {
db := g.DB()
db.SetMaxIdleConns(10)
db.SetMaxOpenConns(10)
db.SetConnMaxLifetime(10)
db.SetMaxIdleConnCount(10)
db.SetMaxOpenConnCount(10)
db.SetMaxConnLifetime(time.Minute)
// 开启调试模式以便于记录所有执行的SQL
db.SetDebug(true)

View File

@ -520,7 +520,6 @@ func getQueriedSqls() {
fmt.Println("Sql :", v.Sql)
fmt.Println("Args :", v.Args)
fmt.Println("Error:", v.Error)
fmt.Println("Func :", v.Func)
}
}

View File

@ -1,47 +1,47 @@
package main
//import (
// _ "github.com/mattn/go-sqlite3"
// "github.com/gogf/gf/database/gdb"
// "github.com/gogf/gf/frame/g"
// "fmt"
//)
//
//func main() {
// gdb.SetConfig(gdb.Config{
// "default": gdb.ConfigGroup{
// gdb.ConfigNode{
// Name: "/tmp/my.db",
// Type: "sqlite",
// },
// },
// })
// db := g.Database()
// if db == nil {
// panic("db create failed")
// }
// defer db.Close()
//
// // 创建表
// 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)
// }
//}
import (
"fmt"
"github.com/gogf/gf/database/gdb"
"github.com/gogf/gf/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)
}
}

View File

@ -1,60 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/util/gconv"
"github.com/gogf/gf/os/gcmd"
"github.com/gogf/gf/container/garray"
"github.com/gogf/gf/database/gredis"
"github.com/gogf/gf/frame/g"
)
func main() {
batchNumber := 1000
redis1Config, err := gredis.ConfigFromStr("im-redis-slave:6379,9")
if err != nil {
panic(err)
}
redis2Config, err := gredis.ConfigFromStr("r-bp1f0a5d4efd8744.redis.rds.aliyuncs.com:6379,9")
if err != nil {
panic(err)
}
gredis.SetConfig(redis1Config)
v, err := g.Redis().DoVar("keys", "*")
if err != nil {
panic(err)
}
array := garray.NewStrArrayFrom(v.Strings())
for {
slice := array.PopLefts(batchNumber)
if len(slice) > 0 {
// `migrate %s %d "" 0 2000 copy replace auth %s keys %s`,
params := g.Slice{
redis2Config.Host,
redis2Config.Port,
"",
redis2Config.Db,
2000,
"copy",
"replace",
"keys",
}
params = append(params, gconv.Interfaces(slice)...)
fmt.Println(params)
if gcmd.GetOpt("dryrun") == "0" {
if v, err := g.Redis().DoVar("migrate", params...); err != nil {
panic(err)
} else {
fmt.Println(v.String())
}
}
} else {
break
}
}
fmt.Println("done")
}

View File

@ -1,4 +1,4 @@
package main
package gbase64
import (
"fmt"

View File

@ -9,26 +9,19 @@ import (
func main() {
// 使用gbinary.Encoded对基本数据类型进行二进制打包
if buffer, err := gbinary.Encode(18, 300, 1.01); err != nil {
glog.Error(err)
} else {
fmt.Println(buffer)
}
fmt.Println(gbinary.Encode(18, 300, 1.01))
// 使用gbinary.Decode对整形二进制解包注意第二个及其后参数为字长确定的整形变量的指针地址字长确定的类型
// 例如int8/16/32/64、uint8/16/32/64、float32/64
// 这里的1.01默认为float64类型(64位系统下)
if buffer, err := gbinary.Encode(18, 300, 1.01); err != nil {
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 {
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)
}
fmt.Println(i1, i2, f3)
}
// 编码/解析 int自动识别变量长度

View File

@ -15,6 +15,6 @@ func main() {
}
redisCfg := new(RedisConfig)
fmt.Println(g.Config().GetToStruct("redis", redisCfg))
fmt.Println(g.Config().GetStruct("redis", redisCfg))
fmt.Println(redisCfg)
}

View File

@ -15,4 +15,6 @@ func main() {
panic(err)
}
fmt.Println(str)
// output:
// 花间一壶酒,独酌无相亲。
}

View File

@ -19,7 +19,7 @@ func getWithPattern1() {
}
}`
if p, e := gparser.LoadContent([]byte(data), "json"); e != nil {
if p, e := gparser.LoadContent([]byte(data)); e != nil {
glog.Error(e)
} else {
fmt.Println("John Score:", p.GetFloat32("users.list.1.score"))
@ -36,7 +36,7 @@ func getWithPattern2() {
<body>Don't forget me this weekend!</body>
</note>`
if p, e := gparser.LoadContent([]byte(data), "xml"); e != nil {
if p, e := gparser.LoadContent([]byte(data)); e != nil {
glog.Error(e)
} else {
fmt.Println("Heading:", p.GetString("note.heading"))
@ -52,7 +52,7 @@ func multiDots1() {
},
"users.count" : 101
}`
if p, e := gparser.LoadContent([]byte(data), "json"); e != nil {
if p, e := gparser.LoadContent([]byte(data)); e != nil {
glog.Error(e)
} else {
fmt.Println("Users Count:", p.Get("users.count"))
@ -70,7 +70,7 @@ func multiDots2() {
"count.type1" : 100
}
}`
if p, e := gparser.LoadContent([]byte(data), "json"); e != nil {
if p, e := gparser.LoadContent([]byte(data)); e != nil {
glog.Error(e)
} else {
fmt.Println("Users Count:", p.Get("users.count.type1"))
@ -88,7 +88,7 @@ func set1() {
<list><title>gf article2</title><content>gf content2</content></list>
<list><title>gf article3</title><content>gf content3</content></list>
</article>`
if p, e := gparser.LoadContent([]byte(data), "xml"); e != nil {
if p, e := gparser.LoadContent([]byte(data)); e != nil {
glog.Error(e)
} else {
p.Set("article.list.0", nil)
@ -105,7 +105,7 @@ func set2() {
"count" : 100
}
}`
if p, e := gparser.LoadContent([]byte(data), "json"); e != nil {
if p, e := gparser.LoadContent([]byte(data)); e != nil {
glog.Error(e)
} else {
p.Set("users.count", 1)
@ -116,7 +116,7 @@ func set2() {
}
func makeXml1() {
p := gparser.New()
p := gparser.New(nil)
p.Set("name", "john")
p.Set("age", 18)
p.Set("scores", map[string]int{
@ -133,7 +133,7 @@ func makeJson1() {
Id int `json:"id"`
Price float32 `json:"price"`
}
p := gparser.New()
p := gparser.New(nil)
p.Set("orders.list.0", Order{1, 100})
p.Set("orders.list.1", Order{2, 666})
p.Set("orders.list.2", Order{3, 999.99})

View File

@ -1,4 +0,0 @@
# MySQL数据库配置
[database]
link = "mysql:root:12345678@tcp(127.0.0.1:3306)/test"

View File

@ -1,13 +0,0 @@
package main
import (
"github.com/gogf/gf/.example/frame/mvc/model/test"
"github.com/gogf/gf/frame/g"
)
func main() {
g.DB().SetDebug(true)
user, err := test.ModelUser().One()
g.Dump(err)
g.Dump(user)
}

View File

@ -1,16 +0,0 @@
package main
import (
"fmt"
"time"
)
func main() {
l := flock.NewFlock("/tmp/go-lock.lock")
l.Lock()
fmt.Printf("lock 1")
l.Lock()
fmt.Printf("lock 1")
time.Sleep(time.Hour)
}

View File

@ -1,18 +0,0 @@
package main
import (
"time"
"github.com/gogf/gf/os/gflock"
"github.com/gogf/gf/os/glog"
"github.com/gogf/gf/os/gproc"
)
func main() {
l := gflock.New("demo.lock")
l.Lock()
glog.Printf("locked by pid: %d", gproc.Pid())
time.Sleep(10 * time.Second)
l.UnLock()
glog.Printf("unlocked by pid: %d", gproc.Pid())
}