英文:
Go + Angular: loading base html
问题
我正在尝试使用Go和Angular编写一个应用程序。我不确定我是否理解了概念,但基本上我应该提供一个简单的HTML页面,加载Angular和应用程序(JS)本身,然后通过Ajax请求处理其余部分。我不知道的是如何在每个非Ajax请求的每个路径上提供HTML文件?我想使用Gorilla mux,但我找不到如何做到这一点。
这样做是否正确?
英文:
I'm trying to write an app in Go with Angular. I'm not sure if I got the concept right, but basically I should serve a simple html that loads angular and the app (js) itself and then the rest is handled by ajax requests. What I don't know is how to serve the html file on every non-ajax request on every path? I would like to use Gorilla mux but I couldn't find out how to do that.
Is this even the right direction?
答案1
得分: 1
对于每个不是已知 URL 的请求,您应该发送 index.html 文件,或者您的基本 Angular 应用程序文件。
Gorilla/mux 有一个 NotFoundHandler,它是处理任何未匹配其他路由的请求的处理程序。您可以像这样为其分配自己的处理程序:
使用 gorilla/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")
}
假设您的基本文件位于 static/index.html 中 :).
现在,所有不是其他请求(在该设置中,不是在路由中定义的 ajax 调用)的请求将提供带有可以由 ngRoute 或 ui-router 处理的 URL 的索引文件。
英文:
On every request that is not any known url You should send index.html - or whatever is Your base angular app file.
Gorilla/mux has a NotFoundHandler, which is handler for everyting that is not matched by any other routes. You can assignt Your own handler for it like that:
solution with gorilla/mux is:
func main() {
r := mux.NewRouter()
r.HandleFunc("/foo", fooHandler)
r.NotFoundHandler = http.HandlerFunc(notFound)
http.Handle("/", r)
}
while notFound is:
func notFound(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "static/index.html")
}
assuming the Your base file is in static/index.html :).
Now all Your requests that are not any other requests (so, in that setup - not an ajax call defined in routes) will serve index file with url that can be handled by ngRoute or ui-router.
答案2
得分: 0
//从与可执行文件相同的目录中的“public”文件夹中提供静态文件。
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-cache")
http.ServeFile(w, r, "public"+r.URL.Path)
})
这将尝试从public目录中提供与URL不匹配的每个URL。希望这可以帮到你。
英文:
//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)
})
This will try to serve every non-matching URL from the public directory. Hope this helps.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论