goweb/static/static.go

29 lines
661 B
Go
Raw Permalink 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 HandlerFunc to handles missing files
func Dir(dirPath string, stripPrefix string, notFound http.HandlerFunc) http.HandlerFunc {
2018-12-06 15:18:05 +01:00
root := http.Dir(dirPath)
fs := http.FileServer(root)
2018-12-06 15:18:05 +01:00
fn := func(w http.ResponseWriter, r *http.Request) {
if _, err := os.Stat(dirPath + r.RequestURI); os.IsNotExist(err) {
notFound.ServeHTTP(w, r)
2018-12-06 15:18:05 +01:00
} else {
fs.ServeHTTP(w, r)
}
}
2018-12-06 15:18:05 +01:00
handler := http.StripPrefix(stripPrefix, http.HandlerFunc(fn))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handler.ServeHTTP(w, r)
})
2018-12-06 15:18:05 +01:00
}