About the use of go mod and goland configuration go mod

1. About go modules

  • 1.1 go modules are a new feature of go1.11
    现在已有go 1.13.4 了本人用了就是最新版的
  • 1.2 About the official definition of modules
模块是相关Go包的集合。modules是源代码交换和版本控制的单元。 go命令直接支持使用modules,包括记录和解析对其他模块的依赖性。modules替换旧的基于GOPATH的方法来指定在给定构建中使用哪些源文件。
  • 1.3 Configuration using modules
    • Configure GO111MODULE
      GO111MODULE 有三个值 off , on,auto
GO111MODULE=off,go命令行将不会支持module功能,寻找依赖包的方式将会沿用旧版本那种通过vendor目录或者GOPATH模式来查找。
GO111MODULE=on,go命令行会使用modules,而一点也不会去GOPATH/src目录下查找。 (pkg 包都存放在 $GOPATH/pkg 下)
GO111MODULE=auto,默认值,go命令行将会根据当前目录来决定是否启用module功能。(pkg 包都存放在 $GOPATH/pkg 下)
  • 1.4 Personal configuration
    export GO111MODULE=auto
因为以前没有使用 ,未来兼容以前的项目,暂设成auto

Two, some commands of go mod

command Description
download download modules to local cache (important to download dependency packages)
edit edit go.mod from tools or scripts(编辑go.mod
graph print module requirement graph
init initialize new module in current directory (it is important to initialize mod in the current directory)
tidy add missing and remove unused modules (pull missing modules, remove unused modules is important)
vendor make vendored copy of dependencies (copy dependencies to vendor)
verify verify dependencies have expected content (verify dependencies are correct)
why explain why packages or modules are needed

Three, how to use go mod

  • 3.1 Simple to use
mkdir hello
cd hello 
go mod init hello 
# 此时会出现一个hello下会出现一个 go.mod 目录
# 需要下载 所有第三方包时 go mod download
# 下载第三包可以直接使用 go get need_pkg
# 下载好的依赖 和 版本 会加入到 go.mod 里面,
# 下载好的第三包 会放在到$GOPATH/pkg/mod 中
# 没有设置GOPATH的话 下载好的第三方包会放在~/go/pkg/mod
# 如果你想放在当前目前可以执行如下命令
go mod vendor    
# 此时你的包就会出现在vendor下了,意思是将依赖包放在vendor中
  • 3.2 About dependency upgrade
go list -m -u all 来检查可以升级的package
go get -u  升级所有依赖
go get -u need-pack 升级指定的依赖  
  • 3.3 About dependency packaging
go build  -ldflags="-s -w" -o app ./main.go
# -ldflags="-s -w" 压缩程序
  • 3.4 When github pulls other people's projects containing go.mod, download all third-party packages
go mod download
  • 3.5 About how to use custom packages
hello
    |--conf
        |-conf.go
    |-main.go
    |-go.mod
如何导入conf 包呢?
先查看go.mod 中的module 后的定义的module_name
在导入时  直接使用module_name/conf   即可

First look at the module_name in go.mod
module_name/pkc

Four, goland configuration

goland 升级到最新的,旧的goland 版本时不支持go mod,
在preferences -> go -> Go Modules(vgo) 
给Enable Go Modules (vgo) Integration 打勾勾就行

modules settings

上图的那个圈起来的地方一定要勾上,
Enable Go Modules(vgo)   启用modules 模式

verdoring mode  会使用vendor 文件夹中的包(不用打勾,打勾意味着依赖包都使用vendor 目录里面的.)

Guess you like

Origin blog.csdn.net/zimu312500/article/details/107850804