CSS and JS doesn't work with Golang HTTP server

Hello,
I started using Golang and not really used to the lack of semicolons. :slight_smile:
I’m trying to get my website working and my CSS and JS doesn’t work at all.

Hi. Could you follow these instructions to post code on the forum. How to post code on this forum

You will need to have a handler for those. You can use

fs := http.FileServer(http.Dir("static"))
  http.Handle("/static/", http.StripPrefix("/static/", fs))

It is a bit confusing with all these static. First line just says. Create a file server for the directory called static.

On next line is a handler for all paths beginning with static. The strip prefix is to remove the static path before finding the file in the directory specified above. If you don’t use strip prefix and asked for /static/test.jpg would it try to find this path in the /static folder. That is /static/static/test.jpg

1 Like

Also, remove http.Handle call from http handler because your file server will be initialized at every call of the handler. Do this once somewhere in main func after the other handle func.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.