react

设置打包路径 修改package.json文件

1  "scripts": {
2    "build": "BUILD_PATH='../go/public' react-scripts build",
3  },

其中BUILD_PATH为打包输出路径

embed

设置 embed

1//go:embed public
2var buildFS embed.FS
3
4//go:embed public/index.html
5var indexPage []byte

gin

路由设置

1r.Use(static.Serve("/", common.EmbedFolder(buildFS, "public")))
2r.NoRoute(func(c *gin.Context) {
3    c.Data(http.StatusOK, "text/html; charset=utf-8", indexPage)
4})

其中 common 包内容为

 1package common
 2
 3import (
 4	"embed"
 5	"io/fs"
 6	"net/http"
 7	"github.com/gin-contrib/static"
 8)
 9
10type embedFileSystem struct {
11	http.FileSystem
12}
13
14func (e embedFileSystem) Exists(prefix string, path string) bool {
15	_, err := e.Open(path)
16	if err != nil {
17		return false
18	}
19	return true
20}
21
22func EmbedFolder(fsEmbed embed.FS, targetPath string) static.ServeFileSystem {
23	efs, err := fs.Sub(fsEmbed, targetPath)
24	if err != nil {
25		panic(err)
26	}
27	return embedFileSystem{
28		FileSystem: http.FS(efs),
29	}
30}

部分参考自 https://github.com/songquanpeng/gin-template 代码