Skip to content

Instantly share code, notes, and snippets.

@hauxe
Created July 4, 2018 05:05
Show Gist options
  • Save hauxe/f2ea1901216177ccf9550a1b8bd59178 to your computer and use it in GitHub Desktop.
Save hauxe/f2ea1901216177ccf9550a1b8bd59178 to your computer and use it in GitHub Desktop.
package main
import (
"flag"
"log"
"net/http"
"strings"
)
// FileSystem custom file system handler
type FileSystem struct {
fs http.FileSystem
}
// Open opens file
func (fs FileSystem) Open(path string) (http.File, error) {
f, err := fs.fs.Open(path)
if err != nil {
return nil, err
}
s, err := f.Stat()
if s.IsDir() {
index := strings.TrimSuffix(path, "/") + "/index.html"
if _, err := fs.fs.Open(index); err != nil {
return nil, err
}
}
return f, nil
}
func main() {
port := flag.String("p", "3000", "port to serve on")
directory := flag.String("d", ".", "the directory of static file to host")
flag.Parse()
fileServer := http.FileServer(FileSystem{http.Dir(*directory)})
http.Handle("/statics/", http.StripPrefix(strings.TrimRight("/statics/", "/"), fileServer))
log.Printf("Serving %s on HTTP port: %s\n", *directory, *port)
log.Fatal(http.ListenAndServe(":"+*port, nil))
}
@threadedstream
Copy link

Adding additional null-check right after f.Stat() would be great. Thanks for a snippet.

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