Golang:资源被解释为样式表,但传输的MIME类型为文本/纯文本。

3

我在使用golang开发我的网页时遇到了问题。 服务器文件(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)
}

但是当我输入http://localhost:8080/templates/home.html时,我看到的是截图。为什么我的页面没有正确加载?我的CSS在哪里?为什么会出现“资源被解释为样式表,但MIME类型为text/plain:”的错误,而我已经在main.go中处理了内容类型?

请点击上面的链接,查看我打开网页时所看到的内容。 - Mahmoud Ahmed
1
请参见 https://github.com/golang/go/wiki/HttpStaticFiles。 - user4466350
2个回答

4
你的基本问题非常简单:你需要使用Content-Type而不是Content Type
然而,在Go语言中,有一种更好的方法将MIME类型与文件扩展名匹配,那就是使用标准库包mime。我强烈建议你使用它。

0

正如"Milo Christiansen"所提到的,mime在这种情况下会有所帮助。 我还想指出,使用io.Copy而不是ioutil.ReadFile会更有效率(如果流复制可以在内核级别进行,则会执行)

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)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接