功能說明
go.rice是一個go軟件包,可以很方便的處理html、js、css、圖像、模版、配置文件等靜態資源文件,在開發調試過程中,可以直接從磁盤加載所需的文件,生成可執行程序後,在不修改源代碼的情況下,將資源文件添加到可執行程序中。
作用
- 找到資源文件正確的絕對路徑。比如你在home目錄執行你的二進制程序,程序依賴一個html-fles的文件夾(包含html等資源),但是html-files在中$GOPATH/src/yourApplication/html-files中,你的程序只是調用rice.FindBox(“html-files”)就好,go.rice將查找到該目錄的正確路徑(相對於yourApplication的位置)。
- 將資源文件嵌入到二進制程序,不再從文件系統加載資源文件,這將創建一個“獨立”可執行文件,減少對文件系統的依賴。資源文件可以在編譯你的源代碼時可以將資源文件轉換成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.go
的go
源文件,這個源文件包含所有資源文件,通過go build
再將其編譯成二進制,生成的go
源文件會變大,會減慢編譯速度並需要更多內存來進行編譯。
資源嵌入方式二:追加
go build -o example
rice append --exec example
注意事項
調用FindBox()
或MustFindBox()
時參數必須要使用字符串,例如FindBox(“example”),不能使用字符串常量或變量,否則將報錯。MustFindBox
和FindBox
功能一樣,只不過MustFindBox
如果出錯會直接panic
。