golang 第三方包(官方推行使用依赖包管理工具dep)
对于golang初学者来说,go语言不像java有maven管理那么方便。依赖包的管理无从下手,往往遇到包冲突后解决问题束手无策。从网上随意找一些第三方的工具包使用,使用过程感觉就是一团乱,用起来各种不方便。官方为了golang语言更好的发展,推出官方依赖管理工具dep。dep是一个原型依赖管理工具,需要在Go 1.7及更高的版本中使用。而且dep在新版本中发展也相对比较成熟,使用简单。
安装
go get -u github.com/golang/dep/cmd/dep
使用
$GOPATH/src/项目
首先初始化:
dep init
项目目录下出现了两个文件(Gopkg.lock、Gopkg.toml)和一个目录(vendor)。
接下来看下Gopkg.lock、Gopkg.toml文件内容:
$ cat Gopkg.lock
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "ab4fef131ee828e96ba67d31a7d690bd5f2f42040c6766b1b12fe856f87e0ff7"
solver-name = "gps-cdcl"
solver-version = 1
$ cat Gopkg.toml
# Gopkg.toml example
#
# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
# for detailed Gopkg.toml documentation.
#
# required = ["github.com/user/thing/cmd/thing"]
# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
#
# [[constraint]]
# name = "github.com/user/project"
# version = "1.0.0"
#
# [[constraint]]
# name = "github.com/user/project2"
# branch = "dev"
# source = "github.com/myfork/project2"
#
# [[override]]
# name = "github.com/x/y"
# version = "2.4.0"
通过一个例子来看具体使用:在项目的main文件下
package main
import (
"github.com/astaxie/beego"
"github.com/bitly/go-simplejson"
"runtime"
)
func main() {
maxCPU := runtime.NumCPU()
runtime.GOMAXPROCS(maxCPU)
strJson := `{"announcer": {"nickname": "时间简史", "kind": "user", "created_at": 1494904539000, "updated_at": 1494983507000, "track_id": 38088960}}`
mapJson,_:=simplejson.NewJson([]byte(strJson))
println(mapJson)
beego.Run()
}
上面已经dep init初始化后,
执行:dep ensure包依赖下载集中管理:
补充:如果遇到版本依赖可执行类似语句:dep ensure -add github.com/bitly/go-simplejson@=0.4.3
再来看下Gopkg.lock、Gopkg.toml文件变化:
$ vim Gopkg.toml
[[constraint]]
name = "github.com/astaxie/beego"
version = "1.8.3"
[[constraint]]
name = "github.com/bitly/go-simplejson"
version = "0.5.0"
$ vim Gopkg.lock
[[projects]]
name = "github.com/astaxie/beego"
packages = [".","config","context","context/param","grace","logs","session","toolbox","utils"]
revision = "cab8458c1c4a5a3b4bf5192922be620e6dede15b"
version = "v1.8.3"
[[projects]]
name = "github.com/bitly/go-simplejson"
packages = ["."]
revision = "aabad6e819789e569bd6aabf444c935aa9ba1e44"
version = "v0.5.0"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "dc040fb12390d61768be6388ad2935bdd7f9cc93d4b1fdda421a284058277c80"
solver-name = "gps-cdcl"
solver-version = 1
在项目下可以看到vendor目录,已经把依赖包集中管理。后续可以直接做交叉编译,不必担心包管理问题。
小结:
dep的依赖包每一次都是拉取新的还是优先使用本地cache呢?可以肯定的是dep也是有本地缓存的,可以打开$GOPATH/pkg/dep/看看,是不是存在呢!
更多内容关注每日编程,每天进步一点。
,免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com