有的时候,需要将资源文件,类似java的resource一样打包进二进制文件,在执行的时候就不需要关心路径不对而找不到的问题
本帖使用 go-bindata 打包
工程目录结构
XXXX
├── resources
│ ├── core-site.xml
│ └── hdfs-site.xml
├── hadoopconf
│ ├── hadoopconf.go
│ ├── hadoopconf_test.go
│ ├── myres.go
首先安装此包
go get -u github.com/jteeuwen/go-bindata/... # golang
go-bindata #执行此命令验证安装成功与否
#如果命令执行失败,则
echo $GOPATH/bin #查看gopath/bin目录是否有go-bindata可执行文件
cp $GOPATH/bin/go-bindata /bin
新建一个 resource 文件夹,放置需要打包的文件,以core-site.xml为例。执行
go-bindata -o=myres.go resource
打开myres.go文件,会发现里面生成许多函数,其中重要的是Asset函数
// Asset loads and returns the asset for the given name.
// It returns an error if the asset could not be found or
// could not be loaded.
func Asset(name string) ([]byte, error) {
cannonicalName := strings.Replace(name, "\\", "/", -1)
if f, ok := _bindata[cannonicalName]; ok {
return f()
}
return nil, fmt.Errorf("Asset %s not found", name)
}
将生成的myres.go移动到和使用的地方同一个包下,代码里就不需要解决导包问题,在使用的地方只需
// 需要使用的地方执行Assert,之后即可解析
pList := propertyList{}
f, err := Asset("resource/core-site.xml")
err = xml.Unmarshal(f, &pList)
编译后的二进制就能读到resource文件下的文件,随处使用,不用关心配置文件找不到
go build -ldflags "-X main.version=1.0.0" xxx
参考文献
https://github.com/jteeuwen/go-bindata
https://c.isme.pub/2019/01/10/go-static/
https://liqiang.io/post/package-static-file-with-golang
https://blog.csdn.net/lampqiu/article/details/48649881
https://blog.csdn.net/idwtwt/article/details/81180460