Reputation: 636
I'm using chi
as router.
My files tree is:
-cmd
- web
- main.go and some other go files here*
- static
- assets
- some html files here*
I have my routes set up like so:
mux := chi.NewRouter()
mux.Use(middleware.Logger)
mux.Use(middleware.SetHeader("Cache-Control", "no-store"))
mux.Get("/about", app.serveFile)
mux.Get("/login", app.serveFile)
mux.Get("/register", app.serveFile)
mux.Get("/", app.serveFile)
fileServer := http.FileServer(http.Dir("./cmd/web/static/assets/"))
mux.Handle("/assets/", http.StripPrefix("/assets/", fileServer))
Here is a snippet of my index.html file:
<link rel="shortcut icon" href="/assets/images/favicon.png" type="image/x-icon">
<link rel="stylesheet" href="/assets/css/style.css">
Edit 1:
I'm using make
as my build tool. Here is the rule to build and run the web:
build_web:
@echo "building projectName web..."
@go build -o ${BINARY_DIR}/${WEB_BINARY_NAME} ./cmd/web/*.go
@echo "projectName web built"
run_web:
@echo "running projectName web..."
@./${BINARY_DIR}/${WEB_BINARY_NAME} -environment ${PREF_ENV} -port ${WEB_PORT}
Running the server on localhost, HTML pages are rendered but css rules are not applied. I checked the network tab of developer tools and it shows status code 200 for all assets (css/js/images). Same was reported through the middleware logger, a 200 status code for all files in the assets folder. I've tried all stackoverflow answers I could stumble upon, still no luck.
Upvotes: 0
Views: 1200
Reputation: 636
How I eventually fixed this:
I entered <address>/assets/css/style.css
in my browser and it returned 404 not found page.
Though it shows a status code 200 in the server log, but the file was not actually served. So I changed the path on my fileserver from /assets/
to /assets/*
(here: mux.Handle("/assets/*", http.StripPrefix("/assets/", fileServer))
) and it worked,
Thanks to @bayta-darrel and @mkopriva for their help
Upvotes: 3