go-bindata-assetfs 实现单文件编译
2021年05月06日 技术分享>后端技术 golang本站文章除注明转载外,均为原创文章。如需转载请注明出处:
https://kwokronny.top/202105/golang-bindata-static/

在开发 yoz-comment 评论系统中为了方便部署,在部署的过程中实现单文件无依赖发布,就在想是否可以将静态文件一同编译进应用中;在搜索后找到了 go-bindata ,为了很方便于 web 应用,最后选择以 go-bindata 为依赖的 go-bindata-assetfs。
话不多说,直接尝试
安装
1 |
|
go-bindata 是一个工具,将静态文件生成为 go 代码,文件以 byte 数组的形式存在。
go-bindata-assetfs 是文件系统接口的实现,从生成的 go 文件中拿文件数据。
使用
1 |
|
无标签传参指的是 需转换的文件,
-o
指转换后导出文件位置,默认为./bindata.go
-pkg
指导出的包名,默认为main
-ignore [regexp value]
正则文本忽略匹配文件
如:-ignore "\\.DS_Store|package.json"
-debug
指调试模式,生成的包并不会嵌入文件,而是直接硬盘读取文件,方便前端热更新调试。基础示例
1 |
|
- Gin 示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24package main
import (
"project/statics"
"net/http"
assetfs "github.com/elazarl/go-bindata-assetfs"
"github.com/gin-gonic/gin"
)
func main() {
engine := gin.Default()
// 通过 go-bindata-assetfs 提供的函数将静态资源
staticFS := assetfs.AssetFS{
Asset: statics.Asset,
AssetDir: statics.AssetDir,
AssetInfo: statics.AssetInfo,
Prefix: "static_data", // 访问路由index.html => 指向文件 static_data/index.html
Fallback: "index.html",
}
engine.StaticFS("/", &staticFS) //配置静态资源文件路由
engine.Run(":8080")
}
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!


