Go语言包管理工具dep的安装与使用

2019-11-10 11:43:02王冬梅

什么是dep?

dep和go,在一定程度上相当于maven之于Java,composer之于PHP,dep是go语言官方的一个包管理工具。

相比较go get而言,dep可以直接给引入的第三方包一个专门的目录,并且可以专门制定一个配置文件,控制go项目所引入的包,版本以及其他依赖关系。

dep这个项目放在golang官方的github中:https://github.com/golang/dep

官方对于dep的解释是:dep is the official experiment, but not yet the official tool. 也就是说,dep目前还处于试验阶段,还并没有成为一个官方意义上的工具。毕竟go语言还很年轻,但是这也充分的证明了go语言的生态圈十分丰富。

安装

安装dep工具的方式有很多种,如果是mac电脑的话,只需要如下命令:

brew install dep

对于Linux和类Unix系统而言,我们还可以使用如下方式安装dep:

curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh

或者直接使用源码安装。

而对于windows电脑,可能会相对来说麻烦些,我们可以直接使用源码编译安装或者直接使用go get命令安装:

go get -u github.com/golang/dep/cmd/dep

待安装完成之后,将dep.exe放在环境变量就可以使用了。

使用

接下来我们来看一下dep的使用方式。

当安装好dep之后,我们在命令行中,输入dep就可以看到有关dep的命令了。

Dep is a tool for managing dependencies for Go projects

Usage: "dep [command]"

Commands:

 init Set up a new Go project, or migrate an existing one
 status Report the status of the project's dependencies
 ensure Ensure a dependency is safely vendored in the project
 version Show the dep version information

Examples:
 dep init  set up a new project
 dep ensure  install the project's dependencies
 dep ensure -update  update the locked versions of all dependencies
 dep ensure -add github.com/pkg/errors add a dependency to the project

Use "dep help [command]" for more information about a command.

我们可以看出来,dep一般进场会使用3个命令:

init-用来初始化项目

status-用来查看当前项目的依赖包的状态

ensure-用来同步包的配置文件和引入的包

下面我们正式使用dep来创建一个项目。首先建立一个项目路径,这里我们将项目路径叫做depProject。然后在项目路径中建立src源代码目录。在src中建立一个存放dep文件和项目主文件的目录,我们暂且可以叫做depmain,并建立一个go文件。

这样我们的目录结构如下:

depProject
    |----src
          |----depmain
                  |-----main.go