2017-10-07 5 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 어디있어 ?? whyy는 "리소스가 Stylesheet로 해석되었지만 MIME 유형이 text/plain으로 전송 됨 :"이라는 오류입니다. main.go의 내용 유형이 처리되는 동안 처리됩니까 ??

+0

내 웹 페이지를 열 때 표시되는 내용을 보려면 위 링크를 클릭하십시오^ –

+1

https://github.com/golang/go/wiki/HttpStaticFiles도 참조하십시오. –

답변

2

기본 문제는 매우 간단합니다. Content Type 대신 Content-Type이 필요합니다.

그러나 Go 형식의 파일 확장자 인 MIME 유형 (특히 mime 표준 라이브러리 패키지)을 비교하는 더 좋은 방법이 있습니다. 나는 당신이 그것을 사용할 것을 강력히 제안 할 것이다.