GO MODULE 包管理

本文介绍golang包管理工具。在golang v1.11版本之前使用gopath进行管理,但在不同项目对同一包不同版本依赖时会造成问题。golang v1.11之后的版本引入了go module进行包管理。

GOPATH

在1.11版本之前,golang是通过GOPATH这个环境变量来管理包依赖(包括第三方包和自己工程中的子包)。同时使用go get命令下载的包都会被放在GOPATH指定的目录下面。它的固定格式如下:

$GOPATH
  bin/                       # Directory where executable binaries are stored
  src/                       # Directory where Go source files of the dependent packages are stored
    github.com/google/go-cmp/
      ...
  pkg/                       # Directory where compiled Go object files are stored
    ...

所有的项目代码,都会放在src目前下面。如果项目代码被放在了其它位置,项目在编译环节会报错。

GO MODULE

在1.11版本之后,引入了GO MODULE。它的主要作用有两个,1是包版本控制(versioning),项目可以指定依赖第三方包的版本号;2是工程代码的位置不再局限在GOPATH目录下(package distribution)。

对项目进行构建时go module 会自动安装 package,它的原则是先拉取最新的 release tag,若无 tag 则拉取最新的 commit

可以使用命令go list -m -u all来检查可以升级的 package,使用go get -u need-upgrade-package升级后会将新的依赖版本更新到 go.mod * 也可以使用go get -u升级所有依赖。

GO111MODULE环境变量

Go.mod文件

示例

module learn

go 1.14

require github.com/pborman/uuid v1.2.1

以上示例比较简单

一般来讲,go.mod 提供了 modulerequirereplace exclude 四个命令:

  • module 语句指定包的名字(路径);
  • require 语句指定的依赖项模块;
  • replace 语句可以替换依赖项模块;
  • exclude 语句可以忽略依赖项模块。

组成部分

  • Module import path.
  • The version of go with which the module is created
  • Dependency requirements of the module for a successful build. It defines both project’s dependencies requirement and also locks them to their correct version.

 分别对应示例中的每一行

依赖分类

  • Direct -A direct dependency is a dependency which the module directly imports.
  • Indirect – It is the dependency that is imported by the module’s direct dependencies. Also, any dependency that is mentioned in the go.mod file but not imported in any of the source files of the module is also treated as an indirect dependency.

Go mod命令

命令

作用

go mod download

下载依赖包到本地(默认为 GOPATH/pkg/mod 目录)

go mod edit

编辑 go.mod 文件

go mod graph

打印模块依赖图

go mod init

初始化当前文件夹,创建 go.mod 文件

go mod tidy

增加缺少的包,删除无用的包

go mod vendor

将依赖复制到 vendor 目录下

go mod verify

校验依赖

go mod why

解释为什么需要依赖

go.sum文件

直接或间接依赖库的校验和,它的主要作用是在编译过程中检查是否有依赖的包发生了版本的变化。因此go.mod和go.sum文件都应该被git仓库管理起来。

参考文献

  1. Go Modules: an Alternative to GOPATH for Package Distribution | Better Tomorrow with Computer Science
  2. Understanding go.sum and go.mod file in Go (Golang) - Welcome To Golang By Example
  3. Go语言go mod包依赖管理工具使用详解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值