I'm trying to add a subrouter to my router code :
router := mux.NewRouter()
baseRouter := router.PathPrefix("/api/v1").Subrouter()
managementRouter := baseRouter.PathPrefix("/managing/{id}").Subrouter()
managementRouter.Use(auth.ManagingMiddleware)
managementRouter.HandleFunc("/add-employees", management.AddEmployeesToOrganization).Methods("POST")
The goal is to force the client to give an id
variable on each call to managementRouter
functions.
Although, when i send a request like this :
/api/v1/managing/627e6f7e05db3552970e1164/add-employees
... I get a 404. Am I missing something or is it just not possible ?
CodePudding user response:
Ok so I found a solution in my dream last night haha
Basically the problem with the following prefix :
managementRouter := baseRouter.PathPrefix("/managing/{id}").Subrouter()
Is that the router has no way of knowing where the id
field stops. So when we access an endpoint with for example this url : /api/v1/managing/627e6f7e05db3552970e1164/add-employees
, the router believes that the {id}
variable is literally 627e6f7e05db3552970e1164/add-employees
and doesn't match any route after it.
So the solution I found is to tell the router what comes after the variable. For that, you just add a slash after the variable :
managementRouter := baseRouter.PathPrefix("/managing/{id}/").Subrouter()