为什么我不能使用 gorilla/mux.Router net/http.Handle

我查看了所有类似的问题并按照那里所说的那样连接了文件,但尽管如此,该文件还是不起作用。我不知道该怎么办,我做错了什么


主程序


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")

}

结构体


测试.html


<!DOCTYPE html>

<html>

    <head>

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

    </head>

    <body class="sb-nav-fixed">

        asdfasd

    </body>

</html>

测试.css


body{

    height: 100%;

    width: 100%;

    background-color: brown;

}


白猪掌柜的
浏览 107回答 1
1回答

潇湘沐

net/http.Handle你不能混合gorilla/mux.Router你可以这样做func main() {&nbsp; &nbsp; http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))&nbsp; &nbsp; http.HandleFunc("/index", index)&nbsp; &nbsp; http.ListenAndServe(":8080", nil)}func index(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; http.ServeFile(w, r, "./static/html/test.html")}或者像这样func main() {&nbsp; &nbsp; r := mux.NewRouter()&nbsp; &nbsp; r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))&nbsp; &nbsp; r.HandleFunc("/index", index)&nbsp; &nbsp; http.ListenAndServe(":8080", r)}func index(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; http.ServeFile(w, r, "./static/html/test.html")}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go