I am making a small self-contained service in Go. The UI requires a few JS libraries, so I figured, I would use http.FileServer
to serve the JS files from node_modules
router := chi.NewRouter()
router.Use(middleware.RequestID)
router.Use(middleware.RealIP)
router.Use(middleware.Logger)
router.Use(middleware.Recoverer)
router.Use(middleware.Timeout(60 * time.Second))
router.Get("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
})
router.Get("/node_modules/", func(w http.ResponseWriter, r *http.Request) {
http.StripPrefix("/node_modules/", http.FileServer(http.Dir("node_modules")))
})
... more routes added here for the API ...
listen = ":8080"
log.Infof("listening on %s", listen)
http.ListenAndServe(listen, router)
When I try to do
<script src="node_modules/jquery/dist/jquery.min.js"></script>
In my UI though, I get a 404. The node_modules directory is there and the file exists. What am I doing wrong?
Solved. The pattern was missing a wildcard "/node_modules/*" works. Also, for some reason wrapping a Handler in a HandlerFunc didn't work (returned 000 status and no content). So the resulting route looks like this
router.Handle(
"/node_modules/*",
http.StripPrefix("/node_modules/", http.FileServer(http.Dir("node_modules"))),
)