Home > Software design >  Prevent Directory Listing in Go Public Folder
Prevent Directory Listing in Go Public Folder

Time:04-16

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

CodePudding user response:

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.

CodePudding user response:

A simple way would be to create an empty index.html file inside the directory /public.

Or you could add a location block for the directory to your nginx configuration, and turn the autoindex feature off:

location /public {
       autoindex off;
}
  •  Tags:  
  • go
  • Related