【发布时间】:2020-06-04 00:20:34
【问题描述】:
我最近开始学习围棋,我想开发一个简单的网站。但是我不知道如何为这个网站使用外部 CSS 文件。
这是我的目录结构:
./
main.go
static/
css/
home.css
templates/
home.html
这是我的 main.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)
}
}
在 home.html 中,我在标题中添加了这个:
<link rel="stylesheet" href="/css/home.css">
在浏览器中调试时似乎找到了该文件,但MIME类型有错误:Browser Console Screenshot
我认为这两行可以解决这个问题,但显然它没有:
fs := http.FileServer(http.Dir("static/"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
有人知道我做错了什么吗?
【问题讨论】: