幾個golang 靜態資源嵌入包

靜態資源嵌入二進制文件中,能夠方便咱們的軟件分發(只須要簡單的二進制文件就能夠了),目前大部分golang 的
web 應用都是使用相似的方法。
如下是收集到的一些常見方案css

github.com/go-bindata/go-bindata

go-bindata 的使用方法是先生成代碼,而後使用提供的api引用
使用流程html

  • 生成資源代碼
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的包裝,也須要生成代碼,可是使用更加簡單,便捷
使用流程git

  • 生成代碼
go-bindata-assetfs data/...
  • 資源引用
http.Handle("/", http.FileServer(assetFS()))

github.com/rakyll/statik

也是須要生成代碼的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)

github.com/gobuffalo/packr

packr 在使用上就更方便的,導入也很清晰golang

  • 生成代碼
    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 的使用相似,開發階段本身查找,編譯構建的時候嵌入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工具

相關文章
相關標籤/搜索