Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fakihariefnoto/6cd08b639f36837ad4223caf7ab717a8 to your computer and use it in GitHub Desktop.
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
// 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