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類型處理??
請點擊上面的鏈接查看我打開我的網頁時看到的內容^ –
另請參閱https://github.com/golang/go/wiki/HttpStaticFiles –