golang资源解释为样式表,但使用MIME类型text / plain进行传输

时间:2017-10-07 17:28:03

标签: html css go glide-golang

使用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时 这就是我所看到的see screenshot 为什么我的页面没有正确加载?我的css在哪儿? whyy是错误"资源被解释为样式表但是使用MIME类型text / plain转移:"当我有我的内容时出现输入main.go处理??

1 个答案:

答案 0 :(得分:4)

您的基本问题非常简单:您需要Content-Type而不是Content Type

但是,有一种更好的方法可以将MIME类型与Go中的文件扩展名匹配,特别是mime标准库包。我强烈建议您使用它。

相关问题