23 lines
573 B
Go
23 lines
573 B
Go
|
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
|
||
|
}
|