Search code examples
httpgoserverassets

Serving static files in an HTTP server


I'm using golang as the backend for a medium-sized web app which has a few pages and a lot of CSS and javascript in different folders, I'm trying to serve the website using golang but only the index file loads , the other pages, javascript, CSS doest load. since my HTML files, all are different from each other I'm not using templates

here is the file structure

-static 
    -assets
        -css(folder with subfolders)
        -js(folder with subfolders)
    -pages (folder with differnt html pages)
         -signup.html
         -dashboard.html
    -index.html
    -register_bundle.js
-main.go
func handlerequests (){
 myRouter := mux.NewRouter().StrictSlash(true)
 myRouter.Handle("/", http.FileServer(http.Dir("./static")))
 myRouter.HandleFunc("/transaction", transactionHandler)
 log.Fatal(http.ListenAndServe(":8080",myRouter))
}

my HTML files have links like these, (showing index.html)

<!-- CSS Files -->
  <link href="./assets/css/bootstrap.min.css" rel="stylesheet" />
  <link href="./assets/css/paper-dashboard.css?v=2.1.1" rel="stylesheet" />
<!--JS files -->
  <script src="./assets/demo/demo.js"></script>
  <!--Main Script file for the page  -->
  <script src="./register_bundle.js"></script>

errors shown here

enter image description here

enter image description here


Solution

  • The problem is browser cannot find those JS and CSS files.

        fs := http.FileServer(http.Dir("./static"))
        MUXRouter.Handle("/", fs)
        MUXRouter.PathPrefix("/assets/").Handler(fs)
        MUXRouter.PathPrefix("/pages/").Handler(fs)
        MUXRouter.Handle("/register_bundle.js", fs)
    

    That way a GET request to http://[host]:[port]/css/style.css will return style.css from the relative ./static/css/ directory. The above code is working in my sample program.