1. go mod

1.1 创建项目

  • 创建一个目录
root@liubei:/data/goproject/src# mkdir go-test
root@liubei:/data/goproject/src# cd go-test/
  • 添加main.go
package main

import "github.com/gin-gonic/gin"

func main() {
	r := gin.Default()
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
	r.Run() 

1.2 mod初始化

  • 执行如下命令:
# go mod init
  • 多了一个go.mod文件
root@liubei:/data/goproject/src/go-test# ls
go.mod  main.go
  • 其内容如下:
module go-test

go 1.17

1.3 重新构建依赖

  • 执行入下命令重新构建依赖
# go mod tidy

依赖的包会写到go.mod 文件中

  • go.mod 文件内容如下:
module go-test

go 1.17

require github.com/gin-gonic/gin v1.7.6

require (
	github.com/gin-contrib/sse v0.1.0 // indirect
	github.com/go-playground/locales v0.13.0 // indirect
	github.com/go-playground/universal-translator v0.17.0 // indirect
	github.com/go-playground/validator/v10 v10.4.1 // indirect
	github.com/golang/protobuf v1.3.3 // indirect
	github.com/json-iterator/go v1.1.9 // indirect
	github.com/leodido/go-urn v1.2.0 // indirect
	github.com/mattn/go-isatty v0.0.12 // indirect
	github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
	github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 // indirect
	github.com/ugorji/go/codec v1.1.7 // indirect
	golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 // indirect
	golang.org/x/sys v0.0.0-20200116001909-b77594299b42 // indirect
	gopkg.in/yaml.v2 v2.2.8 // indirect
)

但此时 这些依赖在goland中看都是红色,说明这些依赖还没有被下载

1.4 编译

# go build main.go

此时从goland中可以看到,这些包的引用都变成了绿色

2. vendor

作用:将依赖包拷贝到代码目录下vendor目录

2.1 拷贝依赖

# go mod vendor
  • 此时多了 vendor目录
root@liubei:/data/goproject/src/go-test# ll
总用量 8936
drwxr-xr-x 4 root root    4096 1124 19:48 ./
drwxr-xr-x 5 root root    4096 1124 18:45 ../
-rw-r--r-- 1 root root     870 1124 18:56 go.mod
-rw-r--r-- 1 root root    5037 1124 18:56 go.sum
drwxr-xr-x 2 root root    4096 1124 19:03 .idea/
-rwxr-xr-x 1 root root 9114818 1124 19:01 main*
-rw-r--r-- 1 root root     230 1124 18:52 main.go
drwxr-xr-x 5 root root    4096 1124 19:48 vendor/

2.2 使用vendor目录编译

# go build -mod vendor

说明:如果不使用 -mod则依然不会使用项目vendor中的依赖

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐