Etrafa baktım ve sonra ne olduğuma özel bir şey bulamadım. Go'nun standart kütüphanesini kullanarak bir API yapıyorum. Kaynak dosyalarımı sunarken, CSS dosyalarım, text/css
olarak göndermek istediğimde text/plain
olarak gönderilir.Golang: CSS dosyaları Content-Type ile gönderiliyor: text/plain
Resource interpreted as Stylesheet but transferred with MIME type text/plain: "http://localhost:3000/css/app.css".
main.go
package main
import (
"bufio"
"log"
"net/http"
"os"
"strings"
"text/template"
)
func main() {
templates := populateTemplates()
http.HandleFunc("/",
func(w http.ResponseWriter, req *http.Request) {
requestedFile := req.URL.Path[1:]
template := templates.Lookup(requestedFile + ".html")
if template != nil {
template.Execute(w, nil)
} else {
w.WriteHeader(404)
}
})
http.HandleFunc("/img/", serveResource)
http.HandleFunc("/css/", serveResource)
log.Fatal(http.ListenAndServe(":3000", nil))
}
func serveResource(w http.ResponseWriter, req *http.Request) {
path := "public" + req.URL.Path
var contentType string
if strings.HasSuffix(path, ".css") {
contentType = "text/css"
} else if strings.HasSuffix(path, ".png") {
contentType = "image/png"
} else {
contentType = "text/plain"
}
f, err := os.Open(path)
if err == nil {
defer f.Close()
w.Header().Add("Content Type", contentType)
br := bufio.NewReader(f)
br.WriteTo(w)
} else {
w.WriteHeader(404)
}
}
func populateTemplates() *template.Template {
result := template.New("templates")
basePath := "templates"
templateFolder, _ := os.Open(basePath)
defer templateFolder.Close()
templatePathRaw, _ := templateFolder.Readdir(-1)
templatePaths := new([]string)
for _, pathInfo := range templatePathRaw {
if !pathInfo.IsDir() {
*templatePaths = append(*templatePaths,
basePath+"/"+pathInfo.Name())
}
}
result.ParseFiles(*templatePaths...)
return result
}
ben text/css
olarak gönderiyorum inanıyoruz:
konsol diyerek bana bir bilgi mesajı atar. Bunu yanlış mı görüyorum?
@Karrot Kake sorunuzu yanıtladı. Ayrıca, [http.FileServer] (https://golang.org/pkg/net/http/#FileServer) 'ı da göz önünde bulundurun, içerik türünü algılar. – Mark
Bahse girerim bu çoğullu bir tutuktur. Şimdi 20 dakika boyunca bu hata ile mücadele ediyorum! – Karlom