I wrote a golang webserver and I was serving static resources before, but after changing my project structure, that no longer works.
This is my project structure
ProjectFolder/
node_modules/
scripts/
test.es6.js
server/
handlers.go
main.go
routes.go
static/
scripts/
test.js
test.js.map
Gruntfile.js
index.html
package.json
This is my index.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javacript" src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.1/backbone-min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script type="text/javascript" src="/static/scripts/test.js"</script>
<body>
<div id="chart"></div>
</body>
This is my routes.go
func NewRouter() *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(route.HandlerFunc)
}
for pathName, pathValue := range staticPaths {
pathPrefix := "/" + pathName + "/"
fmt.Println(pathPrefix)
fmt.Println(pathValue)
router.PathPrefix(pathPrefix).Handler(http.StripPrefix(pathPrefix, http.FileServer(http.Dir(pathValue))))
}
// router.PathPrefix("/static/scripts").Handler(http.FileServer(http.Dir("./static/scripts/")))
return router
}
var staticDirectory = "/static"
var staticPaths = map[string]string{
"scripts": staticDirectory + "/scripts/",
}
var routes = Routes{
Route{
"Index",
"GET",
"/",
Index,
},
}
When I hit localhost:8200, I get a 404 when loading test.js, but index.html is getting hit.
Before, this was an issue with not using http.FileServer to serve static resources, but I am using it now.
I've tried other variations of the path in index.html
src= "static/scripts/test.js"
src= "../static/scripts/test.js"
What is going on?
EDIT-
I've simplified everything and tried to do this
router.Handle("../static/scripts", http.StripPrefix("../static/scripts", http.FileServer(http.Dir("."))))
But that still isn't working.