How do I serve CSS and JS in Go
I added a link to my apache servers css dir into the head section of my template files. I keep the template and data files used by any go application under dir that the go application is running from. In this instance cgi-bin.
The template uses the css from my apache server assets/css
directory :
<link rel="stylesheet" href="/assets/css/main.css" />
go apps run from my cgi-bin dir
sytle sheets are served from my apache assets/css dir
http.Handle("/", 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.