In my html I'm trying to include JS using
<script src="/js/app.js"></script>
I have also tried relative path (from server location)
<script src="js/app.js"></script>
and relative from the html file
My file structure
-js
app.js
-templates
index.html
hub.go
main.go
main.go is the server
func main() {
http.HandleFunc("/", rootHandler)
http.ListenAndServe(":8080", nil)
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "Templates/index.html")
}
Am I missing something do I have to server css/js through server? or should the simple html work
To serve files via http, define a FileServer for a directory and route it to, for example, "/assets/"
using http.Handle
.
Following setup should work for you:
directory structure:
├── assets/
│ ├── js
│ └── css
├── templates/
└── main.go
main.go
func main() {
http.HandleFunc("/", rootHandler)
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets"))))
http.ListenAndServe(":8080", nil)
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "templates/index.html")
}
in your template file:
<script src="/assets/js/app.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With