An alternative (not using ServeMux) solution is to serve explicitly each file located in the root directory. The idea behind is to keep the number of root-based files very small.
sitemap.xml, favicon.ico, robots.txt are indeed mandated to be served out of the root :
package main
import (
"fmt"
"net/http"
)
func HomeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "HomeHandler")
}
func serveSingle(pattern string, filename string) {
http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, filename)
})
}
func main() {
http.HandleFunc("https://stackoverflow.com/", HomeHandler) // homepage
// Mandatory root-based resources
serveSingle("/sitemap.xml", "./sitemap.xml")
serveSingle("/favicon.ico", "./favicon.ico")
serveSingle("/robots.txt", "./robots.txt")
// Normal resources
http.Handle("/static", http.FileServer(http.Dir("./static/")))
http.ListenAndServe(":8080", nil)
}
Please move all other resources (CSS, JS, etc.) to a proper subdirectory, e.g. /static/
.