go-bindata
go bindata
在项目中引用了静态资源时,项目打包后,需要保证包与静态资源的相对目录不变。bindata可以将静态资源生成.go文件,在打包时会嵌入到包中,非常好用。
安装
需要让bindata下载到GOPATH/bin
目录下,在项目外执行命令:
go install github.com/jteeuwen/go-bindata/...@master
生成
go bindata支持以下参数
PS D:\go_workspace\src\test> go-bindata
Missing <input dir>
Usage: D:\g\versions\1.22.8\bin\go-bindata.exe [options] <input directories>
-debug
Do not embed the assets, but provide the embedding API. Contents will still be loaded from disk.
-dev
Similar to debug, but does not emit absolute paths. Expects a rootDir variable to already exist in the generated code's package.
-ignore value
Regex pattern to ignore
-mode uint
Optional file mode override for all files.
-modtime int
Optional modification unix timestamp override for all files.
-nocompress
Assets will *not* be GZIP compressed when this flag is specified.
-nomemcopy
Use a .rodata hack to get rid of unnecessary memcopies. Refer to the documentation to see what implications this carries.
-nometadata
Assets will not preserve size, mode, and modtime info.
-o string
Optional name of the output file to be generated. (default "./bindata.go")
-pkg string
Package name to use in the generated code. (default "main")
-prefix string
Optional path prefix to strip off asset names.
-tags string
Optional set of build tags to include.
-version
Displays version information.
生成.go文件
go-bindata -o=pkg/bindata.go -pkg=pkg template/...
将template/下的静态资源生成到pkg/bindata.go,文件的包名为pkg。
如果出现bindata: Failed to stat input path '.go': CreateFile .go
,删除.go ,再修改文件名即可。
PS D:\go_workspace\src\test> go-bindata -o=pkg/bindata.go -pkg=pkg template/...
bindata: Failed to stat input path '.go': CreateFile .go: The system cannot find the file specified.
使用
生成的bindata.go为我们提供了这些方法
// 根据名称加载并返回文件内容
func Asset(name string) ([]byte, error) {}
// 类似于Asset,但在出错时会panic,适用于初始化全局变量
func MustAsset(name string)[]byte{}
// 返回文件的元数据信息
func AssetInfo(name string)(os.FileInfo,error){}
// 返回所有嵌入文件的名称列表
func AssetNames() []string{}
// 返回指定目录下的文件和子目录名称
func AssetDir(name string) ([]string, error){}
// 将单个嵌入的文件恢复到指定目录
func RestoreAsset(dir, name string) error{}
// 递归的将嵌入的文件和目录恢复到指定目录
func RestoreAssets(dir, name string) error{}
使用很简单,如:
temp, err := tools.Asset("data/template/reach_overstock_info.tmpl")
if err != nil {
vars.Logger.Errorf(ctx, "wechat_service.SendReachOverstockMessage tools.Asset err %#v", err)
}
src := data.Overstocks
tmpl, err := template.New("reach_overstock_info").Parse(string(temp))
小结
go bindata为我们提供了将静态资源嵌入到包里,即将静态资源生成.go文件。