2017-10-07 16 views
0

golangを使用して自分のWebページを開発する際に問題があります。 サーバーファイル(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) 
} 

しかし、私は私のページが右側ロードされないのはなぜsee screenshot 見るものhttp://localhost:8080/templates/home.html これを入力すると?私のCSSはどこですか? whyyはエラーです。「リソースはスタイルシートとして解釈されますが、MIMEタイプtext/plainで転送されます:」というメッセージが表示されます。

+0

上記のリンクをクリックして、自分のウェブページを開いたときに表示される内容をご覧ください^ –

+1

https://github.com/golang/go/wiki/HttpStaticFilesも参照してください –

答えて

2

基本的な問題は非常に簡単です。Content Typeの代わりにContent-Typeが必要です。

しかし、Goのファイル拡張子、具体的にはmime標準ライブラリパッケージにMIMEタイプを一致させるより良い方法があります。私は強くそれを使用することをお勧めします。

関連する問題