使用 GO Gorilla mux 服务器应用 CSS 文件时出现 MIME 类型错误

我在使用 Gorilla Mux 在 GO 网络服务器中包含 css 文件时遇到问题。我在 Google Chrome 控制台中收到以下错误:


forum:1 Refused to apply style from 'http://localhost:8080/css/forum.css' because its MIME type ('text/plain') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

我知道很多人在使用 FileServer 时会因为处理"/"错误而失败,但这对我也不起作用。我的文件结构如下: 文件结构 当我运行服务器时,我在 cmd: 中执行go run src/main.go。我也尝试在src文件夹中运行它。但这也行不通。在 HTML 文件中,我添加了 css 文件


<link rel="stylesheet" type="text/css" href="/css/forum.css" />

我的 GO 代码如下。我尝试以两种方式处理 FileServer,其中一种在另一种上方被注释掉。两者都行不通。除了 FileServer,其他一切都在工作。


package main


import (

    "fmt"

    "net/http"

    "html/template"


    "github.com/gorilla/mux"

)


var templates *template.Template


func main() {

    r := mux.NewRouter()


    templates = template.Must(template.ParseGlob("src/templates/*.html"))

    cssHandler := http.FileServer(http.Dir("./static/css"))


    r.HandleFunc("/home", homeGetHandler).Methods("GET")

    r.HandleFunc("/home", homePostHandler).Methods("POST")

    r.HandleFunc("/forum", forumGetHandler).Methods("GET")

    r.HandleFunc("/forum", forumPostHandler).Methods("POST")


    http.Handle("/forum", r)

    http.Handle("/home", r)

    // http.Handle("/css/", http.StripPrefix("/src/static/css/", cssHandler))

    r.PathPrefix("/css/").Handler(http.StripPrefix("/src/static/css/", cssHandler))



    http.ListenAndServe(":8080", nil)

}


func homeGetHandler(w http.ResponseWriter, r *http.Request) {

    templates.ExecuteTemplate(w, "home.html", nil)

}


func homePostHandler(w http.ResponseWriter, r *http.Request) {

    r.ParseForm()

    comment := r.PostForm.Get("comment")

    fmt.Println(comment)

    http.Redirect(w, r,"/home", 302)

}


func forumGetHandler(w http.ResponseWriter, r *http.Request) {

    templates.ExecuteTemplate(w, "forum.html", nil)

}


func forumPostHandler(w http.ResponseWriter, r *http.Request) {

    r.ParseForm()

    comment := r.PostForm.Get("post")

    fmt.Println(comment)

    http.Redirect(w, r,"/forum", 302)

}

[解决方案] 我找到了答案:


http.Handle("/forum", r)

http.Handle("/home", r)

应该只是:


http.Handle("/",r)


烙印99
浏览 166回答 2
2回答

鸿蒙传说

什么是因为您使用错误的 MIME 类型为您的 css 文件提供服务,您应该为 css 设置正确的标题。利用:func serveCss(w http.ResponseWriter, r *http.Request) {&nbsp; // some code here&nbsp; w.Header().Add("Content-Type", "text/css")&nbsp; // some code here}

至尊宝的传说

问题是您的 csshandler 返回文件的内容,其中 Content-Type 设置为“text/plain”。您必须将其设置为“text/css”才能让浏览器将其解释为 CSS 文件。您可以在使用类似中间件的函数返回文件内容之前设置内容类型:func SetHeader(header,value string, handle http.Handler) func(http.ResponseWriter,*http.Request) {&nbsp; &nbsp;return func(w http.ResponseWriter,req *http.Request) {&nbsp; &nbsp; &nbsp; &nbsp;w.Header().Set(header,value)&nbsp; &nbsp; &nbsp; &nbsp;handle.ServeHTTP(w,req)&nbsp; &nbsp;}}r.PathPrefix("/css/").HandlerFunc(SetHeader("Content-Type","text/css",http.StripPrefix("/src/static/css/", cssHandler)))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go