How do I serve CSS and JS in Go

http.Handle("https://stackoverflow.com/", http.FileServer(http.Dir("css/")))

Would serve your css directory at /. Of course you can serve whichever directory at whatever path you choose.

You probably want to make sure that the static path isn’t in the way of other paths and use something like this.

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

Placing both your js and css in the directory static in your project. This would then serve them at domain.com/static/css/filename.css and domain.com/static/js/filename.js

The StripPrefix method removes the prefix, so it doesn’t try to search e.g. in the static directory for static/css/filename.css which, of course, it wouldn’t find. It would look for css/filename.css in the static directory, which would be correct.

Leave a Comment