我正在尝试用Go with Angular编写一个应用程序。我不确定我的概念是否正确,但基本上我应该提供一个简单的html,它加载angular和应用程序(js)本身,然后其余的由ajax请求处理。我不知道的是,如何在每个路径上的每个非ajax请求上提供html文件?我想使用大猩猩mux,但我不知道如何做到这一点。
这是正确的方向吗?
对于不是任何已知url的每个请求,您应该发送index.html或任何您的基本angular应用程序文件。
Gorilla/mux有一个NotFoundHandler,它是所有其他路由不匹配的东西的处理程序。你可以为它指定自己的处理程序:
大猩猩/mux的解决方案是:
func main() {
r := mux.NewRouter()
r.HandleFunc("/foo", fooHandler)
r.NotFoundHandler = http.HandlerFunc(notFound)
http.Handle("/", r)
}
而notFound是:
func notFound(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "static/index.html")
}
假设Your的基本文件是static/index.html:)。
现在,所有不是任何其他请求的Your请求(因此,在该设置中,不是路由中定义的ajax调用)都将提供具有url的索引文件,该url可以由ngRoute或ui路由器处理。
//serve static files from a folder 'public' which should be in the same dir as the executable.
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-cache")
http.ServeFile(w, r, "public"+r.URL.Path)
})
这将尝试为公共目录中的每个不匹配的URL提供服务。希望这能有所帮助。