Emmanuel Thomas
Emmanuel Thomas

Reputation: 329

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

Upvotes: 3

Views: 3651

Answers (3)

Gautham J
Gautham J

Reputation: 133

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.

Upvotes: 3

i-am-a-pickle
i-am-a-pickle

Reputation: 31

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

Upvotes: 2

Camisamus
Camisamus

Reputation: 11

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.

Upvotes: 1

Related Questions