http - 为 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
或类似的东西,但没有那种东西。当然,我可以编写自己的处理程序,但我想知道这里的标准方法是什么?
这个任务很常见,我想应该有一些标准化的方法?
解决方案
编辑:多路由支持和静态文件服务:
听起来你只是想要:
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
推荐阅读
- symfony - 给定“整数”、“App\Entity\Entreprise”类型的预期参数
- ubuntu - 使用 Mercurial 补丁“应用期间出现错误,请修复并重新刷新”
- unity3d - 在 Unity 中播放粒子系统
- delphi - 可以使 TDBEdit 上的 TextHint 属性起作用
- angular - 以角度在两个 sass 文件之间切换
- office-js - Office.js API 的 displayDialogAsync 方法未打开页面
- mysql - MySQL 可以输出相当于 perl 压缩整数吗?
- python - 如何在 PyTorch 中删除图层指定位置的节点
- r - R - 在城市地图上拟合网格并将数据输入到网格方块中
- ecmascript-6 - Lodash:根据条件在多级Json中查找并添加项目