下载包 go get

-x :下载依赖包,并显示执行的命令

构建 go build

-n :显示构建过程的命令,但不执行
-x :显示执行构建的命令
-o :构建输出可执行文件

1
go build -o app 

运行

1
go run . 

包依赖

1
go mod tidy && go mod vendor

如果遇到以下问题,则是由代码中引入的package地址与项目的git仓库不一致导致的。
例如:
代码中引入package github.com/coreos/prometheus-operator/pkg/client, 但它的git仓库是github.com/prometheus-operator/prometheus-operator/pkg/client,在执行go mod tidy则会报错:

1
2
3
4
go: example.com/operator imports
github.com/coreos/prometheus-operator/pkg/client/versioned: github.com/coreos/prometheus-operator/pkg/client@v0.57.0: parsing go.mod:
module declares its path as: github.com/prometheus-operator/prometheus-operator/pkg/client
but was required as: github.com/coreos/prometheus-operator/pkg/client

需要在当前项目中的go.mod中添加replace

1
2
3
4
5
module example.com

go 1.18

replace github.com/coreos/prometheus-operator/pkg/client => github.com/prometheus-operator/prometheus-operator/pkg/client v0.57.0

或者执行

1
go mod edit -replace github.com/coreos/prometheus-operator/pkg/client=github.com/prometheus-operator/prometheus-operator/pkg/client@v0.57.0

展示包下的函数 go doc

1
2
go doc net/http
go doc fmt.Printf

Go 升级

下载最新版GO:The Go Programming Language

1
2
3
$ go env GOROOT
/usr/local/go
## 将下载文件解压,替换GOROO文件夹内容