首页 > 解决方案 > 无法在 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))

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

标签: cssgo

解决方案


您必须正确设置响应中的 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)
 })

推荐阅读