【golang库】go.rice

功能说明

go.rice是一个go软件包,可以很方便的处理html、js、css、图像、模版、配置文件等静态资源文件,在开发调试过程中,可以直接从磁盘加载所需的文件,生成可执行程序后,在不修改源代码的情况下,将资源文件添加到可执行程序中。

作用

  1. 找到资源文件正确的绝对路径。比如你在home目录执行你的二进制程序,程序依赖一个html-fles的文件夹(包含html等资源),但是html-files在中$GOPATH/src/yourApplication/html-files中,你的程序只是调用rice.FindBox(“html-files”)就好,go.rice将查找到该目录的正确路径(相对于yourApplication的位置)。
  2. 将资源文件嵌入到二进制程序,不再从文件系统加载资源文件,这将创建一个“独立”可执行文件,减少对文件系统的依赖。资源文件可以在编译你的源代码时可以将资源文件转换成go源文件嵌入,也可以在源码编译成二进制后追加,你的程序里都能通过rice.FindBox找到资源。

安装

go get github.com/GeertJohan/go.rice
go get github.com/GeertJohan/go.rice/rice

使用

Box作为http服务的静态内容文件夹,一个Box相当于一个目录

http.Handle("/", http.FileServer(rice.MustFindBox("http-files").HTTPBox()))
http.ListenAndServe(":8080", nil)

载入一个模版

// find a rice.Box
templateBox, err := rice.FindBox("example-templates")
if err != nil {
	log.Fatal(err)
}
// get file contents as string
templateString, err := templateBox.String("message.tmpl")
if err != nil {
	log.Fatal(err)
}
// parse and execute the template
tmplMessage, err := template.New("message").Parse(templateString)
if err != nil {
	log.Fatal(err)
}
tmplMessage.Execute(os.Stdout, map[string]string{"Message": "Hello, world!"})

资源嵌入方式一:作为源码嵌入

rice embed-go
go build

执行 rice embed-go后,会在当前目录生成一个rice-box.gogo源文件,这个源文件包含所有资源文件,通过go build再将其编译成二进制,生成的go源文件会变大,会减慢编译速度并需要更多内存来进行编译。

资源嵌入方式二:追加

go build -o example
rice append --exec example

注意事项

调用FindBox()MustFindBox()时参数必须要使用字符串,例如FindBox(“example”),不能使用字符串常量或变量,否则将报错。MustFindBoxFindBox功能一样,只不过MustFindBox如果出错会直接panic

发布了24 篇原创文章 · 获赞 0 · 访问量 1808

猜你喜欢

转载自blog.csdn.net/kk3909/article/details/104998370