Go的包管理工具(dep)

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

如果你写的项目需要依赖其他的包的话,就需要用到dep了,官方对于dep的解释是:

dep is the official experiment, but not yet the official tool.

也就是说,dep目前还处于试  验阶段,还并没有成为一个官方意义上的工具。

安装dep

安装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

待安装完成之后,在你工作空间的src目录下创建一个项目
我创建的是deptest

image.png

然后进到该目录下,输入 dep

image.png

看你的输出结果和我的一样吗?如果不一样的话就把你的工作空间(GOPATH)下的bin目录加到PATH环境变量里

image.png

然后重启VS Code 接着输入dep,如果能显示和我一样的话就说明您的dep已经准备好了。

PS D:\Go_WorkSpace> 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
  check    Check if imports, Gopkg.toml, and Gopkg.lock are in sync

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常用的命令不多,
是啊,dep常用的就这几个命令

dep init  
设置新的go项目,或迁移现有项目

dep status 
报告项目依赖项的状态

dep ensure 
确保在项目中安全地添加依赖项

dep version 
显示DEP版本信息

dep check 
检查导入、gopkg.toml和gopkg.lock是否同步

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

dep
    |----src
          |----deptest
                  |-----recevie.go
                  |-----send.go

建好之后我们写这两个程序(这两个程序是关于消息队列(RabbitMQ)的)

send.go

package main

import (
    "log"

    "github.com/streadway/amqp"
)

func failOnError(err error, msg string) {
    if err != nil {
        log.Fatalf("%s: %s", msg, err)
    }
}

func main() {
    conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
    failOnError(err, "Failed to connect to RabbitMQ")
    defer conn.Close()

    ch, err := conn.Channel()
    failOnError(err, "Failed to open a channel")
    defer ch.Close()

    q, err := ch.QueueDeclare(
        "hello", // name
        false,   // durable
        false,   // delete when unused
        false,   // exclusive
        false,   // no-wait
        nil,     // arguments
    )
    failOnError(err, "Failed to declare a queue")

    body := "Hello World!"
    err = ch.Publish(
        "",     // exchange
        q.Name, // routing key
        false,  // mandatory
        false,  // immediate
        amqp.Publishing{
            ContentType: "text/plain",
            Body:        []byte(body),
        })
    log.Printf(" [x] Sent %s", body)
    failOnError(err, "Failed to publish a message")
}

recevie.go

package main

import (
    "log"

    "github.com/streadway/amqp"
)

func failOnError(err error, msg string) {
    if err != nil {
        log.Fatalf("%s: %s", msg, err)
    }
}

func main() {
    conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
    failOnError(err, "Failed to connect to RabbitMQ")
    defer conn.Close()

    ch, err := conn.Channel()
    failOnError(err, "Failed to open a channel")
    defer ch.Close()

    q, err := ch.QueueDeclare(
        "hello", // name
        false,   // durable
        false,   // delete when unused
        false,   // exclusive
        false,   // no-wait
        nil,     // arguments
    )
    failOnError(err, "Failed to declare a queue")

    msgs, err := ch.Consume(
        q.Name, // queue
        "",     // consumer
        true,   // auto-ack
        false,  // exclusive
        false,  // no-local
        false,  // no-wait
        nil,    // args
    )
    failOnError(err, "Failed to register a consumer")

    forever := make(chan bool)

    go func() {
        for d := range msgs {
            log.Printf("Received a message: %s", d.Body)
        }
    }()

    log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
    <-forever
}

之后我们在这个目录下运行如下命令:
dep init 

运行完成之后,dep就会为我们自动生成如下文件和目录:

image.png

有点像常规go项目的样子了,不过需要注意的是pkg中存放的go语言引入包的缓存文件,vendor中存放的是真正的引入的包内容。接下来是两个文件,Gopkg.lock和Gopkg.toml。Gopkg.lock文件是自动生成的,而Gopkg.toml文件是我们可以编辑的文件,通过编辑这个文件,并运行dep的命令可以达到引入包的目的:

# 必需包

required = ["github.com/streadway/amqp"]

# 忽略包

#ignored = []没有可以不写

# 项目元数据

#[metadata]

# 约束条件

[[constraint]]

  # name = 

  # 可选:版本

  # version =

  # 分支

  # branch

  # 修订

  # revision

  # 可选:指定来源

  # source = "github.com/gin-gonic/gin"

以上代码是一个示例,我们写好之后运行
dep ensure 
就可以了,我们会看到vendor下多了一些有关此包的依赖和引入。


image.png


我们引入了连接RabbitMQ的包,所以我们现在就可以使用amqp包了。


dep status 


image.png


dep check 

image.png


这样你就可以把这个项目直接发给其他人,其他人也就能运行了。

Last modification:July 7th, 2019 at 11:43 am
如果觉得我的文章对你有用,请随意赞赏