go modules 学习

tags:golang

安装

只需要golang的版本是1.11及之后的,这个模块就内置好了

环境变量

(1) 配置GoLang的GOROOT

(2) 可以不配置GoLang的GOPATH

(3) 配置mod模块的状态

export GO111MODULE=auto
可选值有三个:on:开启,off:关闭,auto:自动
如果是自动模式,文件夹下有go.mod则是开启状态,否则是关闭状态
如果是开启状态,则GOPATH失效

(4) 配置mod的国内代理

#这是阿里的配置
export GOPROXY=https://mirrors.aliyun.com/goproxy/

在goland中的使用

打开goland的设置,然后配置如下:

go_mod.jpg

使用

初始化modules

$ go mod init bitcoin
go: creating new go.mod: module bitcoin

代码编辑

可以引入 GoLang 的官方包,也可以引入非官方包

导入代码需要的依赖

$ go mod tidy

常用命令

$ go help mod
Go mod provides access to operations on modules. Note that support for modules is built into all the go commands,
not just 'go mod'. For example, day-to-day adding, removing, upgrading,
and downgrading of dependencies should be done using 'go get'.
See 'go help modules' for an overview of module functionality. Usage: go mod <command> [arguments] The commands are: download download modules to local cache
edit edit go.mod from tools or scripts
graph print module requirement graph
init initialize new module in current directory
tidy add missing and remove unused modules
vendor make vendored copy of dependencies
verify verify dependencies have expected content
why explain why packages or modules are needed Use "go help mod <command>" for more information about a command.

翻译一下

Go mod提供对模块操作的访问。

注意,所有的go命令都内置了对模块的支持,而不仅仅是"go mod"。例如,日常应该使用"go get"来完成依赖的添加、删除、升级、降级。
更多模块功能的概述,请参阅"go help modules",我把它放在附录里了。 用法:
go mod <命令> [参数]
命令如下:
download 将模块下载到本地缓存
edit 通过工具或脚本编辑"go.mod"
graph 打印模块需求图
init 当前目录下初始化新的模块,后接参数模块名
tidy 添加需要的依赖和删除未使用的依赖
verdor 把依赖项复制到vendor文件中
verify 验证依赖项是否被修改过
why 解释为什么需要包或模块

常见的问题

问题一

$ go mod init
go: cannot determine module path for source directory /Users/shanpengfei/work/go-work-space/src/github.com/shanpengfei7/bitcoin (outside GOPATH, no import comments)

解决方法:init后面应该加上模块的名字

$ go mod init bitcoin
go: creating new go.mod: module bitcoin

问题二

$ go mod init
go: modules disabled inside GOPATH/src by GO111MODULE=auto; see 'go help modules' $ go mod init bitcoin
go: modules disabled inside GOPATH/src by GO111MODULE=auto; see 'go help modules'

解决方法:不要在$GOPATH路径下执行该命令。或者换个路径,或者把环境变量中的$GOPATH置空

附录

看一下官方介绍 go module 的原文:

A module is a collection of related Go packages.
Modules are the unit of source code interchange and versioning.
The go command has direct support for working with modules,
including recording and resolving dependencies on other modules.
Modules replace the old GOPATH-based approach to specifying
which source files are used in a given build. Preliminary module support Go 1.11 includes preliminary support for Go modules,
including a new module-aware 'go get' command.
We intend to keep revising this support, while preserving compatibility,
until it can be declared official (no longer preliminary),
and then at a later point we may remove support for work
in GOPATH and the old 'go get' command. The quickest way to take advantage of the new Go 1.11 module support
is to check out your repository into a directory outside GOPATH/src,
create a go.mod file (described in the next section) there, and run
go commands from within that file tree. For more fine-grained control, the module support in Go 1.11 respects
a temporary environment variable, GO111MODULE, which can be set to one
of three string values: off, on, or auto (the default).
If GO111MODULE=off, then the go command never uses the
new module support. Instead it looks in vendor directories and GOPATH
to find dependencies; we now refer to this as "GOPATH mode."
If GO111MODULE=on, then the go command requires the use of modules,
never consulting GOPATH. We refer to this as the command being
module-aware or running in "module-aware mode".
If GO111MODULE=auto or is unset, then the go command enables or
disables module support based on the current directory.
Module support is enabled only when the current directory is outside
GOPATH/src and itself contains a go.mod file or is below a directory
containing a go.mod file. In module-aware mode, GOPATH no longer defines the meaning of imports
during a build, but it still stores downloaded dependencies (in GOPATH/pkg/mod)
and installed commands (in GOPATH/bin, unless GOBIN is set). Defining a module A module is defined by a tree of Go source files with a go.mod file
in the tree's root directory. The directory containing the go.mod file
is called the module root. Typically the module root will also correspond
to a source code repository root (but in general it need not).
The module is the set of all Go packages in the module root and its
subdirectories, but excluding subtrees with their own go.mod files. The "module path" is the import path prefix corresponding to the module root.
The go.mod file defines the module path and lists the specific versions
of other modules that should be used when resolving imports during a build,
by giving their module paths and versions. For example, this go.mod declares that the directory containing it is the root
of the module with path example.com/m, and it also declares that the module
depends on specific versions of golang.org/x/text and gopkg.in/yaml.v2: module example.com/m require (
golang.org/x/text v0.3.0
gopkg.in/yaml.v2 v2.1.0
) The go.mod file can also specify replacements and excluded versions
that only apply when building the module directly; they are ignored
when the module is incorporated into a larger build.
For more about the go.mod file, see 'go help go.mod'. To start a new module, simply create a go.mod file in the root of the
module's directory tree, containing only a module statement.
The 'go mod init' command can be used to do this: go mod init example.com/m In a project already using an existing dependency management tool like
godep, glide, or dep, 'go mod init' will also add require statements
matching the existing configuration. Once the go.mod file exists, no additional steps are required:
go commands like 'go build', 'go test', or even 'go list' will automatically
add new dependencies as needed to satisfy imports. The main module and the build list The "main module" is the module containing the directory where the go command
is run. The go command finds the module root by looking for a go.mod in the
current directory, or else the current directory's parent directory,
or else the parent's parent directory, and so on. The main module's go.mod file defines the precise set of packages available
for use by the go command, through require, replace, and exclude statements.
Dependency modules, found by following require statements, also contribute
to the definition of that set of packages, but only through their go.mod
files' require statements: any replace and exclude statements in dependency
modules are ignored. The replace and exclude statements therefore allow the
main module complete control over its own build, without also being subject
to complete control by dependencies. The set of modules providing packages to builds is called the "build list".
The build list initially contains only the main module. Then the go command
adds to the list the exact module versions required by modules already
on the list, recursively, until there is nothing left to add to the list.
If multiple versions of a particular module are added to the list,
then at the end only the latest version (according to semantic version
ordering) is kept for use in the build. The 'go list' command provides information about the main module
and the build list. For example: go list -m # print path of main module
go list -m -f={{.Dir}} # print root directory of main module
go list -m all # print build list Maintaining module requirements The go.mod file is meant to be readable and editable by both
programmers and tools. The go command itself automatically updates the go.mod file
to maintain a standard formatting and the accuracy of require statements. Any go command that finds an unfamiliar import will look up the module
containing that import and add the latest version of that module
to go.mod automatically. In most cases, therefore, it suffices to
add an import to source code and run 'go build', 'go test', or even 'go list':
as part of analyzing the package, the go command will discover
and resolve the import and update the go.mod file. Any go command can determine that a module requirement is
missing and must be added, even when considering only a single
package from the module. On the other hand, determining that a module requirement
is no longer necessary and can be deleted requires a full view of
all packages in the module, across all possible build configurations
(architectures, operating systems, build tags, and so on).
The 'go mod tidy' command builds that view and then
adds any missing module requirements and removes unnecessary ones. As part of maintaining the require statements in go.mod, the go command
tracks which ones provide packages imported directly by the current module
and which ones provide packages only used indirectly by other module
dependencies. Requirements needed only for indirect uses are marked with a
"// indirect" comment in the go.mod file. Indirect requirements are
automatically removed from the go.mod file once they are implied by other
direct requirements. Indirect requirements only arise when using modules
that fail to state some of their own dependencies or when explicitly
upgrading a module's dependencies ahead of its own stated requirements. Because of this automatic maintenance, the information in go.mod is an
up-to-date, readable description of the build. The 'go get' command updates go.mod to change the module versions used in a
build. An upgrade of one module may imply upgrading others, and similarly a
downgrade of one module may imply downgrading others. The 'go get' command
makes these implied changes as well. If go.mod is edited directly, commands
like 'go build' or 'go list' will assume that an upgrade is intended and
automatically make any implied upgrades and update go.mod to reflect them. The 'go mod' command provides other functionality for use in maintaining
and understanding modules and go.mod files. See 'go help mod'. The -mod build flag provides additional control over updating and use of go.mod. If invoked with -mod=readonly, the go command is disallowed from the implicit
automatic updating of go.mod described above. Instead, it fails when any changes
to go.mod are needed. This setting is most useful to check that go.mod does
not need updates, such as in a continuous integration and testing system.
The "go get" command remains permitted to update go.mod even with -mod=readonly,
and the "go mod" commands do not take the -mod flag (or any other build flags). If invoked with -mod=vendor, the go command assumes that the vendor
directory holds the correct copies of dependencies and ignores
the dependency descriptions in go.mod. Pseudo-versions The go.mod file and the go command more generally use semantic versions as
the standard form for describing module versions, so that versions can be
compared to determine which should be considered earlier or later than another.
A module version like v1.2.3 is introduced by tagging a revision in the
underlying source repository. Untagged revisions can be referred to
using a "pseudo-version" like v0.0.0-yyyymmddhhmmss-abcdefabcdef,
where the time is the commit time in UTC and the final suffix is the prefix
of the commit hash. The time portion ensures that two pseudo-versions can
be compared to determine which happened later, the commit hash identifes
the underlying commit, and the prefix (v0.0.0- in this example) is derived from
the most recent tagged version in the commit graph before this commit. There are three pseudo-version forms: vX.0.0-yyyymmddhhmmss-abcdefabcdef is used when there is no earlier
versioned commit with an appropriate major version before the target commit.
(This was originally the only form, so some older go.mod files use this form
even for commits that do follow tags.) vX.Y.Z-pre.0.yyyymmddhhmmss-abcdefabcdef is used when the most
recent versioned commit before the target commit is vX.Y.Z-pre. vX.Y.(Z+1)-0.yyyymmddhhmmss-abcdefabcdef is used when the most
recent versioned commit before the target commit is vX.Y.Z. Pseudo-versions never need to be typed by hand: the go command will accept
the plain commit hash and translate it into a pseudo-version (or a tagged
version if available) automatically. This conversion is an example of a
module query. Module queries The go command accepts a "module query" in place of a module version
both on the command line and in the main module's go.mod file.
(After evaluating a query found in the main module's go.mod file,
the go command updates the file to replace the query with its result.) A fully-specified semantic version, such as "v1.2.3",
evaluates to that specific version. A semantic version prefix, such as "v1" or "v1.2",
evaluates to the latest available tagged version with that prefix. A semantic version comparison, such as "<v1.2.3" or ">=v1.5.6",
evaluates to the available tagged version nearest to the comparison target
(the latest version for < and <=, the earliest version for > and >=). The string "latest" matches the latest available tagged version,
or else the underlying source repository's latest untagged revision. A revision identifier for the underlying source repository,
such as a commit hash prefix, revision tag, or branch name,
selects that specific code revision. If the revision is
also tagged with a semantic version, the query evaluates to
that semantic version. Otherwise the query evaluates to a
pseudo-version for the commit. All queries prefer release versions to pre-release versions.
For example, "<v1.2.3" will prefer to return "v1.2.2"
instead of "v1.2.3-pre1", even though "v1.2.3-pre1" is nearer
to the comparison target. Module versions disallowed by exclude statements in the
main module's go.mod are considered unavailable and cannot
be returned by queries. For example, these commands are all valid: go get github.com/gorilla/mux@latest # same (@latest is default for 'go get')
go get github.com/gorilla/mux@v1.6.2 # records v1.6.2
go get github.com/gorilla/mux@e3702bed2 # records v1.6.2
go get github.com/gorilla/mux@c856192 # records v0.0.0-20180517173623-c85619274f5d
go get github.com/gorilla/mux@master # records current meaning of master Module compatibility and semantic versioning The go command requires that modules use semantic versions and expects that
the versions accurately describe compatibility: it assumes that v1.5.4 is a
backwards-compatible replacement for v1.5.3, v1.4.0, and even v1.0.0.
More generally the go command expects that packages follow the
"import compatibility rule", which says: "If an old package and a new package have the same import path,
the new package must be backwards compatible with the old package." Because the go command assumes the import compatibility rule,
a module definition can only set the minimum required version of one
of its dependencies: it cannot set a maximum or exclude selected versions.
Still, the import compatibility rule is not a guarantee: it may be that
v1.5.4 is buggy and not a backwards-compatible replacement for v1.5.3.
Because of this, the go command never updates from an older version
to a newer version of a module unasked. In semantic versioning, changing the major version number indicates a lack
of backwards compatibility with earlier versions. To preserve import
compatibility, the go command requires that modules with major version v2
or later use a module path with that major version as the final element.
For example, version v2.0.0 of example.com/m must instead use module path
example.com/m/v2, and packages in that module would use that path as
their import path prefix, as in example.com/m/v2/sub/pkg. Including the
major version number in the module path and import paths in this way is
called "semantic import versioning". Pseudo-versions for modules with major
version v2 and later begin with that major version instead of v0, as in
v2.0.0-20180326061214-4fc5987536ef. As a special case, module paths beginning with gopkg.in/ continue to use the
conventions established on that system: the major version is always present,
and it is preceded by a dot instead of a slash: gopkg.in/yaml.v1
and gopkg.in/yaml.v2, not gopkg.in/yaml and gopkg.in/yaml/v2. The go command treats modules with different module paths as unrelated:
it makes no connection between example.com/m and example.com/m/v2.
Modules with different major versions can be used together in a build
and are kept separate by the fact that their packages use different
import paths. In semantic versioning, major version v0 is for initial development,
indicating no expectations of stability or backwards compatibility.
Major version v0 does not appear in the module path, because those
versions are preparation for v1.0.0, and v1 does not appear in the
module path either. Code written before the semantic import versioning convention
was introduced may use major versions v2 and later to describe
the same set of unversioned import paths as used in v0 and v1.
To accommodate such code, if a source code repository has a
v2.0.0 or later tag for a file tree with no go.mod, the version is
considered to be part of the v1 module's available versions
and is given an +incompatible suffix when converted to a module
version, as in v2.0.0+incompatible. The +incompatible tag is also
applied to pseudo-versions derived from such versions, as in
v2.0.1-0.yyyymmddhhmmss-abcdefabcdef+incompatible. In general, having a dependency in the build list (as reported by 'go list -m all')
on a v0 version, pre-release version, pseudo-version, or +incompatible version
is an indication that problems are more likely when upgrading that
dependency, since there is no expectation of compatibility for those. See https://research.swtch.com/vgo-import for more information about
semantic import versioning, and see https://semver.org/ for more about
semantic versioning. Module code layout For now, see https://research.swtch.com/vgo-module for information
about how source code in version control systems is mapped to
module file trees. Module downloading and verification The go command maintains, in the main module's root directory alongside
go.mod, a file named go.sum containing the expected cryptographic checksums
of the content of specific module versions. Each time a dependency is
used, its checksum is added to go.sum if missing or else required to match
the existing entry in go.sum. The go command maintains a cache of downloaded packages and computes
and records the cryptographic checksum of each package at download time.
In normal operation, the go command checks these pre-computed checksums
against the main module's go.sum file, instead of recomputing them on
each command invocation. The 'go mod verify' command checks that
the cached copies of module downloads still match both their recorded
checksums and the entries in go.sum. The go command can fetch modules from a proxy instead of connecting
to source control systems directly, according to the setting of the GOPROXY
environment variable. See 'go help goproxy' for details about the proxy and also the format of
the cached downloaded packages. Modules and vendoring When using modules, the go command completely ignores vendor directories. By default, the go command satisfies dependencies by downloading modules
from their sources and using those downloaded copies (after verification,
as described in the previous section). To allow interoperation with older
versions of Go, or to ensure that all files used for a build are stored
together in a single file tree, 'go mod vendor' creates a directory named
vendor in the root directory of the main module and stores there all the
packages from dependency modules that are needed to support builds and
tests of packages in the main module. To build using the main module's top-level vendor directory to satisfy
dependencies (disabling use of the usual network sources and local
caches), use 'go build -mod=vendor'. Note that only the main module's
top-level vendor directory is used; vendor directories in other locations
are still ignored.

欢迎阅读单鹏飞的学习笔记

go modules 学习的更多相关文章

  1. Golang(八)go modules 学习

    0. 前言 最近加入鹅厂学习 k8s,组内使用 Go 1.11 以上的 go modules 管理依赖,因此整理了相关资料 本文严重参考原文:初窥Go module 1. 传统 Golang 包依赖管 ...

  2. go modules学习

    https://github.com/golang/go/wiki/Modules https://tonybai.com/2018/07/15/hello-go-module/ https://ww ...

  3. 1全志 A20 camera移植

    转自 http://www.right.com.cn/forum/thread-146260-1-1.html   在Android4.0升级后,突然发现大量平台对Camera的支持均非常不好.要么C ...

  4. django-jet 中文文档

    关于 JET是新式的Django管理界面并且增强了功能.     内容 文档 开始 安装django-jet 安装仪表盘 配置 配置文件 自动补全 紧凑内联 过滤器 仪表盘 自定义仪表盘 仪表盘模块 ...

  5. AngularJs学习笔记--Modules

    原版地址:http://code.angularjs.org/1.0.2/docs/guide/module 一.什么是Module? 很多应用都有一个用于初始化.加载(wires是这个意思吗?)和启 ...

  6. node 学习笔记 - Modules 模块加载系统 (1)

    本文同步自我的个人博客:http://www.52cik.com/2015/12/11/learn-node-modules-path.html 用了这么久的 require,但却没有系统的学习过 n ...

  7. Python Tutorial 学习(六)--Modules

    6. Modules 当你退出Python的shell模式然后又重新进入的时候,之前定义的变量,函数等都会没有了. 因此, 推荐的做法是将这些东西写入文件,并在适当的时候调用获取他们. 这就是为人所知 ...

  8. react native 学习之 native modules

    翻译自https://facebook.github.io/react-native/docs/native-modules-ios.html Native Modules 很多情况下,app需要使用 ...

  9. webpack学习之——模块(Modules)

    在模块化编程中,开发者将程序分解成离散功能块(discrete chunks of functionality),并称之为模块. 每个模块具有比完整程序更小的接触面,使得校验.调试.测试轻而易举. 精 ...

随机推荐

  1. 玩转OneNET物联网平台之MQTT服务⑤ —— OneNet智能灯+MVP框架

    授人以鱼不如授人以渔,目的不是为了教会你具体项目开发,而是学会学习的能力.希望大家分享给你周边需要的朋友或者同学,说不定大神成长之路有博哥的奠基石... QQ技术互动交流群:ESP8266&3 ...

  2. 【阿里云IoT+YF3300】7.物联网设备表达式运算

    很多时候从设备采集的数据并不能直接使用,还需要进行处理一下.如果采用脚本处理,有点太复杂了,而采用表达式运算,则很方便地解决了此类问题. 一.  设备连接 运行环境搭建:Win7系统请下载相关的设备驱 ...

  3. 百万年薪python之路 -- 函数初始练习

    1.整理函数相关知识点 2.写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者. def func(lst): lst = lst[1::2] return l ...

  4. hdfs 文件系统命令操作

    hdfs 文件系统命令操作 [1]hdfs dfs -ls [目录]. 显示所有文件 hdfs dfs -ls -h /user/20170214.txt 显示文件时,文件大小以人易读的形式显示 [2 ...

  5. 继承+派生+分类+钻石继承(day20)

    目录 昨日内容 面对对象编程 类 定义类时发生的事情 调用类时发生的事情 init 对象 对象查找类的属性的顺序 对象的绑定方法 python中万物皆对象 今日内容 继承 什么是继承 为什么要继承 如 ...

  6. .Net Core实现健康检查

    ASP.NET Core 提供运行状况检查中间件和库,以用于报告应用基础结构组件的运行状况. 运行状况检查由应用程序作为 HTTP 终结点公开. 可以为各种实时监视方案配置运行状况检查终结点: 运行状 ...

  7. Springboot与任务整合(四)

    一 异步任务 启动类 @MapperScan("com.topcheer.*.*.dao") @SpringBootApplication @EnableCaching @Enab ...

  8. Python基础-语法知识

    ——编程语言的发展史 机器语言 优点:执行速度够快 缺点:开发效率非常低 汇编语言 优点:执行效率相较于机器语言略低 缺点:开发效率相较于机器语言略高 高级语言 C.C++.C#.java.PHP.p ...

  9. [考试反思]1001csp-s模拟测试(b):逃离

    如你所见,b组题,除了NC乱入直奔T2抢了我一个首杀以外A层学过FFT的人都没有参加. 竞争压力很小,题又简单,所以就造就了6个AK. 然而并不计入总分,我仍然稳在第二机房. T1lyl16分钟切掉我 ...

  10. 手把手带你实战下Spring的七种事务传播行为

    目录 本文目录 一.什么是事务传播行为? 二.事务的7种传播行为 三.7种传播行为实战 本文介绍Spring的七种事务传播行为并通过代码演示下. 本文目录 一.什么是事务传播行为? 事务传播行为(pr ...