为URL的所有子目录提供默认页面。

huangapple go评论82阅读模式
英文:

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

huangapple
  • 本文由 发表于 2021年8月5日 00:15:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/68654733.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定