My simple web application was working fine, except for the part that it was 
showing directory listings, which I'd like to avoid.

After searching, came to this solution
https://groups.google.com/forum/#!msg/golang-nuts/bStLPdIVM6w/hidTJgDZpHcJ
using a virtual file-system.


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, other 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.

Tried to adapt my code to that virtual filesystem solution above:

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)))       // 
second parameter was nil before
}


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
}



The 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.

The function `indexHandler` doesn’t seem to be called whenever `/`, 
`index.html` or `/kit1.html` is chosen, as the `fmt.Println` function 
doesn't print anything on the console.

Without changing the html/ and static/ files locations, what changes should 
I do to the code?

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to