为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
白猪掌柜的 2022-12-19 20:30:39
我查看了所有类似的问题并按照那里所说的那样连接了文件,但尽管如此,该文件还是不起作用。我不知道该怎么办,我做错了什么主程序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>测试.cssbody{    height: 100%;    width: 100%;    background-color: brown;}
查看完整描述

1 回答

?
潇湘沐

TA贡献1816条经验 获得超6个赞

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

}


查看完整回答
反对 回复 2022-12-19
  • 1 回答
  • 0 关注
  • 89 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信