首页 > 解决方案 > 使用 GO 导入的 Style.css 出现 MIME 错误

问题描述

我刚开始学习围棋,我真正想做的一件事就是在围棋中制作网站。我看了一些教程并让网站正常工作,但我不知道如何添加样式。

我在 Internet 和 stackoverflow 上搜索了一些示例,但找不到真正适合我的示例(并且保持简单)。

下面是我最终得到的代码。但我认为我现在遇到了一个新问题,因为控制台中显示: 错误

我尝试了很多我在互联网上找到的解决方案,但没有一个有效,所以我很确定这是因为我在 go 中错误地导入了 css。

去(functions.go):

package main

import (
    "html/template"
    "net/http"
)

type IndexPage struct {
    Title string
    SubTitle string
}

func indexHandler(w http.ResponseWriter, r *http.Request){
    p := IndexPage{Title: "Pizza site", SubTitle: "everyone loves pizzas"} 
    t, _ := template.ParseFiles("index.html")
    t.Execute(w,p)
}

func main() {

    http.HandleFunc("/", indexHandler)
    http.Handle("/css/", http.FileServer(http.Dir("css")))
    http.ListenAndServe(":8080", nil)
}

html (index.html):

<html lang="nl">
<head>
  <meta charset="utf-8">
  <title>Pizzaaaaaaa</title>
  <link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
    <article>
        <h1>
            {{ .Title }}
            <span class="subtitle">{{ .SubTitle }}</span>
        </h1>
        <p>Some text</p>
    </article>
</body>
</html>

CSS ( /css/style.css )

*{
    color: rgb(250, 157, 157);
}

文件树

文件树

标签: cssgo

解决方案


当您尝试从此 url 访问 css 文件时,您的句柄返回 404:/css/*

用这个改变你的css句柄:

    http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("./css"))))

*你得到'text/plain',因为404是纯文本。


推荐阅读