【问题标题】:Golang Static folder path returns all filesGolang 静态文件夹路径返回所有文件
【发布时间】:2021-11-01 06:54:41
【问题描述】:

我有这个代码来打开静态文件夹

fs := http.FileServer(http.Dir("./static/"))
router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))

但是当我要去/static 路径时,它会返回此文件夹中的文件列表

例如

license.txt
logo.png

但我想返回一个空白页

【问题讨论】:

    标签: go static-files mux


    【解决方案1】:

    您可以在./static/目录中添加空白index.html,它将呈现为空白页面。

    类似的东西

    <html>
    <head><title>Nothing here</title></head>
    <body><h1>Nothing here</h1></body>
    </html>
    

    【讨论】:

    • @YusufYakubov 文件服务器为文件和目录提供服务,如果您想要自定义行为,您需要自己实现文件服务器
    【解决方案2】:

    vodolaz095 的回答是最简单的,但如果你真的必须在 Go 中这样做,你可以包装 FileServer 以捕获根请求的特定情况:

    func noIndex(fs http.Handler) http.HandlerFunc {
        return func(w http.ResponseWriter, r *http.Request) {
            if r.URL.Path == "" || strings.HasSuffix(r.URL.Path, "/") {
                w.Write("")
                return
            }
            fs.ServeHTTP(w, r)
        }
    }
    

    请注意,这不会捕获对 URL 中没有尾部斜杠的子目录的请求;要捕获这一点,您需要一个更详细的自定义实现,该实现是文件系统感知的,以了解什么是目录和什么是文件。

    【讨论】:

      【解决方案3】:

      看起来您正在使用gorilla/mux - 但如果您不介意使用标准库的http.ServeMux,您可以在Go 代码中实现这一点,如下所示:

      func main() {
      
          fs := http.FileServer(http.Dir("./static/"))
          h := http.NewServeMux()
      
          blank := http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {})
      
          h.Handle("/static/", http.StripPrefix("/static/", fs)) // will match "/static" with a redirect ...
          h.Handle("/static", blank)                             // ... unless you create a hanlder explicitly
      
          http.ListenAndServe(":8080", h)
      }
      

      来自http.ServeMux 文档:

      ...如果已注册子树并收到请求命名 没有尾部斜杠的子树根,ServeMux 重定向 对子树根的请求(添加尾部斜杠)。这种行为 可以通过单独的路径注册来覆盖,而无需 尾部斜线。例如,注册“/images/”会导致 ServeMux 将对“/images”的请求重定向到“/images/”,除非 “/images”已单独注册。

      【讨论】:

        猜你喜欢
        • 2014-08-20
        • 2018-08-18
        • 2022-11-10
        • 1970-01-01
        • 1970-01-01
        • 2020-03-19
        • 2015-10-03
        • 1970-01-01
        相关资源
        最近更新 更多