[GOLANG] go mod

2,576 阅读2分钟

背景

刚开始学习golang语言(版本:1.14),下载好之后,hello world!程序完美运行,之后我想尝试import功能,在main函数中调用自定义包pcenter/wechat的方法,发现报package pcenter/wechat is not in GOROOT 错误,查找资料后发现和1.11版本之后发布的mod功能有关,遂总结如下文字。

问题解决方案

如果读者和我遇到同样的问题,简单解决方案为修改环境变量 export GO111MODULE=auto

go mod 简介

go modules 是 golang 1.11 新加的特性。Modules官方定义为:

模块是相关Go包的集合。modules是源代码交换和版本控制的单元。 go命令直接支持使用modules,包括记录和解析对其他模块的依赖性。modules替换旧的基于GOPATH的方法来指定在给定构建中使用哪些源文件。

可以简单理解为golang的包管理器,相当于java的maven,或者nodejs的package。

GO111MODULE

使用该功能需要制定环境变量export GO111MODULE=on,mac使用brew安装的1.14版本默认下载好就是这个配置。其它方式请手动修改。

go mod 命令

golang使用go mod命令管理包,包括以下几种

命令 说明
download download modules to local cache(下载依赖包)
edit edit go.mod from tools or scripts(编辑go.mod)
graph print module requirement graph(打印模块依赖图)
init initialize new module in current directory(在当前目录初始化mod)
tidy add missing and remove unused modules(拉取缺少的模块,移除不用的模块)
vendor make vendored copy of dependencies(将依赖复制到vendor下)
verify verify dependencies have expected content(验证依赖是否正确)
why explain why packages or modules are needed(解释为什么需要依赖)

在项目中的运用(以创建新项目示例)

  1. 项目初始化
mkdir test
cd test
go mod init test

创建好后,将在test目录下生成go.mod文件。

2.在test目录下编写一个引用其他包的文件

package main

import "github.com/parnurzeal/gorequest"

func main() {
    request := gorequest.New()
    ······
}
  1. 执行go run main.go 或自动下载依赖,并将依赖关系写入go.mod文件