如何在根目录下提供静态页面,同时仍支持Go中的动态路由?

时间:2019-10-17 15:35:02

标签: http go server

如何在仍允许特定子路由的同时将HTML文件作为默认HTTP /路径返回?我想提供一个静态index.html和其他HTML页面,同时仍将特定的路由传递给其他http.Handlers

在下面的示例中,我正在使用httprouter mux,但我也对net/http的示例感兴趣。

router := httprouter.New()
router.GET("/api", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {...})
router.ServeFiles("/*filepath", http.Dir(projectpath.Join("templates")))
router.GET("/", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
    http.FileServer(http.Dir("templates")).ServeHTTP(w, r)
})
router.GET("/api", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {...})

或使用net/http

http.Handle("/", http.FileServer(http.Dir("templates")))
http.Handle("/api", func(w http.ResponseWriter, r *http.Request){...})
http.ListenAndServe(":80", nil)

0 个答案:

没有答案