I'm trying to set up a route to serve my reactjs application.
I have my index.html and bundle.js in the public folder
/public/index.html
/public/bundle.js
I'm using go as my backend API, and also to serve my reactjs app.
I created a subroute for my app like:
r := mux.NewRouter()
app := r.Host("app.example.com").Subrouter()
So any request with app as the subdomain will be for my Reactjs app.
So now I have to serve every request regardless of the URL to my reactjs app.
Is path prefix what I need here?
I tried this:
app.PathPrefix("/").Handler(serveReact)
func serveReact(w http.ResponseWriter, r *http.Request) {
}
But I get this error:
cannot use serveReact (type func() http.Handler) as type http.Handler in argument to app.PathPrefix("/").Handler: func() http.Handler does not implement http.Handler (missing ServeHTTP method)
Your http handler needs a ServeHTTP
method. If you pass your function to http.HandlerFunc
, that will be introduced for you:
app.PathPrefix("/").Handler(http.HandlerFunc(serveReact))
func serveReact(w http.ResponseWriter, r *http.Request) {
}
The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler that calls f.
type HandlerFunc func(ResponseWriter, *Request)
// ServeHTTP calls f(w, r).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
f(w, r)
}
Similarly, you could use the mux router HandlerFunc
instead:
app.PathPrefix("/").HandlerFunc(serveReact)
func serveReact(w http.ResponseWriter, r *http.Request) {
}
This essentially performs both steps for you in a combined single step.