httpRouter 服务静态文件的问题

Trouble with httpRouter serving static files

我已经搜索了现有的话题并按照他们所说的做了,但没有成功。

当我在 localhost:8081/ 访问我的 go 应用程序时,它已成功加载 index.html 但它没有找到 js 文件,因此没有显示任何内容,我正在尝试使用 go 提供一个反应应用程序.问题出在 ServeFiles 函数上,因为它无法正常工作。

func RouteDefault(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
    index := template.Must(template.ParseFiles("static/index.html"))
    index.Execute(w, nil)
}

func main() {
    // BasicAuth username and password
    user := ""
    pass := ""

    DefaultUser()

    // HTTPRouter Settings and Routes
    router := httprouter.New()
    router.ServeFiles("/static/*filepath", http.Dir("static"))
    router.GET("/", RouteDefault)
    router.GET("/dashboard/", RouteDefault)
    router.GET("/about/", RouteDefault)
    router.GET("/signout/", RouteDefault)
    router.POST("/login/", BasicAuth(RouteLogin, user, pass))
    router.GET("/getusers/", JWTAuth(RouteGetUsers))
    router.POST("/newuser/", JWTAuth(RouteNewUser))
    router.POST("/deleteuser/", JWTAuth(RouteDeleteUser))
    router.POST("/mypassword/", JWTAuth(RouteMyPassword))
    router.POST("/upload/", JWTAuth(RouteUpload))
    router.GET("/getgraphs/", JWTAuth(RouteGetGraphs))
    router.POST("/graph/", JWTAuth(RouteGetGraph))
    router.POST("/deletegraph/", JWTAuth(RouteDeleteGraph))
    router.GET("/autologin/", JWTAuth(RouteAutoLogin))

    handler := cors.AllowAll().Handler(router)
    fmt.Println(http.ListenAndServe(":8081", handler))
}

参考这个githublink:https://github.com/julienschmidt/httprouter/issues/7

我添加了第二个 httprouter 实例,并通过它提供静态文件,然后将第一个 httprouter NotFound 设置为第二个 httprouter

static := httprouter.New()
static.ServeFiles("/*filepath", http.Dir("static"))
router.NotFound = static