Go 1.22 http mux:在同一路径上提供句柄和 FS

问题描述 投票:0回答:1

在 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。我怎样才能做同样的事情?

go
1个回答
0
投票

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)
    ...
© www.soinside.com 2019 - 2024. All rights reserved.