golang生成uuid
# 建立一个文件 test.go
[root@sltvb7v2wy3 jia_uuid]# cat test.go
package main
import (
"fmt"
"github.com/gofrs/uuid"
)
func main() {
uuid, _ := uuid.NewV4()
fmt.Println("uuid: ", uuid)
}
# 尝试运行 test.go, 提示缺少安装包 uuid. go.mod 也不存在
[root@sltvb7v2wy3 jia_uuid]# go run test.go
test.go:6:1: no required module provides package github.com/gofrs/uuid: go.mod file not found in current directory or any parent directory; see 'go help modules'
# 使用 go mod init <module> 生成go.mod 文件
[root@sltvb7v2wy3 jia_uuid]# go mod init example/uuid
go: creating new go.mod: module example/uuid
go: to add module requirements and sums:
go mod tidy
# 可以看到本地生成了 go.mod 文件
[root@sltvb7v2wy3 jia_uuid]# ls
go.mod test.go
# 查看 go.mod 文件
[root@sltvb7v2wy3 jia_uuid]# cat go.mod
module example/uuid
go 1.19
# 尝试执行test.go, 提示需要安装包
[root@sltvb7v2wy3 jia_uuid]# go run test.go
test.go:6:1: no required module provides package github.com/gofrs/uuid; to add it:
go get github.com/gofrs/uuid
# 按照提示,安装 uuid 包
[root@sltvb7v2wy3 jia_uuid]# go get github.com/gofrs/uuid
go: downloading github.com/gofrs/uuid v4.3.1+incompatible
go: added github.com/gofrs/uuid v4.3.1+incompatible
# 查看文件,本地生成 go.mod
[root@sltvb7v2wy3 jia_uuid]# ll
total 12
-rw-r--r-- 1 root root 92 Dec 6 15:46 go.mod
-rw-r--r-- 1 root root 187 Dec 6 15:46 go.sum
-rw-r--r-- 1 root root 133 Dec 6 15:40 test.go
# 查看此时的go.sum
[root@sltvb7v2wy3 jia_uuid]# cat go.sum
github.com/gofrs/uuid v4.3.1+incompatible h1:0/KbAdpx3UXAx1kEOWHJeOkpbgRFGHVgv+CFIY7dBJI=
github.com/gofrs/uuid v4.3.1+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
# 查看此时的go.mod
[root@sltvb7v2wy3 jia_uuid]# cat go.mod
module example/uuid
go 1.19
require github.com/gofrs/uuid v4.3.1+incompatible // indirect
# 再次运行test.go, uuid 生成
[root@sltvb7v2wy3 jia_uuid]# go run test.go
uuid: d31c22bc-e5ea-4857-8208-3b61a7fc4c42