登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-01 09:21:31 154浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《为 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

理论要掌握,实操不能落!以上关于《为 URL 的所有子目录提供默认页面》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>