英文:
why i can't connect css file using gorilla/mux.Router net/http.Handle
问题
我查看了所有类似的问题,并按照其中的说明连接了文件,但尽管如此,文件仍然无法工作。
我不知道该怎么办,我做错了什么。
main.go
func main() {
    r := mux.NewRouter()
    http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
    r.HandleFunc("/index", index)
    http.ListenAndServe(":8080", r)
}
func index(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "./static/html/test.html")
}
test.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <link rel="stylesheet" type="text/css" href="/static/css/test.css" />
    </head>
    <body class="sb-nav-fixed">
        asdfasd
    </body>
</html>
test.css
body{
    height: 100%;
    width: 100%;
    background-color: brown;
}
英文:
I looked at all similar questions and connected the file as it was said there, but despite this, the file does not work.
I don't know what to do, what did I do wrong
main.go
func main() {
	r := mux.NewRouter()
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
	r.HandleFunc("/index", index)
	http.ListenAndServe(":8080", r)
}
func index(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, "./static/html/test.html")
}
test.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <link rel="stylesheet" type="text/css" href="/static/css/test.css" />
    </head>
    <body class="sb-nav-fixed">
        asdfasd
    </body>
</html>
test.css
body{
    height: 100%;
    width: 100%;
    background-color: brown;
}
答案1
得分: 1
你不能混合使用net/http.Handle和gorilla/mux.Router。
你可以像这样做:
func main() {
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
	http.HandleFunc("/index", index)
	http.ListenAndServe(":8080", nil)
}
func index(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, "./static/html/test.html")
}
或者像这样:
func main() {
	r := mux.NewRouter()
	r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
	r.HandleFunc("/index", index)
	http.ListenAndServe(":8080", r)
}
func index(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, "./static/html/test.html")
}
英文:
you can't mix net/http.Handle and gorilla/mux.Router
you can do it like this
func main() {
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
	http.HandleFunc("/index", index)
	http.ListenAndServe(":8080", nil)
}
func index(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, "./static/html/test.html")
}
or like this
func main() {
	r := mux.NewRouter()
	r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
	r.HandleFunc("/index", index)
	http.ListenAndServe(":8080", r)
}
func index(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, "./static/html/test.html")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论