语言技巧
gofmt 格式化代码
gofmt -s -w xxx.go
嵌套结构体屏蔽指定字段 json 输出
type User struct {
Pwd string `json:"pwd"`
Age int `json:"age"`
}
type UserOut struct {
User
Pwd *struct{} `json:"pwd,omitempty"`// 这里的字段json名需要和嵌套的字段json名一致,否则无效
}
func TestJson(t *testing.T) {
u := User{Pwd: "123", Age: 1}
bb := UserOut{User: u}
b, _ := json.MarshalIndent(bb, "", " ")
t.Log(string(b))
}
github action 使用 ubuntu-latest 执行 make xxx 操作时,需要在 Makefile 指定 shell
在首行添加
SHELL := /bin/bash
go get 指定版本
从 Go 1.11 开始,使用 Go modules 可以做到这一点。在为 Go 模块安装依赖项时,你可以指定一个模块查询,其中可能包含分支或标记名称:
拉取最新的版本(优先择取 tag)
go get golang.org/x/text@latest
拉取 master 分支的最新 commit
go get golang.org/x/text@master
# 如果分支带斜杠需要设置直连
GOPROXY=direct GOSUMDB=off go install github.com/gogf/gf/cmd/gf/v2@feat/docrun
拉取 tag 为 v0.3.2 的 commit
go get golang.org/x/text@v0.3.2
拉取 hash 为 342b231 的 commit,最终会被转换为 v0.3.2:
go get golang.org/x/text@342b2e
指定版本拉取,拉取 v3 版本
go get github.com/smartwalle/alipay/v3
清理 go mod 缓存
go clean -modcache
查看模块有哪些版本
go list -m -versions github.com/gogf/gf/v2
go list -m -versions github.com/gogf/gf/cmd/gf/v2
go mod 查看间接依赖来源
go mod why github.com/gogf/gf/v2
# 再详细的依赖树
go mod graph | grep github.com/gogf/gf/v2
go mod 通过 replace 使用来自 fork 的包
例如这个驱动没有合并到主库https://github.com/okyer/gf/blob/master/contrib/drivers/gaussdb/go.mod
# import _ "github.com/gogf/gf/contrib/drivers/gaussdb/v2"
# 在不知道版本号的情况下
go mod edit -replace github.com/gogf/gf/contrib/drivers/gaussdb/v2=github.com/okyer/gf/contrib/drivers/gaussdb/v2@latest
go mod tidy
构建
windows
在 Windows 下如果开启了 cgo,那么极大概率是无法交叉编译。参考
set GOOS=linux
set GOARCH=amd64
GCC
https://jmeubank.github.io/tdm-gcc/download/
目标平台
https://golang.google.cn/doc/install/source
darwin amd64
darwin arm64
ios amd64
ios arm64
freebsd 386
freebsd amd64
freebsd arm
linux 386
linux amd64
linux arm
linux arm64
linux ppc64
linux ppc64le
linux mips
linux mipsle
linux mips64
linux mips64le
netbsd 386
netbsd amd64
netbsd arm
openbsd 386
openbsd amd64
openbsd arm
windows 386
windows amd64
android arm
dragonfly amd64
plan9 386
plan9 amd64
solaris amd64
pprof 使用
gf 的配置方式,https://wiki.goframe.org/pages/viewpage.action?pageId=1114350
开启后使用视图形式查看
需 要下载安装graphviz
内存分析
切换视图,通过不同的视图查看内存使用情况,定位内存占用过高的地方
# 直接执行
go tool pprof -http="127.0.0.1:8080" http://127.0.0.1:8000/debug/pprof/heap
# 或者先下载 http://localhost/debug/pprof/heap
go tool pprof -http=":8080" heap
# 实时内存
# http://127.0.0.1:8080/ui/peek?si=inuse_space
# http://127.0.0.1:8080/ui/top?si=inuse_space
# 历史内存
# http://127.0.0.1:8080/ui/?si=alloc_space
CPU 分析
# 直接执行
go tool pprof -http="127.0.0.1:8081" http://127.0.0.1:8000/debug/pprof/profile
# 或者先下载 http://localhost/debug/pprof/profile
go tool pprof -http=":8081" profile