- 文档 https://goframe.org/index 21M
- 登录认证 https://gitee.com/goflyfox/gtoken
修改"github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" s := g.Server() s.BindHandler("/", func(r *ghttp.Request) { r.Response.Write("哈喽世界!") }) s.SetPort(8888) s.Run()
C:\www\go\pkg\mod\github.com\gogf\gf@v1.16.6\os\gproc
gproc_comm.go 54行 ./tmphttps://goframe.org/cli
//工具下载
gf init gf //创建一个gf项目 gf init . 当前目录下创建
交叉编译工具 gf build 下面是配置
[gfcli]
[gfcli.build]
name = "stock"
arch = "amd64"
system = "linux,windows"
mod = "none"
cgo = 0
pack = "public,template,config"
gf工具
gf run main.go -o gf.exe 编译
gf pack public,template packed/data.go 打包
gf get github.com/gogf/gf 下载
gf update 更新工具
gf -v常用数据类型 使用 g.Map{}调用
var v g.Var 任意类型
// 泛型
type Var = gvar.Var
// 常用Map类型
type Map = map[string]interface{}
type MapAnyAny = map[interface{}]interface{}
type MapAnyStr = map[interface{}]string
type MapAnyInt = map[interface{}]int
type MapStrAny = map[string]interface{}
type MapStrStr = map[string]string
type MapStrInt = map[string]int
type MapIntAny = map[int]interface{}
type MapIntStr = map[int]string
type MapIntInt = map[int]int
// 常用Slice Map类型
type List = []Map
type ListAnyStr = []map[interface{}]string
type ListAnyInt = []map[interface{}]int
type ListStrAny = []map[string]interface{}
type ListStrStr = []map[string]string
type ListStrInt = []map[string]int
type ListIntAny = []map[int]interface{}
type ListIntStr = []map[int]string
type ListIntInt = []map[int]int
// 常用Slice类型
type Slice = []interface{}
type SliceAny = []interface{}
type SliceStr = []string
type SliceInt = []int
// 常用Slice类型(别名)
type Array = []interface{}
type ArrayAny = []interface{}
type ArrayStr = []string
type ArrayInt = []int
gconv.String(v) //gconv用于类型转换模块
g.Cfg().Get("database") //获取配置
g.Cfg().Get("database.default.1.name") 层级读取
a:=gerror.NewCode(400,"错误")
fmt.Println(gerror.Code(a))//错误码
c := gcache.New()
// 设置缓存,不过期
c.Set("k1", "v1", 0)
// 当键名不存在时写入,设置过期时间1000毫秒
gcache.SetIfNotExist("k1", "v1", 1000*time.Millisecond)
// 获取缓存
v, _ := c.Get("k1")
// 缓存中是否存在指定键名
b, _ := c.Contains("k1")
c.Remove("k1")
c.Close()
g.View().SetPath("template")//设置模板
g.View().BindFuncMap(g.Map{})//自定义函数
r.Response.WriteTpl("/shop/index.html")
match, _ := gregex.MatchString(`(\w+).+\-\-\s*(.+)`, `GF is best! -- John`)正则
str, _ := gcharset.Convert("UTF-8", "GB2312", src) 编码转换
s := g.Server()
s.SetIndexFolder(true) 是否列出文件
s.SetServerRoot("/home/www/")设置目录
s.AddStaticPath("/weui", "/public/weui")
//路由分组
s := g.Server()
s.Group("/", func(group *ghttp.RouterGroup) {
group.Middleware(MiddlewareCORS)
group.ALL("/hello", api.Hello)
})
s.Group("/api", func(group *ghttp.RouterGroup) {
group.POST("/hello", api.Hello)
GET,PUT,DELETE,HEAD
})
//任何类型转换成slice
ss:=g.Var{}
ss.Set("[1,2,3]")
json.Unmarshal(ss.Bytes(),&ss)
fmt.Println(&ss)
ss:="[1,2,3]"
json.Unmarshal([]byte(ss),&ss)
fmt.Println(ss)
ss:=g.Var{}
json.Unmarshal(rs["data"].Bytes(), &ss)
r.Response.WriteJson(g.Map{"code":200,"msg":"请求成功","list":&ss})
//请求参数
s.BindHandler("/", func(r *ghttp.Request) {
id:=r.GetInt("id",1) //转换成int
id:=r.GetString("id","字符串") //转换字符串
id:=r.Get("id")//这三个支持任意类型POST GET ALL 用 id==nil判断是否变量存在
r.Cookie.SetCookie("ids","中国","","/",0)//0表示不过期
ids:=r.Cookie.Get("ids")
r.Cookie.Remove("ids") //移除cookie
r.Session.Set("name", "john")
name:=r.Session.GetString("name")
r.Session.Remove("name") 移除
r.Session.Clear()
r.Response.RedirectTo("weui/index.html",301)//301跳转
r.Response.Writeln(id)//输出到页面
r.Response.WriteJson(g.Map{
"id": 1,
"name": "john",
})
r.Response.WriteJsonP(g.Map{
"id": 1,
"name": "john",
})
r.Response.Write(`<?xml version="1.0" encoding="UTF-8"?>`)
r.Response.WriteXml(g.Map{
"id": 1,
"name": "john",
})
r.Exit()//退出
})
//跨域中间件
func MiddlewareCORS(r *ghttp.Request) {
r.Response.CORSDefault()
r.Middleware.Next()
}
//鉴权中间件
func MiddlewareAuth(r *ghttp.Request) {
token := r.Get("token")
if token == "200820" {
r.Middleware.Next()
} else {
r.Response.WriteJson(g.Map{"code":403,"msg":"无权访问"})
}
}
- ORM操作
rs.IsEmpty() 判断是否为空 true为空
m:= g.Model("tb")
m:= g.Model("user").Safe()//可多次m=m.xxx使用
rs,_:=g.Model("user").Where("id in(?)",g.Slice{1,3}).All()//查询多条返回数组,len(rs)==0表示没查到
rs,_:=g.Model("user").Where("id in(?)",g.Slice{1,3}).One()//单条,len(rs)==0表示没查到
rs,_:=g.Model("user").Where("id in(?)",g.Slice{1,3}).Count()//记录数
rs,_:=g.Model("user").Where("id in(?)",g.Slice{1,3}).Array("id")//返回单列组成的切片
rs,_:=g.Model("user").Where("id in(?)",g.Slice{1}).Value("id")//返回单子段IsEmpty判断为空没查到
var rs *User
//废弃统一scan g.Model("user").Where("id in(?)",g.Slice{1}).Struct(&rs)
fmt.Println(rs.Username)//查询一条返回结构体 没找到 rs==nil只能这样判断
var rs []*User
//废弃统一scan g.Model("user").Where("id in(?)",g.Slice{1,3}).Structs(&rs)
for _,v:=range rs{
fmt.Println(v.Username)
}//返回结构体,len(rs)==0没找到
var rs []*User
g.Model("user").Where("id in(?)",g.Slice{1}).Scan(&rs)//返回结构体,len(rs)==0没找到,用于单条多条
sql操作
rs, _ := g.DB().GetAll("select * from user")
rs, _ := g.DB().GetOne("select * from user")
rs, _ := g.DB().Exec("update user set username=? where id=1","新闻")//支持sql原生
n,_:=rs.LastInsertId()
m,_:=rs.RowsAffected()
//插入
rs, err := g.Model("user").Data(g.Map{"name": "john","id":"id+1"}).Insert()//直接写入
user:=&User{Id:1}
rs, err := g.Model("user").Data(user).Insert()//结构体写入
n,_:=rs.RowsAffected() //记录=1表示插入一行
id,_:=rs.LastInsertId() //插入后id
//快捷插入
rs, _ := g.DB().Insert("user",g.Map{"username":"li"})
//修改
rs,_:=g.Model("user").Data(g.Map{"username":"李虎"}).Where("id",1).Update()
m,_:=rs.RowsAffected() //判断是否修改成功,0没有修改
rs, _ := g.DB().Update("user",g.Map{"username":"li"},"id=1")//快捷
rs,_:=g.Model("user").Data(g.Map{"username":"李虎","num":gdb.Raw("num+1")}).Where("id",1).Update()//支持公式+1
//删除
rs, err := g.Model("user").Where("id", 10).Delete()
m,_:=rs.RowsAffected() //m>0表示删除成功
rs, _ := g.DB().Delete("user",g.Map{"id":4})//快捷方法
Group("age")//分组
Order("class asc,course asc,score desc")//排序
Having("score>?", 60)//过滤
Limit(0, 10) //page pagesize
condition := g.Map{
"title like ?" : "%九寨%",
"online" : 1,
"hits between ? and ?" : g.Slice{1, 10},
"exp > 0" : nil,
"category" : g.Slice{100, 200},
}
Where(condition)
Fields("uid, nickname") 字段选择
Cache(time.Hour, "vip-user") 缓存一小时 -1是清楚
Unscoped()忽略软删除
r["id"].Int() 类型转换
- redis
[redis]
default = "127.0.0.1:6379,0"
cache = "127.0.0.1:6379,1,123456?idleTimeout=600"
conn := g.Redis().Conn()
defer conn.Close()
conn.Do("SET", "k", "v")
v, _ := conn.Do("GET", "k")
fmt.Println(gconv.String(v))
v, _ := g.Redis().DoVar("GET", "k")//处理更方便
fmt.Println(v.String())
conn.Send("GET", "foo")//多条调用
v, _ := conn.Receive()//取回结果
作者:Yoby 创建时间:2020-09-05 22:56
更新时间:2024-12-05 13:26
更新时间:2024-12-05 13:26