Golang 静态文件夹路径 returns 所有文件

Golang Static folder path returns all files

我有一个打开静态文件夹的代码

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

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

例如

license.txt
logo.png

但我想return一个空白页

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

像这样

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

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 中没有尾部斜线的子目录请求;要解决这个问题,您需要一个更详细的自定义实现,它是文件系统感知的,以了解什么是目录,什么是文件。

看起来您正在使用 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 文档:

...if a subtree has been registered and a request is received naming the subtree root without its trailing slash, ServeMux redirects that request to the subtree root (adding the trailing slash). This behavior can be overridden with a separate registration for the path without the trailing slash. For example, registering "/images/" causes ServeMux to redirect a request for "/images" to "/images/", unless "/images" has been registered separately.