Created
March 15, 2021 12:16
-
-
Save fakihariefnoto/6cd08b639f36837ad4223caf7ab717a8 to your computer and use it in GitHub Desktop.
golang httprouter disable access index folder but allow for dynamic filename to serve files
This file contains 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
// import "github.com/julienschmidt/httprouter" | |
// example router | |
// Serve static files for Assets | |
router := httprouter.New() | |
router.GET("/fonts/*filepath", fileHandler("/fonts/")) | |
router.GET("/styles/*filepath", fileHandler("/styles/")) | |
router.GET("/scripts/*filepath", fileHandler("/scripts/")) | |
router.GET("/img/*filepath", fileHandler("/img/")) | |
// fileHandler to handle directory index | |
func fileHandler(folder string) httprouter.Handle { | |
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { | |
fileReq := p.ByName("filepath") | |
// disable / or /assets/childdirective/../ | |
if fileReq == "/" || (len(fileReq) > 1 && fileReq[len(fileReq)-1:] == "/") { | |
w.WriteHeader(http.StatusNotFound) | |
fmt.Fprint(w, "404 page not found") | |
return | |
} | |
r.URL.Path = fileReq | |
fileServer := http.FileServer(http.Dir(fmt.Sprintf("%v%v", "/var/www", folder))) | |
fileServer.ServeHTTP(w, r) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment