goweb/static/static.go

29 lines
661 B
Go

package static
import (
"net/http"
"os"
)
// Dir serves the files in the given directory or
// uses the given HandlerFunc to handles missing files
func Dir(dirPath string, stripPrefix string, notFound http.HandlerFunc) http.HandlerFunc {
root := http.Dir(dirPath)
fs := http.FileServer(root)
fn := func(w http.ResponseWriter, r *http.Request) {
if _, err := os.Stat(dirPath + r.RequestURI); os.IsNotExist(err) {
notFound.ServeHTTP(w, r)
} else {
fs.ServeHTTP(w, r)
}
}
handler := http.StripPrefix(stripPrefix, http.HandlerFunc(fn))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handler.ServeHTTP(w, r)
})
}