首页 > 解决方案 > 为 URL 的所有子目录提供默认页面

问题描述

我想以FileServer这样的方式调用,它为不同目录(subdirs)的所有子目录提供相同的页面。

当然,幼稚的方法是行不通的:

  for _, prefix := range subdirs {
     fsDist := http.FileServer(http.Dir(defaultPage))
     r.PathPrefix(prefix).Handler(http.StripPrefix(prefix, fsDist))
  }

因为/abc/123被映射到defaultPage/123并且我只需要defaultPage.

例如,如果subdirs := []string{"abc", "xyz"},它应该像这样映射:

    abc/xyz => defaultPage
    abc/def => defaultPage
    xyz/aaa => defaultPage

我知道我需要类似http.SetPrefix或类似的东西,但没有那种东西。当然,我可以编写自己的处理程序,但我想知道这里的标准方法是什么?

这个任务很常见,我想应该有一些标准化的方法?

标签: httpgourlgorillamux

解决方案


编辑:多路由支持和静态文件服务:


听起来你只是想要:

r := mux.NewRouter()
r.HandleFunc("/products", ProductsHandler) // some other route...

staticFilePath := "catch-all.txt"

fh := http.HandlerFunc(
    func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, staticFilePath)
    },
)

for _, dir := range []string{"abc", "xyz"} {
    r.PathPrefix("/" + dir + "/").Handler(fh)
}

工作示例(在操场外运行): https: //play.golang.org/p/MD1Tj1CUcEh

$ curl localhost:8000/abc/xyz
catch all

$ curl localhost:8000/abc/def
catch all

$ curl localhost:8000/xyz/aaa
catch all

$ curl localhost:8000/products
product

推荐阅读