靜態資源嵌入二進制文件中,可以方便我們的軟件分發(只需要簡單的二進制文件就可以了),目前大部分golang 的
web 應用都是使用類似的方法。
以下是收集到的一些常見方案
github.com/go-bindata/go-bindata
go-bindata 的使用方法是先生成代碼,然后使用提供的api引用
使用流程
- 生成資源代碼
go-bindata data/
- 通用引用
data, err := Asset("pub/style/foo.css")
if err != nil {
// Asset was not found.
}
// use asset data
- http server 引用
go-bindata -fs -prefix "static/" static/
mux := http.NewServeMux()
mux.Handle("/static", http.FileServer(AssetFile()))
http.ListenAndServe(":8080", mux)
github.com/elazarl/go-bindata-assetfs
go-bindata-assetfs 是go-bindata的包裝,也需要生成代碼,但是使用更加簡單,便捷
使用流程
- 生成代碼
go-bindata-assetfs data/
- 資源引用
http.Handle("/", http.FileServer(assetFS()))
github.com/rakyll/statik
也是需要生成代碼的
- 生成代碼
statik -src=/path/to/your/project/public
- 代碼引用
import (
"github.com/rakyll/statik/fs"
_ "./statik" // TODO: Replace with the absolute import path
)
// ...
statikFS, err := fs.New()
if err != nil {
log.Fatal(err)
}
// Serve the contents over HTTP.
http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(statikFS)))
http.ListenAndServe(":8080", nil)
github.com/gobuffalo/packr
packr 在使用上就更方便的,導入也很清晰
- 生成代碼
packr 在開發階段是不需要生成代碼的,我們可以像普通文件的方法使用,當需要嵌入的時候通過工具生成
就可以自動嵌入了,使用靈活
package main
import (
"fmt"
"github.com/gobuffalo/packr"
)
func main() {
box := packr.NewBox("./templates")
s, err := box.FindString("admin/index.html")
if err != nil {
log.Fatal(err)
}
fmt.Println(s)
}
- 構建嵌入
packr build
github.com/GeertJohan/go.rice
go.rice 與packr 的使用類似,開發階段自己查找,編譯構建的時候嵌入
- 使用
box := rice.MustFindBox("cssfiles")
cssFileServer := http.StripPrefix("/css/", http.FileServer(box.HTTPBox()))
http.Handle("/css/", cssFileServer)
http.ListenAndServe(":8080", nil)
- 編譯構建
rice embed-go
go build
說明
以上就是自己目前發現的幾個golang比較方便的靜態資源嵌入包,后續發現新的再添加完善
參考資料
https://github.com/go-bindata/go-bindata
https://github.com/elazarl/go-bindata-assetfs
https://github.com/rakyll/statik
https://github.com/gobuffalo/packr
https://github.com/GeertJohan/go.rice