我正在尝试 embed一个静态站点(和 SPA)到我的 Go 代码中。我的项目的高层结构是
.
├── web.go
└── spa/
└── index.html
我的意图是拥有 http://localhost:8090/
服务 index.html
.执行此操作的相关代码是
//go:embed spa
var spa embed.FS
log.Info("starting api server")
r := mux.NewRouter()
r.Handle("/", http.FileServer(http.FS(spa)))
log.Fatal(http.ListenAndServe(":8090", r))
访问时http://localhost:8090/
,我得到spa
404 page not found
我应该如何设置?
最佳答案
嵌入目录中的文件路径以//go:embed 指令中使用的路径为前缀。 index.html 的内嵌文件系统路径是 spa/index.html
.
Create a sub file system Root 于spa
目录并为该文件系统提供服务。 index.html
的路径在子文件系统中是 index.html
.
sub, _ := fs.Sub(spa, "spa")
r.Handle("/", http.FileServer(http.FS(sub)))
https://pkg.go.dev/io/fs#SubRun an example on the playground .
这种方法适用于任何多路复用器,包括 gorilla 多路复用器。这是 Gorilla 的代码,其中
r
是 *mux.Router
:sub, _ := fs.Sub(spa, "spa")
r.PathPrefix("/").Handler(http.FileServer(http.FS(sub)))
Run an example on the playground
关于go - 嵌入目录中的 index.html 在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67232525/