Skip to content

Instantly share code, notes, and snippets.

@timjonesdev
Created September 17, 2019 21:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timjonesdev/469a290717b6c65cae9f2b228fa4f062 to your computer and use it in GitHub Desktop.
Save timjonesdev/469a290717b6c65cae9f2b228fa4f062 to your computer and use it in GitHub Desktop.
A static file server that gracefully handles resource not found errors and passes requests to the client.
func StaticFileServer(r chi.Router, public string, static string) {
// everything up to the r.Get call is executed the first time the function is called
if strings.ContainsAny(public, "{}*") {
panic("FileServer does not permit URL parameters.")
}
root, _ := filepath.Abs(static)
if _, err := os.Stat(root); os.IsNotExist(err) {
panic("Static Documents Directory Not Found")
}
fs := http.StripPrefix(public, http.FileServer(http.Dir(root)))
if public != "/" && public[len(public)-1] != '/' {
r.Get(public, http.RedirectHandler(public+"/", 301).ServeHTTP)
public += "/"
}
// Register the Get request for the specified path, most likely /*
r.Get(public+"*", func(w http.ResponseWriter, r *http.Request) {
file := strings.Replace(r.RequestURI, public, "/", 1)
// if the requested resource was not found, pass the request to the client
if _, err := os.Stat(root + file); os.IsNotExist(err) {
http.ServeFile(w, r, path.Join(root, "index.html"))
return
}
// if the requested resource was found, serve it
fs.ServeHTTP(w, r)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment