英文:
How to handle SPA urls correctly in Golang?
问题
我正在尝试使用echo嵌入和提供我的前端(使用静态导出的nextjs)。我目前正在使用以下代码:
//go:embed all:frontend/out
var FrontendFS embed.FS
func BuildFrontendFS() http.FileSystem {
	build, err := fs.Sub(FrontendFS, "frontend/out")
	if err != nil {
		log.Fatal(err)
	}
	return http.FS(build)
}
e := echo.New()
e.Use(middleware.StaticWithConfig(middleware.StaticConfig{
	Filesystem: BuildFrontendFS(),
	HTML5:      true,
}))
e.Logger.Fatal(e.Start(":1323"))
这个方法很好用,但是当我尝试打开类似localhost:1323/example这样的URL时,它会路由回index.html。问题在于有一个名为example.html的页面,我希望看到该页面。如果我像这样调用URL:localhost:1323/example.html,它可以正常工作。
有什么办法可以解决这个问题,使我可以只使用localhost:1323/example?
英文:
I am trying to embed and serve my frontend (nextjs with static export) with echo. I am currently using:
//go:embed all:frontend/out
var FrontendFS embed.FS
func BuildFrontendFS() http.FileSystem {
	build, err := fs.Sub(FrontendFS, "frontend/out")
	if err != nil {
		log.Fatal(err)
	}
	return http.FS(build)
}
e := echo.New()
e.Use(middleware.StaticWithConfig(middleware.StaticConfig{
	Filesystem: BuildFrontendFS(),
	HTML5:      true,
}))
e.Logger.Fatal(e.Start(":1323"))
It works great however when I try to open a url like localhost:1323/example it routes back to index.html. The problem is that there is a page called example.html and I am expecting to see that page instead. If I call the url like localhost:1323/example.html it works.
Any ideas how I can solve this so that I can just use localhost:1323/example ?
答案1
得分: 1
我看到一个引用了./out目录,所以看起来你正在导出为静态HTML。如果是这种情况,请在你的next.config.js中启用trailingSlash设置:
module.exports = {
  trailingSlash: true,
}
导出后,./example.html将变为./example/index.html。
英文:
I see an ./out directory being referenced, so it looks like you're exporting to static HTML. If that's the case, enable the trailingSlash setting in your next.config.js:
module.exports = {
  trailingSlash: true,
}
./example.html will become ./example/index.html after the export.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论