在 Go Web 应用程序中,我有一个嵌入式 FS,其中包含静态文件和模板文件。
索引函数
func index(w http.ResponseWriter, r *http.Request)
正在解析和执行模板。
我如何才能在
/
路径上同时服务?
GET /
将服务index
GET/{anythingelse}
将从 FS 送达
//go:embed assets
var staticFiles embed.FS
var staticFS = fs.FS(staticFiles)
htmlContent, _ := fs.Sub(staticFS, "assets")
fs := http.FileServer(http.FS(htmlContent))
mux := http.NewServeMux()
mux.Handle("GET /", fs)
mux.HandleFunc("GET /", index)
julienschmidt/httprouter
有一个 router.NotFound。我怎样才能做同样的事情?
在
if
函数中使用 index
语句:
//go:embed assets
var staticFiles embed.FS
var staticFS = fs.FS(staticFiles)
htmlContent, _ := fs.Sub(staticFS, "assets")
fs := http.FileServer(http.FS(htmlContent))
func index(w http.ReponseWriter, r *http.Request) {
if r.URL.Path != "/" {
fs.ServeHTTP(w, r)
return
}
// insert original index code here
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /", index)
...