Skip to content

Instantly share code, notes, and snippets.

@anonymouse64
Created May 25, 2019 13:27
Show Gist options
  • Save anonymouse64/2c282ea1604065aecfdd556b3c8f2f64 to your computer and use it in GitHub Desktop.
Save anonymouse64/2c282ea1604065aecfdd556b3c8f2f64 to your computer and use it in GitHub Desktop.
// singleFileHandler creates a http handler for a single statically specific
// file
// note that this doesn't use the url request path as the file, it uses the
// function argument as what file to serve
func singleFileHandler(f string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Return a 404 if the file doesn't exist
info, err := os.Stat(f)
if err != nil {
if os.IsNotExist(err) {
http.NotFound(w, r)
return
}
}
// Return a 404 if the request is for a directory
if info.IsDir() {
http.NotFound(w, r)
return
}
// otherwise serve the single file
http.ServeFile(w, r, f)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment