go1.16新增的embed.FS - Wed, Apr 7, 2021
go1.16新增的embed.FS
1. 概述
go1.16中加入了内置的bindata,比原先的bindata包小了好多。
2. bindata的使用
将前端编译出来的文件打包成go
yarn build:prod
go-bindata-assetfs -pkg middlewares -nocompress=false dist/...
将前端go代码插入到http服务中
// Dashboard default url host:port or host:port/dashboard or host:port/dashboard/
func Dashboard(handler http.Handler) http.Handler {
// return http.FileServer(assetFS())
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/dashboard" || r.URL.Path == "/" {
http.Redirect(w, r, "/dashboard/", http.StatusFound)
return
}
// Serving ./dashboard/
if strings.Index(r.URL.Path, "/dashboard/") == 0 {
http.StripPrefix("/dashboard/", http.FileServer(assetFS())).ServeHTTP(w, r)
return
}
handler.ServeHTTP(w, r)
})
}
bindata.go是用字符串存储二进制文件,会比原有的文件还要大。插入go编译生成的可执行文件中,会使执行文件显著增大。
3. embed.FS
目录结构
ui
├── dist
│ ├── favicon.ico
│ ├── index.html
│ └── static
│ ├── css
│ │ ├── app.bbbfe7a4.css
│ │ ├── chunk-9305baa0.2bcd27a6.css
│ ├── fonts
│ │ ├── element-icons.535877f5.woff
│ ├── img
│ │ ├── 404.a57b6f31.png
│ │ ├── 404_cloud.0f4bc32b.png
│ ├── js
│ │ ├── app.07035864.js
│ │ ├── chunk-0999b2fb.e2e2e3d4.js
│ └── swagger
│ └── swagger.yaml
└── ui.go
ui.go
package ui
import "embed"
//go:embed dist
var WebUI embed.FS
ui.go会把文件夹打包到WebUI变量中,注意WebUI是包含dist文件夹,后续操作需要去掉文件夹。
将前端go代码插入到http服务中。与bindata相比基本变化不大,多了Sub文件夹dist的操作。
// UI default url host:port or host:port/ui or host:port/ui/
func UI(handler http.Handler) http.Handler {
// return http.FileServer(assetFS())
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/dashboard" || r.URL.Path == "/" {
http.Redirect(w, r, "/dashboard/", http.StatusFound)
return
}
// Serving ./dashboard/
if strings.Index(r.URL.Path, "/dashboard/") == 0 {
fsys, err := fs.Sub(ui.WebUI, "dist")
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
http.StripPrefix("/dashboard/", http.FileServer(http.FS(fsys))).ServeHTTP(w, r)
return
}
handler.ServeHTTP(w, r)
})
}