无法在 Go Web 应用程序中提供外部 CSS 文件



我最近开始学习围棋,我想开发一个简单的网站。但是我不知道如何为本网站使用外部CSS文件。

这是我的目录结构:

./
main.go
static/
css/
home.css
templates/
home.html

这是我的主.go文件:

package main
import (
"html/template"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", homeHandler)
fs := http.FileServer(http.Dir("static/"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
log.Println("Listening on :8080...")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, "home")
}
func renderTemplate(w http.ResponseWriter, tmpl string) {
t, err := template.ParseFiles("templates/" + tmpl + ".html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = t.Execute(w, nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}

在家里.html我在标题中添加了这个:

<link rel="stylesheet" href="/css/home.css">

在浏览器中调试时,似乎找到了该文件,但 MIME 类型存在错误: 浏览器控制台屏幕截图

我以为这两行可以解决这个问题,但显然它没有:

fs := http.FileServer(http.Dir("static/"))
http.Handle("/static/", http.StripPrefix("/static/", fs))

有人知道我做错了什么吗?

您必须在响应中正确设置 Content-Type 标头。如果没有内容类型,大多数浏览器将不会执行 css。像下面这样的东西应该有效,但这本质上只是一个草图:

http.HandleFunc("/static/",func(wr http.ResponseWriter,req *http.Request) {
// Determine mime type based on the URL
if req.URL.Path.HasSuffix(".css") {
wr.Header().Set("Content-Type","text/css")
} 
http.StripPrefix("/static/", fs)).ServeHTTP(wr,req)
})

最新更新