bindata

command
v0.0.0-...-156932d Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 14, 2024 License: Apache-2.0 Imports: 8 Imported by: 0

README

bindata 轻松实现对静态资源的二进制打包

注意:不建议继续使用bindata来打包资源文件到go程序了,建议使用//go:embed resource的方式来代替。

go似乎有计划要支持对静态资源文件的打包,但是目前最新go发行版仍然不支持。

如果想实现类似功能,就只能借助一些第三方的库,比如go-rice、go-bindata等等,这些三方库用起来也没那么简单方便。

这里写了个简单的demo,后续有类似需求可以考虑这么实现,后面go官方支持了再考虑切换实现方式,没必要用那些过度设计的三方库了。

1. 演示下如何使用bindata来将文件或者整个目录转换成go文件存储

# 构建bindata工具
go build -v

# 将整个static目录压缩后存储到一个gobin/static.go文件
./bindata -input static/ -output gobin/static.go

2. 演示下如何在代码中使用上述生成的go文件来还原回以前的文件内容

  • 代码中其他地方直接通过 gobin.StaticGo 来引用上述内容
  • 可以通过 compress.UnTar(dst, bytes.NewBuffer(gobin.StaticGo))解压到本地文件系统,然后就能当做本地文件来使用

利用这种转换,开发者可以很方便地将一些依赖本地配置文件、静态资源文件的项目做下优化。 可以轻松实现go get安装,您可以选择在程序首次执行时将打包好的静态资源文件释放到本地文件系统中去。

假定存在如下静态资源目录static,其下包含了多个文件,现在我想将其全部打包到一个go文件中。

tree .
$ .
  |- static
     |- file1.txt
     |- file2.txt
     |- file3.txt

运行 go build -v bindata 编译我们之前写的工具,然后运行 bindata -input=path/to/static -output=goin/static.go -gopkg=gobin

$ tree .
.
|- static
   |- file1.txt
   |- file2.txt
   |- file3.txt
   
|- gobin
   |- static.go

我们看到当前目录下多生成了一个gobin目录,其下多了个go文件static.go,查看下文件内容:

$ cat gobin/static.go
   
package gobin
   
var StaticGo = []uint8{
   31,139,8,0,0,0,0,0,0,255,236,213,193,10,194,48,12,128,225,158,125,138,62,129,36,77,219,60,79,15,171,171,136,7,91,65,124,122,105,39,13   1,29,244,182,58,89,190,75,24,140,209,145,253,44,166,203,128,199,242,40,106,61,0,0,222,218,54,217,187,54,193,76,215,13,178,66,98,240,2   36,25,136,21,32,121,100,165,97,197,51,205,238,185,132,155,2,120,142,225,122,58,167,225,211,125,185,132,24,191,60,231,253,42,243,252,1   9,101,76,89,167,172,235,119,160,241,240,235,227,136,206,234,222,205,150,250,183,78,250,239,104,209,191,145,254,247,166,238,157,182,21   2,191,155,254,255,134,164,255,30,22,253,147,244,47,132,16,123,241,10,0,0,255,255,106,242,211,179,0,16,0,0,
}

哈哈,现在看到static目录及其下的文件已经被完整打包到一个go文件中了,且通过导出变量进行了导出,后续使用的时候,可以先将其还原到本地文> 件系统,以前已经写好的代码不用做任何修改,怎么还原到本地文件系统呢,并使用呢?

// 在你需要引用这些静态资源的package中释放这些静态资源文件到本地文件系统
func init() {
    compress.UnTar(path/to/static, bytes.NewBuffer(gobin.StaticGo))
   
    val := config.Read(path/to/static/file1.go, "section", "property", defaultValue)
    ...
}

超级简单!Try it as you need!

Documentation

The Go Gopher

There is no documentation for this package.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL