Created
September 17, 2019 21:56
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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