防止Go公共文件夹中的目录列表显示

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

Prevent Directory Listing in Go Public Folder

问题

我正在使用nginx后面的go,我的公共文件夹有点太公开了:

func main() {
    defer db.Close()

    // 公共目录是 /public
    fs := http.FileServer(http.Dir("public"))

    http.Handle("/public/", http.StripPrefix("/public/", fs))

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {..

如果访问者只是输入了mydomain/public,它可以访问整个公共文件夹并查看所有文件。我希望保持对文件的访问开放(显然),但是如果您只输入/public或/public/images,我想删除目录列表,所以例如/public/css/main.css可以工作,但不是/public/或/public/css。

英文:

I am using go behind nginx and my public folder is well..a bit too public:

func main() {
	defer db.Close()

	// public dir is /public
	fs := http.FileServer(http.Dir("public"))

	http.Handle("/public/", http.StripPrefix("/public/", fs))

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {..

If the visitor just types mydomain/public it can access the whole public folder and. see all the file. I would like to keep the access to the files open (obviously) but I want to remove the directory listing if you just type /public or /public/images
so e.g. /public/css/main.css would work but not /public/ or /public/css

答案1

得分: 2

你可以实现一个自定义中间件,如果路径有尾部斜杠(即它是一个目录),则返回404。

func intercept(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if strings.HasSuffix(r.URL.Path, "/") {
            http.NotFound(w, r)
            return
        }

        next.ServeHTTP(w, r)
    })
}

func main() {
    defer db.Close()

    // public dir is /public
    fs := http.FileServer(http.Dir("public"))

    http.Handle("/public/", http.StripPrefix("/public", intercept(fs)))
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {...}
    ...
}

此外,对于没有尾部斜杠的任何目录的请求将被重定向以接收404响应。

英文:

You can implement a custom middleware to return 404 if path has a trailing slash (ie if it's a directory).

func intercept(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if strings.HasSuffix(r.URL.Path, "/") {
            http.NotFound(w, r)
            return
        }

        next.ServeHTTP(w, r)
    })
}

func main() {
    defer db.Close()

    // public dir is /public
    fs := http.FileServer(http.Dir("public"))

    http.Handle("/public/", http.StripPrefix("/public", intercept(fs)))
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {...}
    ...
}

Also, requests for any directory without the trailing slash will be redirected to receive 404 response.

huangapple
  • 本文由 发表于 2022年4月16日 04:26:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/71888651.html
匿名

发表评论

匿名网友

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

确定