如何在 Go 中将静态文件提供给动态路径?

时间:2021-03-25 16:55:15

标签: go gorilla mux

我的文件结构就是 main.go 在文件夹 co 和文件夹 cmd 内。

-assets/
-cmd/co/main.go

这是我在 main.go 中的代码,

func main() {
    router := NewRouter()
    router.HandleFunc("/search", api.SearchHandler)
    router.HandleFunc("/product-details/{author}/{name}/{id}//", api.DetailsHandler)
    // ... listenAndServe
}

func NewRouter() *mux.Router {
    router := mux.NewRouter()
    staticDir := "/assets/"
    router.
        PathPrefix(staticDir).
        Handler(http.StripPrefix(staticDir, http.FileServer(http.Dir("."+staticDir))))
    return router
}

处理静态 url 的 /search 工作正常,但是当我使用子路由转到 product-details/{author} ...(动态 url 路径)时,Web 浏览器会向我发送错误 404。所以 go 不会以这种方式在动态路径中提供文件夹

0 个答案:

没有答案