Golang Gin Embed搭配React使用
react #
设置打包路径
修改package.json
文件
"scripts": {
"build": "BUILD_PATH='../go/public' react-scripts build",
},
其中BUILD_PATH
为打包输出路径
embed #
设置 embed
//go:embed public
var buildFS embed.FS
//go:embed public/index.html
var indexPage []byte
gin #
路由设置
r.Use(static.Serve("/", common.EmbedFolder(buildFS, "public")))
r.NoRoute(func(c *gin.Context) {
c.Data(http.StatusOK, "text/html; charset=utf-8", indexPage)
})
其中 common 包内容为
package common
import (
"embed"
"io/fs"
"net/http"
"github.com/gin-contrib/static"
)
type embedFileSystem struct {
http.FileSystem
}
func (e embedFileSystem) Exists(prefix string, path string) bool {
_, err := e.Open(path)
if err != nil {
return false
}
return true
}
func EmbedFolder(fsEmbed embed.FS, targetPath string) static.ServeFileSystem {
efs, err := fs.Sub(fsEmbed, targetPath)
if err != nil {
panic(err)
}
return embedFileSystem{
FileSystem: http.FS(efs),
}
}