第一章 Go 語言打包靜態文件以及如何與Gin一起使用Go-bindata
前幾天,開始學習用 Go 語言開發一個內部項目來幫助解決測試環境中的一些不便利的問題。因為開發的小項目中存在一些靜態文件和配置文件,第一打包的時候發現並沒有將靜態文件打包進入可執行文件,這樣在發布的時候又需要手動拷貝一下靜態文件,這樣就很麻煩了。在一些網上資料上發現了 go-bindata。這樣我還是只分發一個文件就可以了,不過打包出來的文件會大一點。
his package converts any file into managable Go source code. Useful for embedding binary data into a go program. The file data is optionally gzip compressed before being converted to a raw byte slice.
It comes with a command line tool in the go-bindata sub directory. This tool offers a set of command line options, used to customize the output being generated.
go-bindata 將任何文件封裝在一個 Go 語言的 Source Code 裡面,文件數據在轉換為原始字節時可以選擇使用 gzip 壓縮,同時提供了統一的接口,幫助獲取原始的文件數據
go get -u github.com/jteeuwen/go-bindata/...
使用 go-bindata --help 可以查看具體的使用方式
go-bindata --helpUsage: go-bindata [options] <input directories> -debug Do not embed the assets, but provide the embedding API. Contents will still be loaded from disk. -dev Similar to debug, but does not emit absolute paths. Expects a rootDir variable to already exist in the generated code&34;./bindata.go&34;main&34;template/css/app.ee8ee5dd.css&34;template/favicon.ico&34;template/fonts/element-icons.535877f5.woff&34;template/img/Avatar.41ba4b7a.jpg&34;template/index.html&34;template/js/app.40872d4f.js&34;conf/app.ini&34;conf/app.ini&34;template/index.html&34;/css&34;./template/css&34;/fonts&34;./template/fonts&34;/img&34;./template/img&34;/js&34;./template/js&34;/favicon.ico&34;./template/favicon.ico&34;/&34;index.html&34;template/css&34;index.html&34;template/js&34;index.html&34;template/fonts&34;index.html&34;template/img&34;index.html&34;template&34;index.html&34;/css&34;/fonts&34;/img&34;/js&34;/favicon.ico&34;/&34;template/index.html&34;Accept&34;text/html&34;template&34;index.html&34;template&34;template/css/app.ee8ee5dd.css&34;index.html" 意思為如何查詢不到則默認返回 index.html 文件,因為配置了前綴,這裡返回的應該是 template/index.html
在日常開發中,沒有必要沒改動一下靜態文件就要重新生成 asset.go,此時我們可以使用 -debug 模式生成 asset.go 文件,這樣訪問文件還是使用的真實文件
go-bindata-assetfs -debug -o=asset/asset.go -pkg=asset template/... conf/...
通過 go-bindata 和 go-bindata-assetfs 的使用,我們可以將靜態文件進行打包,最終提供單個分發文件,簡化部署和使用。
提一下 go-bindata 項目之前的一些周折。
如果你搜索 go-bindata 的文章,會發現早期的文章指向的項目地址往往是:https://github.com/jteeuwen/go-bindata 。那是最早的項目地址,jteeuwen 是原作者 Jim Teeuwen 的帳號。
但不知道什麼時候,因為什麼原因,原作者把項目關閉了,連 jteeuwen 這個帳號都刪除了。(從現存線索推斷,大約是 2018 年的事)
現在原地址也有一個項目,但已經 不是原項目 ,也 不再維護 了。那是有人發現 go-bindata 刪除後,為了讓依賴它的項目不會報錯,重新註冊了 jteeuwen 這個帳號,重新 fork 了這個項目 (真正原項目已刪,是從一個 fork 那裡 fork 的) 。因為初衷是讓某個項目能夠繼續工作(據說是已經沒法修改的私人項目,所以也不能指向新的地址),並沒有打算繼續維護,也不想冒充原項目,所以這個項目設為了 archived (read only)。詳情可以參考以下討論:
https://github.com/jteeuwen/go-bindata/issues/5
https://github.com/jteeuwen/discussions/issues
現在給出的項目地址,不確定跟原作者有沒有關係——估計是沒有的。那它不過是眾多 fork 的其中一個。選它僅僅因為它最活躍、關注人數最多。這可能跟它掛在了同名 organization 下有一定關係,也可能裡面有某個大牛。
理由並不重要,只需要知道它最活躍是一個共識,就夠了。
題外這段引用 https://jaycechant.info/2020/go-bindata-golang-static-resources-embedding/