reactjs - 使用 go:embed 在 golang gin-gonic 中提供静态文件,在重新加载前端 URL 时出现 404 错误
问题描述
我使用gin和 go1.17 构建了一个 go 应用程序。
我go:embed
用来为使用 react 构建的 SPA 应用程序提供静态内容。(尝试https://github.com/gin-contrib/static/issues/19中建议的方法)。我的前端文件位于构建文件夹中
build/index.html
build/asset-manifest.json
build/static/css/**
build/static/js/**
build/manifest.json
//go:embed build/*
var reactStatic embed.FS
type embedFileSystem struct {
http.FileSystem
indexes bool
}
func (e embedFileSystem) Exists(prefix string, path string) bool {
f, err := e.Open(path)
if err != nil {
return false
}
// check if indexing is allowed
s, _ := f.Stat()
if s.IsDir() && !e.indexes {
return false
}
return true
}
func EmbedFolder(fsEmbed embed.FS, targetPath string, index bool) static.ServeFileSystem {
subFS, err := fs.Sub(fsEmbed, targetPath)
if err != nil {
panic(err)
}
return embedFileSystem{
FileSystem: http.FS(subFS),
indexes: index,
}
}
func main() {
router := gin.Default()
fs := EmbedFolder(reactStatic, "build", true)
//Serve frontend static files
router.Use(static.Serve("/", fs))
/* THESE ARE MY STATIC URLs FROM THE REACT APP in FRONTEND */
router.Use(static.Serve("/login", fs))
router.Use(static.Serve("/calendar", fs))
router.NoRoute(func(c *gin.Context) {
c.JSON(404, gin.H{
"code": "PAGE_NOT_FOUND", "message": "Page not found",
})
})
setupBaseRoutes(router, database)
httpServerExitDone := &sync.WaitGroup{}
httpServerExitDone.Add(1)
srv, ln := server.StartServer(router, httpServerExitDone)
log.Printf("Starting Server at %s", ln.Addr().String())
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt)
<-quit
log.Println("Shutdown Server ...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Server Shutdown:", err)
}
log.Println("Server exiting")
}
当应用程序加载并打开页面时http://localhost:8000/
,它会正确打开,我可以导航到http://localhost:8000/calendar
使用 react-router-dom。但是当我重新加载页面时http://localhost:8000/calendar
,我得到 404 错误。
解决方案
推荐阅读
- javascript - 无法从输入字段获取用户输入并将其分配给另一个 div 的 innerHTML
- javascript - 尝试将 lodash 代码转换为 es6 方法;它抛出错误?
- javascript - 如何将 map 函数中的变量放入 Apollo 变异变量中?
- reactjs - 使用 Hashrouter 登录时重定向
- android - SwitchPreference 无法正常工作 - 为什么会这样?
- node.js - 如何发送带参数的 GET 请求
- php - 如何在php中创建删除行按钮
- php - 如何使用 HTML 中的选择框在数据库中搜索特定用户并在表格中显示该信息?
- python - 是否可以使用 pyomo 对最小最大问题进行建模
- python - 使用 Python 获取当前月份的所有日期