Home > Mobile >  Trouble with httpRouter serving static files
Trouble with httpRouter serving static files

Time:05-21

I have searched for existing threads and did what they said to no success.

When I access my go app at localhost:8081/ it is successfully loading index.html but it is not finding the js file so nothing is displayed, I am trying to serve a react app with go. The problem is with the ServeFiles function as that is not working properly.

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

enter image description here

CodePudding user response:

Refer to this github link: https://github.com/julienschmidt/httprouter/issues/7

I added a second httprouter instance, and fed the static files through that, then set the first httprouter NotFound to the second httprouter

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