3 回答
TA贡献1851条经验 获得超5个赞
这就是我在标准 Go 库中使用的,路由效果很好。
在此处查看Adapt 功能
// Creates a new serve mux
mux := http.NewServeMux()
// Create room for static files serving
mux.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),
api.GetMongoConnection(),
api.CheckEmptyUserForm(),
api.EncodeUserJson(),
api.ExpectBody(),
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
// 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
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "html/index.html")
})
TA贡献1876条经验 获得超7个赞
您可以http直接使用该包。
索引页
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./public/index.html")
})
这将为所有与路由不匹配的请求提供 index.html 文件。
文件服务器
http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("./public"))))
这将为公共目录中的所有文件提供服务。
不要忘记启动你的服务器
http.ListenAndServe(":8000", nil)
TA贡献1864条经验 获得超2个赞
使用 goji 微框架
https://github.com/zenazn/goji
很容易使用
func render_html_page(w http.ResponseWriter, url string) {
t, err := template.ParseFiles(url)
if err != nil {
panic (err)
}
t.Execute(w, nil)
}
func index(c web.C, w http.ResponseWriter, r *http.Request) {
render_html_page(w, "./public/index.html")
}
func main() {
goji.Get("/", index)
goji.Serve()
}
此代码有效,您只需要进行导入
- 3 回答
- 0 关注
- 144 浏览
添加回答
举报