Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serve static files via http with go

Tags:

go

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

like image 386
Higeath Avatar asked Apr 15 '17 11:04

Higeath


1 Answers

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>
like image 153
The F Avatar answered Nov 11 '22 11:11

The F