go-mod

概述

本文是阅读了别人的文档之后,做的笔记。
go modules 是 golang 1.11 新加的特性。

当modules 功能启用时,依赖包的存放位置变更为$GOPATH/pkg,允许同一个package多个版本并存,且多个项目可以共享缓存的 module。

特性和node.js的node_module有些类似,项目可以自己制定需要使用的包的版本

如何开启

通过调整 GO111MODULE 环境变量来改变开启状态;一共3个状态:off, on和auto(默认值)

export GO111MODULE=on
  • off

go命令行将不会支持module功能,寻找依赖包的方式将会沿用旧版本那种通过vendor目录或者GOPATH模式来查找。

  • on

go命令行会使用modules,而一点也不会去GOPATH目录下查找。

  • auto

默认值,go命令行将会根据当前目录来决定是否启用module功能。这种情况下可以分为两种情形:
当前目录在GOPATH/src之外且该目录包含go.mod文件
当前文件在包含go.mod文件的目录下面。

go mod命令

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(解释为什么需要依赖)
实例

创建一个目录,并且将这个目录使用go mod初始化

mkdir squid
cd squid
PS C:\main\code\squid> go mod init squid
go: creating new go.mod: module squid

然后开始编写一个main.go文件。

package main

import (
	"github.com/sirupsen/logrus"
)

func main() {
	logrus.Debug("hello world.")
}

执行 go run main.go 运行代码会发现 go mod 会自动查找依赖自动下载:
将会触发下载github.com/sirupsen/logrus库;
会修改工作目录中go.mod文件

module squid

go 1.13

require (
	github.com/sirupsen/logrus v1.4.2
)

go 会自动生成一个 go.sum 文件来记录 dependency tree:

go mod tidy

这个命令很有用 首先我们看看它的官方解释 tidy: add missing and remove unused modules
也就是说 你的go.mod中多引入的或者是少引入的 使用 go mod tidy 它可以帮你处理;

我无法使用goalng.org/x的包我该怎么办

例如:
你本地的包要引入 golang.org/x/net/html
但是被封了,那么你可以使用github上的镜像包 例如说是 github.com/golang/x/net/html

在你的项目的go.mod 中 加入
replace golang.org/x/net/html => github.com/golang/x/net/html
但是一般你科学上网不就行了吗。。

使用replace

如果需要使用本地的库,就需要用这个replace语法,否则go mod方式下,会出现这样的报错:

build _/C_/main/code/squid/squid_svr/test/greeter: cannot find module for path _/C_/main/code/squid/squid_svr/test/greeter

在mod文件中添加这样的语句,就能将本地的子目录用起来了
replace greeter => …/greeter
如果是在本项目下面的子目录,直接写全的mod目录。

参考链接
发布了76 篇原创文章 · 获赞 13 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/erlang_hell/article/details/104281996