嵌入目录中的index.html在哪里?
我正在尝试将静态站点(和 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.
创建一个以该spa目录为根的子文件系统并为该文件系统提供服务。index.html子文件系统中的路径为index.html.
sub, _ := fs.Sub(spa, "spa")
r.Handle("/", http.FileServer(http.FS(sub)))
https://pkg.go.dev/io/fs#Sub
在操场上运行一个例子。
这种方法适用于任何多路复用器,包括大猩猩多路复用器。这是 Gorilla 的代码,其中r是*mux.Router:
sub, _ := fs.Sub(spa, "spa")
r.PathPrefix("/").Handler(http.FileServer(http.FS(sub)))
在操场上运行一个例子