什麼是go.rich
官網: https://github.com/GeertJohan/go.rice
go.rice是一個go軟件包,可以很方便的處理html、js、css、圖像、模版、配置文件等靜態資源文件,在開發調試過程中,可以直接從磁盤加載所需的文件,生成可執行程序後,在不修改源代碼的情況下,將資源文件添加到可執行程序中。
總結: go.rice是一個golang 靜態資源嵌入工具包。go.rice 支持打包靜態文件到 go 文件中。從使用角度,go.rice 其實是更便捷的靜態文件操作庫。
功能:
-
找到資源文件正確的絕對路徑。比如你在home目錄執行你的二進制程序,程序依賴一個html-fles的文件夾(包含html等資源),但是html-files在中$GOPATH/src/yourApplication/html-files中,你的程序只是調用rice.FindBox(“html-files”)就好,go.rice將查找到該目錄的正確路徑(相對於yourApplication的位置)。
-
**將資源文件嵌入到二進制程序,不再從文件系統加載資源文件,這將創建一個“獨立”可執行文件,減少對文件系統的依賴。**資源文件可以在編譯你的源代碼時可以將資源文件轉換成go源文件嵌入,也可以在源碼編譯成二進制後追加,你的程序裏都能通過rice.FindBox找到資源。
如何使用
注意:調用FindBox()或MustFindBox()時參數必須要使用字符串,例如FindBox(“example”),不能使用字符串常量或變量,否則將報錯。MustFindBox和FindBox功能一樣,只不過MustFindBox如果出錯會直接panic。
作爲源碼嵌入
rice embed-go
go build
執行 rice embed-go後,會在當前目錄生成一個rice-box.go的go源文件,這個源文件包含所有資源文件,通過go build再將其編譯成二進制,生成的go源文件會變大,會減慢編譯速度並需要更多內存來進行編譯。
go.rice 把一個目錄認爲是一個 rice.Box 操作:
import (
"fmt"
"html/template"
"github.com/GeertJohan/go.rice"
)
func main() {
// 這裏寫相對於的執行文件的地址
box, err := rice.FindBox("theme/default")
if err != nil {
println(err.Error())
return
}
// 從目錄 Box 讀取文件
str, err := box.String("post.html")
if err != nil {
println(err.Error())
return
}
t, err := template.New("tpl").Parse(str)
fmt.Println(t, err)
}
go.rice 的打包命令是 rice。用起來非常直接:在有使用 go.rice 操作的 go 代碼目錄,直接執行 rice embed-go:
rice 命令
go.rice 的打包命令是 rice。用起來非常直接:在有使用 go.rice 操作的 go 代碼目錄,直接執行 rice embed-go:
rice embed-go
rice -i "github.com/xxx/xyz" embed-go // -i 處理指定包裏的 go.rice 操作
它就會生成當前包名下的、嵌入了文件的代碼 rice-box.go。但是,它不遞歸處理 import。他會分析當前目錄下的 go 代碼中 go.rice 的使用,找到對應需要嵌入的文件夾。但是子目錄下的和 import 的裏面的 go.rice 使用不會分析,需要你手動 cd 過去或者 -i 指定要處理的包執行命令。這點來說非常的不友好。
資源嵌入:追加 rice append
# go run github.com/GeertJohan/go.rice/rice --help
Usage:
rice [OPTIONS] <command>
Application Options:
--memprofile= Write memory profile to this file
--cpuprofile= Write cpu profile to this file
-v, --verbose Show verbose debug information
-i, --import-path= Import path(s) to use. Using PWD when left empty. Specify multiple times for more
import paths to append
Help Options:
-h, --help Show this help message
Available commands:
append
clean
embed-go
embed-syso
rice append:將資源作爲zip文件附加到可執行文件中,此方法更改已生成的可執行文件。它將資源作爲zip文件附加到二進制文件中。 它使編譯速度更快。使用append方法可以很好地向可執行二進制文件添加大型assets 。
附加的缺點是它沒有提供工作查找方法(a working Seek method)。
makefile 中使用如下:
taigu: $(BUILD_DEPS)
@echo $(GOFLAGS)
rm -f taigu
go build $(GOFLAGS) -o taigu ./cmd/taigu
go run github.com/GeertJohan/go.rice/rice append --exec taigu -i ./build
.PHONY: taigu
BINS+=taigu
我們可以使用-i 參數添加一個路徑,它會在-i 添加的路徑下go文件中找,rice.FindBox() or rice.MustFindBox()函數調用。如果目錄下,沒有該函數調用,會報如下信息:
go run github.com/GeertJohan/go.rice/rice append --exec taigu -i ./build
no calls to rice.FindBox() or rice.MustFindBox() found in import path `./build`