Prevent Directory Listing in Go Public Folder

Viewed 120

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 Answers

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.

Related