Skip to content

Instantly share code, notes, and snippets.

@tenthree
Last active April 1, 2020 12:02
Show Gist options
  • Save tenthree/8714ce31eb566b679e5e37ad177a23be to your computer and use it in GitHub Desktop.
Save tenthree/8714ce31eb566b679e5e37ad177a23be to your computer and use it in GitHub Desktop.
create an indexless dir filesystem instead of http.Dir for http.FileServer
package main
import "net/http"
func main() {
mux := http.NewServeMux()
// add a "/files" route from the "./static" directory, http://localhost:8080/files/{file}
mux.Handle("/files/", http.StripPrefix("/files/", http.FileServer(utils.NewIndexlessDir("./static"))))
http.ListenAndServe(":8080", mux)
}
package utils
import (
"net/http"
"strings"
)
type indexlessFileSystem struct {
fs http.FileSystem
}
// NewIndexlessDir will create an indexless http.FileSystem in the specified path
func NewIndexlessDir(path string) http.FileSystem {
return &indexlessFileSystem{http.Dir(path)}
}
// Open a file path or any dir path which has index.html
func (ulfs indexlessFileSystem) Open(name string) (http.File, error) {
file, err := ulfs.fs.Open(name)
if err != nil {
return nil, err
}
info, err := file.Stat()
if err != nil {
return nil, err
}
if info.IsDir() {
index := strings.TrimSuffix(name, "/") + "/index.html"
if _, err := ulfs.fs.Open(index); err != nil {
return nil, err
}
}
return file, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment