【问题标题】:golang Resource interpreted as Stylesheet but transferred with MIME type text/plaingolang 资源解释为样式表,但使用 MIME 类型 text/plain 传输
【发布时间】:2018-03-19 06:48:56
【问题描述】:

我在使用 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在哪里??为什么在我处理 main.go 中的内容类型时出现错误“资源解释为样式表但使用 MIME 类型文本/纯文本传输:”??

【问题讨论】:

标签: html css go glide-golang


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    正如“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)
    }
    

    【讨论】:

      猜你喜欢
      • 2013-06-17
      • 2020-05-06
      • 2012-05-20
      • 2017-06-03
      • 2014-11-19
      • 2014-05-26
      • 2013-05-04
      • 2011-12-13
      • 2017-10-12
      相关资源
      最近更新 更多