Go index.html在嵌入式目录中的什么位置?
我正在尝试将静态站点(和SPA)添加到我的Go代码中。我的项目的高层结构是Go index.html在嵌入式目录中的什么位置?,go,webserver,single-page-application,Go,Webserver,Single Page Application,我正在尝试将静态站点(和SPA)添加到我的Go代码中。我的项目的高层结构是 . ├── web.go └── spa/ └── index.html 我的目的是拥有http://localhost:8090/serviceindex.html sub, _ := fs.Sub(spa, "spa") r.Handle("/", http.FileServer(http.FS(sub))) 相关的代码是 //go:embed spa var sp
.
├── web.go
└── spa/
└── index.html
我的目的是拥有http://localhost:8090/
serviceindex.html
sub, _ := fs.Sub(spa, "spa")
r.Handle("/", http.FileServer(http.FS(sub)))
相关的代码是
//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页面未找到
该如何设置?嵌入目录中的文件路径以//go:embed指令中使用的路径作为前缀。index.html的嵌入式文件系统路径为<代码>spa/index.html
sub, _ := fs.Sub(spa, "spa")
r.Handle("/", http.FileServer(http.FS(sub)))
扎根于spa
目录并服务于该文件系统。子文件系统中index.html的路径是index.html
sub, _ := fs.Sub(spa, "spa")
r.Handle("/", http.FileServer(http.FS(sub)))
这种方法适用于任何mux,包括Gorilla mux
示例:对于Gorilla Mux,您需要指定路径前缀:
package main
import (
"embed"
"fmt"
"github.com/gorilla/mux"
"log"
"net/http"
)
//go:embed spa
var spa embed.FS
func main() {
log.Println("starting api server")
r := mux.NewRouter()
r.PathPrefix("/spa/").Handler(http.StripPrefix("/", http.FileServer(http.FS(spa))))
log.Fatal(http.ListenAndServe(":8090", r))
}
这将请求路由到/spa/*
处理程序。然后,您必须去掉前缀/
,因为spa
目录的内容有spa/
前缀,但没有前导的/
:
b, _ := spa.ReadFile("spa/index.html")
fmt.Println(string(b)) // file contents
总结一下:
http://localhost:8090/spa/index.html
被路由到r.PathPrefix(“/spa/”)
处理程序。虽然路由是/spa/index.html
,但去掉第一个/
,结果是spa/index.html
,这最终匹配嵌入变量中的文件路径。非常感谢您的详细解释。它的工作原理是http://localhost:8090/spa/
最终到达index.html
文件,URI为http://localhost:8090/spa/#/
(内容完全可见)。非常感谢。我将了解如何将/
重定向到/spa/
,以使根目录服务于spa。谢谢。我必须对此进行调查,因为当从@blackgreen的解决方案转到您的解决方案时(r.PathPrefix(“/spa/”).Handler(http.StripPrefix(“/”,http.FileServer(http.FS(spa)))
→ r.Handle(“/”,http.FileServer(http.FS(sub))
),对index.html
的调用是正确的,但随后所有连续调用都失败了(使用404或(取消)
),这真的很奇怪(在同一spa
目录上)。您所说的“所有连续调用”是什么意思?你是说对/index.html
的第二个请求失败了,对其他url的请求失败了吗?对不起,我不清楚。我的意思是,index.html
调用其他URL(它是一个SPA),这些调用(对创建的FS中的文件,在index.html
旁边)以404或(取消)
(根据Chrome DevTools)失败。奇怪的是,另一个解决方案可以在相同的位置使用相同的文件(当然是使用/spa
后缀调用)@Woj-See。编辑问题以显示spa/目录中其他文件的位置以及用于访问这些文件的URL。我猜源文件的结构和URL之间不匹配。