我在使用 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)
鸿蒙传说
至尊宝的传说
相关分类