2017-10-07 408 views
0

我在使用golang開發我的網頁時遇到問題。 服務器文件(main.go):golang將資源解釋爲樣式表,但使用MIME類型傳輸text/plain

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在哪裏?爲什麼是錯誤「資源解釋爲樣式表,但傳輸與MIME類型文本/純:」出現,而我有我的內容在main.go類型處理??

+0

請點擊上面的鏈接查看我打開我的網頁時看到的內容^ –

+1

另請參閱https://github.com/golang/go/wiki/HttpStaticFiles –

回答

2

您的基本問題很簡單:您需要Content-Type而不是Content Type

但是,有一種更好的方法可以將MIME類型與Go中的文件擴展名匹配,特別是mime標準庫軟件包。我強烈建議你使用它。

相關問題