Skip to content

Instantly share code, notes, and snippets.

@hoshi-takanori
Last active February 24, 2024 18:56
Show Gist options
  • Save hoshi-takanori/db0c4e136b2751809c4c to your computer and use it in GitHub Desktop.
Save hoshi-takanori/db0c4e136b2751809c4c to your computer and use it in GitHub Desktop.
http.FileServer with no directory listing.
// http://grokbase.com/p/gg/golang-nuts/12a9xcadca/go-nuts-disable-directory-listing-with-http-fileserver
package main
import (
"net/http"
"os"
)
type NoListFile struct {
http.File
}
func (f NoListFile) Readdir(count int) ([]os.FileInfo, error) {
return nil, nil
}
type NoListFileSystem struct {
base http.FileSystem
}
func (fs NoListFileSystem) Open(name string) (http.File, error) {
f, err := fs.base.Open(name)
if err != nil {
return nil, err
}
return NoListFile{f}, nil
}
func main() {
fs := NoListFileSystem{http.Dir(".")}
http.ListenAndServe(":8080", http.FileServer(fs))
}
@sheepwall
Copy link

sheepwall commented Jan 25, 2021

Thanks for this.

Wanted to show a 404 for directories as well, so I added in the Open method:

func (fs NoListFileSystem) Open(name string) (http.File, error) {
	f, err := fs.base.Open(name)
	if err != nil {
		return nil, err
	}

	info, err := f.Stat()
	if err != nil {
		return nil, err
	}
	if info.IsDir() {
		return nil, os.ErrNotExist
	}

	return NoListFile{f}, nil
}

edit: messed up earlier, have to use the Stat method of the opened file (as opposed to os.Stat(name)) since base has its own root directory. Fixed that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment