Hello,
I was playing with the file server and wanted to route root search to a index.html located inside a http.FileServer.
Im having the following code to demonstrate.
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httputil"
"os"
"strings"
)
var staticHttp = http.NewServeMux()
func ApplicationHandler(w http.ResponseWriter, r *http.Request) {
dump, err := httputil.DumpRequest(r, true)
if err != nil {
http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
return
}
fmt.Printf("%q \n", dump)
if strings.Contains(r.URL.Path, ".") {
staticHttp.ServeHTTP(w, r)
} else {
http.Redirect(w, r, "/index.html", http.StatusPermanentRedirect)
}
}
func main() {
defer os.Remove("./dist/index.html")
defer os.Remove("./dist/another.file")
defer os.Remove("./dir")
_ = os.Mkdir("./dist", 0777)
_ = ioutil.WriteFile("./dist/index.html", []byte("MY APP"), 0777)
_ = ioutil.WriteFile("./dist/another.file", []byte("another file"), 0777)
http.HandleFunc("/", ApplicationHandler)
staticHttp.Handle("/", http.FileServer(http.Dir("./dist")))
http.ListenAndServe(":9999", nil)
}
This code dont work when i visit â/â my browser will start loop.
Solution for my problem is just to use http.Handle("/", http.FileServer(http.Dir("./dist"))) since by default the browser seems to look for index.html
I share on the forum to try find out what causes the behaviour when I route a StatusPermanentRedirect to a http.FileServer.