0

How do you return HTML files as the default HTTP / path while still allowing specific child routes? I would like to serve a static index.html and some other HTML pages while still having specific routes passed to other http.Handlers.

In the example below I'm using the httprouter mux, but I'm interested in examples for net/http as well.

router := httprouter.New()
router.GET("/api", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {...})
router.ServeFiles("/*filepath", http.Dir(projectpath.Join("templates")))
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) {...})

Or using net/http

http.Handle("/", http.FileServer(http.Dir("templates")))
http.Handle("/api", func(w http.ResponseWriter, r *http.Request){...})
http.ListenAndServe(":80", nil)
Xeoncross
  • 55,620
  • 80
  • 262
  • 364
  • Your last example works and does what you want. What is your question? – icza Oct 17 '19 at 15:40
  • @icza I am unable to serve files from `templates/*` other than `templates/index.html` – Xeoncross Oct 17 '19 at 19:32
  • Here is a more complete example: https://gist.github.com/Xeoncross/74cce1a97a28c08a18dc2c5f7d678490 – Xeoncross Oct 17 '19 at 19:32
  • That works for me. I put 2 files into `templates`: `index.html` and `list.html`. Querying `localhost:80/list.html` serves me the `list.html`. – icza Oct 18 '19 at 07:33

0 Answers0