- 需求
- 改进思路
- a). Gin文档 静态资源嵌入 方案
- b). Gin 自带方法
- 代码
- 效果
- c). 改进
- 1. 自带http库做法
- 2. 查看gin staticfs源码
- 3. 最终解决方案
用Gin开发Web服务时, 编译生成的应用可能如下, 需提供static目录和web-app.exe给用户
如果将static文件夹到生成的exe中,分发单个EXE文件给用户使用,更加方便
# 改进前 ├── static │ └── js/jquery.min.js │ ├── favicon.ico │ ├── index.html ├── web-app.exe # 改进后 ├── web-app.exe (static内嵌进exe里)改进思路 a). Gin文档 静态资源嵌入 方案
b). Gin 自带方法 代码参考: https://learnku.com/docs/gin-gonic/1.7/examples-bind-single-binary-with-template/11403
需要使用额外工具go-assets,操作有点复杂,因此不考虑
package main
import (
"embed"
"net/http"
"github.com/gin-gonic/gin"
)
//go:embed static
r.Any("/static/*filepath", func(c *gin.Context) {
staticServer := http.FileServer(http.FS(fs))
staticServer.ServeHTTP(c.Writer, c.Request)
})
r.Run("localhost:80")
}
查看效果达到预期



