Answer the question
In order to leave comments, you need to log in
Gorilla Mux: doesn't take value in vars := mux.Vars(r) Golang?
Good afternoon.
Please tell me, I am writing an Http server that supports the CRUD API. I ran into a problem that the GetPost request - which should search by the Id of the post - does not pull the Id from the URL string. What does it have to do with checking in PostMan, if you enter the line at the end / "Id number", then the request is processed, and if / {Id}, as written in the handler, then the request is not processed. I can't understand what is the reason. The function does not work at all.
Part of the handler code:
type postHandler struct {
Services services.Store
}
func (h *postHandler) NewRouter() *mux.Router {
r := mux.NewRouter()
r.HandleFunc("/post", h.CreatePost). Methods("POST")
r.HandleFunc("/post/{Id}", h.GetPost).Methods("GET")
r.HandleFunc("/posts", h.GetAll).Methods("GET")
r.HandleFunc("/post/{Id}", h.DeletePost).Methods("DELETE")
r.HandleFunc("/ post/{Id}", h.UpdatePost).Methods("PUT")
return r
}
func (h *postHandler) GetPost(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key := vars["Id"]
idInt, _ := strconv.Atoi(key)
res, err := h.Services.GetId(idInt)
if err != nil {
w.Write([]byte("could not get post"))
return
}
json.NewEncoder(w).Encode(&res)
}
Accordingly, the rest of Delete and Update have a similar problem.
I will be glad to any advice.
Answer the question
In order to leave comments, you need to log in
Through mux.Vars you can only extract what's in the URL, i.e. parts of the URL, and the parameters must be retrieved via r.URL.Query().Get("param_name")
Let's look at an example from a real task.
The URL contains the English name of the category (chairs), as well as the width and height filter parameters.
https://domain.com/products/chairs?height=200&width=100
r.HandleFunc("/products/{category_handle}", h.ShowProducts).Methods("GET")
// из извлекаем из URL категорию
vars := mux.Vars(r)
categoryHandle := vars["categoryHandle"]
// получаем параметры
height, _ := strconv.Atoi(r.URL.Query().Get("height"))
width, _ := strconv.Atoi(r.URL.Query().Get("width"))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question