【问题标题】:Can't serve external CSS File in Go webapp无法在 Go webapp 中提供外部 CSS 文件
【发布时间】: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))

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

【问题讨论】:

    标签: css go


    【解决方案1】:

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

    【讨论】:

    • 感谢您的快速回复。我不得不使用if strings.HasSuffix(r.URL.String(), ".css") {},并将html中的css链接更改为&lt;link rel="stylesheet" href="/static/css/home.css"。现在它起作用了!谢谢。
    猜你喜欢
    • 2019-04-11
    • 2016-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 2017-09-21
    • 1970-01-01
    相关资源
    最近更新 更多