httprouter icon indicating copy to clipboard operation
httprouter copied to clipboard

Serve static files from root while serving dynamic routes as well

Open xeoncross opened this issue 4 years ago • 0 comments

Being able to serve static files at the root ("/index.html") while still allowing other routes is not covered by the readme. None of the issues I've read cover this either. I'm posting a working solution here for those looking. Perhaps this can be added to the readme.

router := httprouter.New()
router.GET("/", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	http.FileServer(http.Dir(("./templates"))).ServeHTTP(w, r)
})
router.GET("/api/", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	...
})
http.ListenAndServe(":3000", router)

This solves the panic: '/api/' in new path '/api/' conflicts with existing wildcard '/*filepath' in existing prefix '/*filepath' error when using the recommended router.ServeFiles("/*filepath", http.Dir("./templates")) function.

xeoncross avatar Oct 21 '19 15:10 xeoncross