dimanche 3 janvier 2016

css and js loading as text/html with golang's html templates and thus not running on the html page

ok so I JUST started learning golang just cuz I have some free time now and it's fun. and I don't wanna serve static pages, so I am using html/template, but when the page runs, the js and css files are not working.

here's my starter code:

func main() {
    http.HandleFunc("/", handleHTTP);
    http.ListenAndServe(":8080", nil);
}

func HandleHTTP(w http.ResponseWriter, r *http.Request){
    tmpl, err := template.New("MainPage").ParseFiles("index.html");
    if (err != nil){
        fmt.Println(err.Error());
    }

    tmpl.ExecuteTemplate(w, "MAIN", r.URL.Path);
}

then, I saw on a youtube vid about building web apps with golang to change the content type before you load the file so that the server knows what type of file is it. and so my new code changed to this big conditional for now, I will change it to a slice of file extensions, but for now I just want it to work first.

func handleHTTP(w http.ResponseWriter, r *http.Request){
    var contentType string;
    url := r.URL.Path;
    if (strings.HasSuffix(url, ".html")){
        contentType = "text/html";
    } else if (strings.HasSuffix(url, ".css")){
        contentType = "text/css";
    } else if (strings.HasSuffix(url, ".js")){
        contentType = "application/javascript";
    } else if (strings.HasSuffix(url, ".png")) {
        contentType = "image/png";
    } else if (strings.HasSuffix(url, ".jpg")) {
        contentType = "image/jpeg";
        http.ServeFile(w, r, r.URL.Path);
    } else if (strings.HasSuffix(url, ".gif")){
        contentType = "image/gif";
    } else if (strings.HasSuffix(url, ".svg")){
        contentType = "image/svg+xml";
    } else if (strings.HasSuffix(url, ".mp4")){
        contentType = "video/mp4";
    } else if (strings.HasSuffix(url, ".webm")) {
        contentType = "video/webm";
    } else if (strings.HasSuffix(url, ".ogg")) {
        contentType = "video/ogg";
    } else if (strings.HasSuffix(url, ".mp3")) {
        contentType = "audio/mp3";
    } else if (strings.HasSuffix(url, ".wav")) {
        contentType = "audio/wav";
    } else if (url == "") {
        w.Header().Set("Content-Type", contentType);
        tmpl, _ := template.New("MainPage").ParseFiles("index.html");
        tmpl.ExecuteTemplate(w, "MAIN", url);
    }


}

but still, the html page is loaded and the js and css files are read as text/html when I looked through the inspect element, so I don't know how to make them work, please and thank you.




Aucun commentaire:

Enregistrer un commentaire