CSS in Golang not being served

I’m trying to include CSS in my Golang application to render it on a Web browser.

In order to do that, I’ve created a file structure as follows :

  • Asset (containing all sorts of assets for my app)
  • css (containing a single styles.css file)
  • HTML (containing all my .html files)

They are located in the main folder, which also contains a main.go file and .txt files that serve as a library.

Also see picture below:

enter image description here

Inside my HTML files, I’ve included a stylesheet as follows :

<link rel="stylesheet" type="text/css" href="/css/styles.css">

and Inside my main.go file I’ve included this code to serve the files to the webserver :

css := http.FileServer(http.Dir("css"))
http.Handle("/css/", http.StripPrefix("/css/", css))

Although, I seem to be missing something, and after extensive search I’m still not finding it. I did find a question relative to that here, but the question was very poorly written and the answer too specific.

For reference, here’s my main function in main.go :

func main() {

font("standard")

http.HandleFunc("/program", handler)
http.HandleFunc("/400", charHandleError)
http.HandleFunc("/500", internalServerError)

fs := http.FileServer(http.Dir("Asset"))
http.Handle("/static/", http.StripPrefix("/static/", fs))

css := http.FileServer(http.Dir("css"))
http.Handle("/css/", http.StripPrefix("/css/", css))

http.Handle("/", noHandler())

addr := ":8001"

go func() {
    log.Println("Server started on http://localhost" + addr + "/program")
}()

http.ListenAndServe(addr, nil)

}

  • Unless you embed the assets within your binary, the source location of the css files have no relation to your compiled program, and are only relative to your current working directory. Where and how are you executing the application?

    – 

Leave a Comment