Serving SPA and routing for endpoints

46 views
Skip to first unread message

Hugh Myrie

unread,
Mar 10, 2021, 9:53:13 PM3/10/21
to golang-nuts
I am trying to follow the example as described in the link: https://github.com/gorilla/mux, to serve a single page application (Angular) from Go and also to route my endpoints.

My endpoints are not being routed although the index.html is served. My main function has the following format:

//===
func main() {
getParams()
r := mux.NewRouter()
// Routes consist of a path and a handler function.

//-----------------------------------------------
    usersR := r.PathPrefix("/users").Subrouter()
    usersR.Path("").Methods(http.MethodPost).HandlerFunc(createUser)
    usersR.Path("/{id}").Methods(http.MethodGet).HandlerFunc(getUserByID)
    usersR.Path("/`{id}").Methods(http.MethodPut).HandlerFunc(updateUser)
    usersR.Path("/{id}").Methods(http.MethodDelete).HandlerFunc(deleteUser)

    productR := r.PathPrefix("/product").Subrouter()
    productR.Path("").Methods(http.MethodGet).HandlerFunc(getProductInfo)
    productR.Path("/{id}").Methods(http.MethodGet).HandlerFunc(getProductID)

   
c := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
        AllowCredentials: true,
    })
handler := c.Handler(r)
r.HandleFunc("/stockcount", getStock)
spa := spaHandler{staticPath: "public", indexPath: "index.html"}
r.PathPrefix("/{_:.*}").Handler(spa)   

ip := GetOutboundIP()
portAvailable(port)
fmt.Printf("Start listening on %s // %s \n", ip, port)
http.ListenAndServe(":"+port, handler)
}

//===========

All request seems to be handled by the spaHandler so I received a bad request when trying to reach an endpoint.

500 (Internal Server Error)

Also how do I re-route for path "/home" to the index.html?
Reply all
Reply to author
Forward
0 new messages