Last active
February 24, 2024 18:56
-
-
Save hoshi-takanori/db0c4e136b2751809c4c to your computer and use it in GitHub Desktop.
http.FileServer with no directory listing.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this.
Wanted to show a 404 for directories as well, so I added in the Open method:
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.