css - 无法在 Go webapp 中提供外部 CSS 文件
问题描述
我最近开始学习围棋,我想开发一个简单的网站。但是我不知道如何为这个网站使用外部 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 类型出现错误:浏览器控制台屏幕截图
我认为这两行可以解决这个问题,但显然它没有:
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)
})
推荐阅读
- javascript - 函数不仅调用一次
- javascript - 将数据动态推送到 Highmaps
- http-headers - Apple Watch 优化的电子邮件不起作用
- pytorch - 作为学习率调度程序的线性衰减(pytorch)
- javascript - 如何使用请求获取 Javascript 页面的完整 HTML 内容?
- python - 如何检查一个元素是否在子列表中,然后打印子列表
- json - Flutter 仅从响应中打印一个值
- cassandra - CassandraCQLUnit 给出空会话
- laravel - Laravel 推送器监听私人事件:错误 403 页面被禁止
- python - 在 TensorFlow2 中结合来自不同“网络”的梯度