靜態資源嵌入二進制文件中,能夠方便咱們的軟件分發(只須要簡單的二進制文件就能夠了),目前大部分golang 的
web 應用都是使用相似的方法。
如下是收集到的一些常見方案css
go-bindata 的使用方法是先生成代碼,而後使用提供的api引用
使用流程html
go-bindata data/
data, err := Asset("pub/style/foo.css")
if err != nil {
// Asset was not found.
}
// use asset data
go-bindata -fs -prefix "static/" static/
mux := http.NewServeMux()
mux.Handle("/static", http.FileServer(AssetFile()))
http.ListenAndServe(":8080", mux)
go-bindata-assetfs 是go-bindata的包裝,也須要生成代碼,可是使用更加簡單,便捷
使用流程git
go-bindata-assetfs data/
http.Handle("/", http.FileServer(assetFS()))
也是須要生成代碼的github
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)
packr 在使用上就更方便的,導入也很清晰golang
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
go.rice 與packr 的使用相似,開發階段本身查找,編譯構建的時候嵌入web
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比較方便的靜態資源嵌入包,後續發現新的再添加完善api
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工具