Mahmoud Ahmed
Mahmoud Ahmed

Reputation: 33

golang Resource interpreted as Stylesheet but transferred with MIME type text/plain

I have a problem in developing my webpage using golang. server file (main.go):

package main

import (
    "net/http"
    "io/ioutil"
    "strings"
    "log"
)

type MyHandler struct {
}

func (this *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    path := r.URL.Path[1:]
    log.Println(path)
    data, err := ioutil.ReadFile(string(path))

    if err == nil {
        var contentType string

        if strings.HasSuffix(path, ".css") {
            contentType = "text/css"
        } else if strings.HasSuffix(path, ".html") {
            contentType = "text/html"
        } else if strings.HasSuffix(path, ".js") {
            contentType = "application/javascript"
        } else if strings.HasSuffix(path, ".png") {
            contentType = "image/png"
        } else if strings.HasSuffix(path, ".svg") {
            contentType = "image/svg+xml"
        } else {
            contentType = "text/plain"
        }

        w.Header().Add("Content Type", contentType)
        w.Write(data)
    } else {
        w.WriteHeader(404)
        w.Write([]byte("404 Mi amigo - " + http.StatusText(404)))
    }
}

func main() {
    http.Handle("/", new(MyHandler))
    http.ListenAndServe(":8080", nil)
}

But when i type http://localhost:8080/templates/home.html this what i see see screenshot Why my page is not loaded right?? where is my css?? whyy is the error "Resource interpreted as Stylesheet but transferred with MIME type text/plain:" appears while i have my content Type in main.go handled??

Upvotes: 3

Views: 1545

Answers (2)

anirudh adiga
anirudh adiga

Reputation: 39

as mentioned by "Milo Christiansen" mime will help in this case. I also wanted to point out that it will be efficient to use io.Copy instead of ioutil.ReadFile (if the stream copy can happen at kernel level it will do)

package main

import (
    "io"
    "log"
    "mime"
    "net/http"
    "os"
    "path/filepath"
)

func main() {
    http.HandleFunc("/", ServeFile)
    log.Fatal(http.ListenAndServe(":8400", nil))
}

func ServeFile(resp http.ResponseWriter, req *http.Request) {
    path := filepath.Join("./resource/", req.URL.Path)
        
    file, err := os.Open(path)
    if err != nil {
        http.Error(resp, err.Error(), http.StatusNotFound)
        return
    }

    if contentType := mime.TypeByExtension(filepath.Ext(path)); len(contentType) > 0 {
        resp.Header().Add("Content-Type", contentType)
    }

    io.Copy(resp, file)
}

Upvotes: 0

Milo Christiansen
Milo Christiansen

Reputation: 3294

Your basic problem is very simple: You need Content-Type instead of Content Type.

However, there is a better way to match MIME types to file extensions in Go, specifically the mime standard library package. I would strongly suggest that you use it.

Upvotes: 4

Related Questions