I am trying to test a handler, the handler is below:
router.HandleFunc("/address/{id}", DeletePerson).Methods("DELETE")
The request that I created was:
request, _ := http.NewRequest("DELETE", "/address/2", nil)
DeletePerson(response, request)
using github.com/gorilla/mux I attempted to extract the "id" with
params = mux.Vars(request)
item := params["id"]
returns: params = map[] and item = ""
However, if I call DeletePerson with the curl command:
curl -X DELETE http://localhost:8000/address/2
I get: params = map["id"] and item = "2"
HOW Do I construct a URL request that get the results like Curl?
If you call DeletePerson
directly, the request doesn't pass through the router, which parses the parameters in the request path.
Also, http.NewRequest
returns a client request. Either add scheme and host to the URL and pass the request to http.Client.Do
, or use httptest.NewRequest to create a server request directly.
NewRequest returns a new incoming server Request, suitable for passing to an http.Handler for testing.
request := httptest.NewRequest("DELETE", "/address/2", nil)
mux.ServeHTTP(response, request)
I think the problem is that you don't put the full URL in the request. And I guess that you ignore the error while executing the request. If you don't put the full URL it will complains something like this: panic: Delete /address/2: unsupported protocol scheme ""
The following code works OK in my machine:
package main
import "net/http"
func main() {
r, err := http.NewRequest("DELETE", "http://localhost:8080/address/2", nil)
if err != nil {
panic(err)
}
if _, err := http.DefaultClient.Do(r); err != nil {
panic(err)
}
}
Hope this helps :)