How to call a subpath endpoint in Go without call main path?

Viewed 43

I'm having an issue with Golang using gorilla/mux.

I've declared an endpoint and certain subpath, but when I try to call the subpath BEFORE call it's main path, it returns me a 404 error.

So, there's my schema:

on main.go: services.StartRestService()

on services package:

func StartRestService() {
    log.Println("Loading Rest Service")

    router := mux.NewRouter()
    router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { mainHandleRequests(w, r, router) }).Methods("GET")
    http.Handle("/", router)

    log.Fatal(http.ListenAndServe(":8083", router)) 
}

on another go file in the same services package:

func homePage(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Welcome to the HomePage!")
    fmt.Println("Endpoint Hit: homePage")
}

func pong(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Pong!")
    fmt.Println("Endpoint Hit: pong")
}

func mainHandleRequests(w http.ResponseWriter, r *http.Request, router *mux.Router) {
    homePage(w, r)
    router.HandleFunc("/ping", pong)
}

Running my application, if I try to call http://localhost:8083/ping it returns me 404 not found. Only if I call http://localhost:8083, and after that I call the ping endpoint, it works.

What is wrong?

1 Answers

Yes, the router is unaware of the /ping endpoint until mainHandleRequests is called once.

So, the router should be set up and then not touched or changed in any way by incoming calls.

I have restructured your code a little:

func homePageHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Welcome to the HomePage!")
    fmt.Println("Endpoint Hit: homePage")
}

func pongHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Pong!")
    fmt.Println("Endpoint Hit: pong")
}

func main() {
    log.Println("Loading Rest Service")

    router := mux.NewRouter()

    router.Path("/").Methods(http.MethodGet).HandlerFunc(homePageHandler)
    router.Path("/ping").Methods(http.MethodGet).HandlerFunc(pongHandler)

    log.Fatal(http.ListenAndServe(":8083", router))
}
Related