goweb/static/static.go

23 lines
573 B
Go
Raw Normal View History

2018-12-06 15:18:05 +01:00
package static
import (
"net/http"
"os"
)
// Dir serves the files in the given directory or
// uses the given handler to handles missing files
func Dir(dirPath string, stripPrefix string, notFoundHandler http.Handler) http.Handler {
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) {
notFoundHandler.ServeHTTP(w, r)
} else {
fs.ServeHTTP(w, r)
}
}
handler := http.StripPrefix(stripPrefix, http.HandlerFunc(fn))
return handler
}