7

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

0

1 Answer 1

13

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>
Sign up to request clarification or add additional context in comments.

1 Comment

I have copied the exact structure you are using but I'm still getting 404 not found and image might help: imgur.com/a/J2ep0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.