0

Now I have 3 files and a folder in the same directory like the following. index.html will request the .css, .js(ReactJS) and images inside the folder /img.

enter image description here

After quite a lot of search and try, I know that I can use the following to make a file server to serve the / url request for files inside client/index.

http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("client/index"))))

It works well. But it only serve static files and I want to make some change to the html file before transferring out such as modifying a value in a tag <input id='projectId' type='hidden' value={{.projectId}}/>. Therefore, I need to register a HandleFunc('/', handler) to execute the html template but the url / is already used for implementing the file server.

What is the proper way to modify the html dynamically while also serving requests to the file system for the files (.css, .js and images inside the folder img)?

server / pghndler / index / index.go

package index

func RegisterHandlers() {
    http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("client/index"))))
    http.HandleFunc("/login", loginHandler)
}

1 Answer 1

1

It seems to me that the easiest way (less code) is to pretend as if your static files are in different directory, say "static". This means that you have to change the path in html file(s) where you refer to them, ie where you had

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

you replace it with

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

Then in your server code you can have an handler for path static and still use the / for dynamic stuff, ie

func main() {
    http.HandleFunc("/", hh_root)
    http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("/home/Casper/public/client/index/"))))
    http.ListenAndServe(":8080", nil)
}

func hh_root(w http.ResponseWriter, r *http.Request) {
    // generate response from template
}

It is common to organize web resources into directories like "css" and "js" so perhaps it makes sense to use these for fake paths - then when your app grows and you wish to organize it better, it is easier to do.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.