Golang + 角

我开始尝试使用 Go 和 Angular,但我有一个奇怪的问题..我想我只是遗漏了一个小细节,但我无法弄清楚。

我正在使用https://github.com/julienschmidt/httprouter作为 Go 的路由器......现在使用 Angular,我应该能够将 URL 复制并粘贴到浏览器中,Angular 应该处理相应的路由,对吗?

我有一个“/登录”路线。如果通过前端访问路由....

Go 路由基本上只是在做

router.NotFound = http.FileServer(http.Dir("./public"))

这适用于“/”路线,但不适用于其他任何路线。这似乎是正确的。但是如何正确设置路由,以便 Angular 处理所有路由?


神不在的星期二
浏览 145回答 3
3回答

江户川乱折腾

这就是我在标准 Go 库中使用的,路由效果很好。在此处查看Adapt 功能// Creates a new serve muxmux := http.NewServeMux()// Create room for static files servingmux.Handle("/node_modules/", http.StripPrefix("/node_modules", http.FileServer(http.Dir("./node_modules"))))mux.Handle("/html/", http.StripPrefix("/html", http.FileServer(http.Dir("./html"))))mux.Handle("/js/", http.StripPrefix("/js", http.FileServer(http.Dir("./js"))))mux.Handle("/ts/", http.StripPrefix("/ts", http.FileServer(http.Dir("./ts"))))mux.Handle("/css/", http.StripPrefix("/css", http.FileServer(http.Dir("./css"))))// Do your api stuff**mux.Handle("/api/register", util.Adapt(api.RegisterHandler(mux),&nbsp; &nbsp; api.GetMongoConnection(),&nbsp; &nbsp; api.CheckEmptyUserForm(),&nbsp; &nbsp; api.EncodeUserJson(),&nbsp; &nbsp; api.ExpectBody(),&nbsp; &nbsp; api.ExpectPOST(),))mux.HandleFunc("/api/login", api.Login)mux.HandleFunc("/api/authenticate", api.Authenticate)// Any other request, we should render our SPA's only html file,// Allowing angular to do the routing on anything else other then the api&nbsp; &nbsp;&nbsp;// and the files it needs for itself to work.// Order here is critical. This html should contain the base tag like// <base href="/"> *href here should match the HandleFunc path below&nbsp;mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; http.ServeFile(w, r, "html/index.html")})

幕布斯6054654

您可以http直接使用该包。索引页http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; http.ServeFile(w, r, "./public/index.html")})这将为所有与路由不匹配的请求提供 index.html 文件。文件服务器http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("./public"))))这将为公共目录中的所有文件提供服务。不要忘记启动你的服务器http.ListenAndServe(":8000", nil)

慕斯王

使用 goji 微框架https://github.com/zenazn/goji很容易使用func render_html_page(w http.ResponseWriter, url string) {&nbsp; &nbsp; t, err := template.ParseFiles(url)&nbsp;&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic (err)&nbsp; &nbsp; }&nbsp; &nbsp; t.Execute(w, nil)}func index(c web.C, w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; render_html_page(w, "./public/index.html")}func main() {&nbsp; &nbsp; &nbsp; &nbsp; goji.Get("/", index)&nbsp; &nbsp; &nbsp; &nbsp; goji.Serve()}此代码有效,您只需要进行导入
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go