« Back to Index

[Golang Prevent Directory Listing with Static FileServer]

View original Gist on GitHub

Tags: #static #fileserver #go #golang

Golang Prevent Directory Listing with Static FileServer.go

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

func main() {
	http.Handle("/", noDirListing(http.FileServer(http.Dir("./static/"))))
	log.Println(http.ListenAndServe(":8080", nil))
}