2
votes

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

3
Try using absolute paths in the html. i.e. "/assets... instead of "./assets..., same with the register js file.mkopriva
i tried that...but didnt workEmmanuel Thomas
did you try removing the ./ altogether?Hikash
yes, removed "./ " from everywhere, here is how the links look like now <script src="/assets/js/core/popper.min.js"></script> <script src="/assets/js/core/bootstrap.min.js"></script> <script src="/assets/js/plugins/perfect-scrollbar.jquery.min.js"></script> <script src="/assets/js/plugins/moment.min.js"></script>Emmanuel Thomas
Try clearing your browser cache and then try again.p9sh

3 Answers

2
votes

try

gor:= mux.NewRouter().StrictSlash(true)

fs := http.FileServer(http.Dir("./static"))
gor.PathPrefix("/transaction").Handler(fs)

it probably should work if it doesnt just try reading documentation for http.FileServer

2
votes

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.

1
votes

did you try serving a handler fot your resources folder?

sdir := "/resources/"
myRouter.PathPrefix(sdir).Handler(http.StripPrefix(sdir, http.FileServer(http.Dir("."+sdir))))

this allow you to access the foloder as a subdomain.