My app has the following structure
~/go
|
|___ go binary (or go source files)
|
|___ static/css, static/js, static/images
|
|___ html/ where index.html, kit1.html files are
This was working fine, but a user could point to http://mysite/static
and get a directory listing which I’d like to prevent.
I’ve found an example on how to circumvent this. Tried to adapt it:
func main() {
//fs := http.FileServer(http.Dir("static/")) (old working)
http.HandleFunc("/", indexHandler)
http.HandleFunc("/kit1", indexHandler)
fs := justFilesFilesystem{http.Dir("")}
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(fs)))
log.Fatal(http.ListenAndServe(":8090", http.FileServer(fs)))
}
type justFilesFilesystem struct {
fs http.FileSystem
}
func (fs justFilesFilesystem) Open(name string) (http.File, error) {
f, err := fs.fs.Open(name)
if err != nil {
return nil, err
}
return neuteredReaddirFile{f}, nil
}
type neuteredReaddirFile struct {
http.File
}
func (f neuteredReaddirFile) Readdir(count int) ([]os.FileInfo, error) {
return nil, nil
}
My handler begins with
func indexHandler(w http.ResponseWriter, r *http.Request) {
path, err := filepath.Abs(filepath.Dir(os.Args[0]))
// error checking surpressed
switch r.Method {
case "GET":
f := urlToFile(r.URL.Path)
fmt.Println("f: ", f)
if f == "" {
f = "index.html"
}
fmt.Println("f_after: ", f)
http.ServeFile(w, r, "html/"+f)
Although it seems to load around 150Kb, it shows a blank page having just
<pre>
</pre>
If index.html
is copied from html/index.html
to /home/lupe/go/
the server renders it.
Wouldn’t like to change html
and static
files locations, what changes should I do to the code?