英文:
Serve default page for all subdirs of 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
之类的东西,但实际上没有这样的函数。当然,我可以编写自己的处理程序,但我想知道这里是否有标准化的方法?
这个任务非常常见,我想应该有一些标准化的方法。
英文:
I would like to call FileServer
in such way, that it serves the same page for all subdirectories of distinct directories (subdirs
).
The naïve approach, of course, does not work:
for _, prefix := range subdirs {
fsDist := http.FileServer(http.Dir(defaultPage))
r.PathPrefix(prefix).Handler(http.StripPrefix(prefix, fsDist))
}
Because /abc/123
is mapped to defaultPage/123
and I need just defaultPage
.
For example, if subdirs := []string{"abc", "xyz"}
, it should be mapped like this:
abc/xyz => defaultPage
abc/def => defaultPage
xyz/aaa => defaultPage
I understand that I need something like http.SetPrefix
or something like that, but there is nothing of that kind. Of course, I could write my own handler, but I wonder what is the standard approach here?
The task is pretty common, and I suppose there should be some standardized approach?
答案1
得分: 3
以下是翻译好的内容:
EDIT:多路由支持和静态文件服务:
看起来你只是想要:
r := mux.NewRouter()
r.HandleFunc("/products", ProductsHandler) // 其他路由...
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)
}
工作示例(在playground之外运行):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
英文:
EDIT: multiple-route support & static file-serving:
It sounds like you just want:
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)
}
Working example (run outside playground): 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论