Reputation: 33
I'm trying to serve static files with Go, after following a few tutorials and other SO answers (here and here) I've arrived at the below code. I have researched numerous other similar questions, but the answers aren't working for me. I'm implementing my routing slightly different than most of the other questions, so I wonder if there's a subtle issue there that's causing the problem, but unfortunately my Go skills aren't polished enough to see what it is. My code is below (I've excluded the code for the handlers as it shouldn't be relevant).
router.go
package main
import (
"net/http"
"github.com/gorilla/mux"
)
func NewRouter() *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
var handler http.Handler
handler = route.HandlerFunc
handler = Logger(handler, route.Name)
router.
Methods(route.Method).
Path(route.Path).
Name(route.Name).
Handler(handler)
}
// This should work?
fs := http.FileServer(http.Dir("./static"))
router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))
return router
}
routes.go
package main
import (
"net/http"
"web-api/app/handlers"
)
type Route struct {
Name string
Method string
Path string
HandlerFunc http.HandlerFunc
}
type Routes []Route
var routes = Routes{
Route{
"Index",
"GET",
"/",
handlers.Index,
},
Route{
"Login",
"GET",
"/login",
handlers.GetLogin,
},
Route{
"Login",
"POST",
"/login",
handlers.PostLogin,
},
}
main.go
...
func main() {
router := NewRouter()
log.Fatal(http.ListenAndServe(":8080", router))
}
My file structure is setup as:
- app
- main.go
- router.go
- routes.go
- static/
- stylesheets/
- index.css
For some reason the browser can't access localhost:8080/static/stylesheets/index.css
Upvotes: 1
Views: 1803
Reputation: 121189
File paths are relative to the current working directory, not to source code file that references the path.
The application's file server configuration assumes that the app
directory is the current working directory. Change directory to the app
directory before running the application.
Upvotes: 2