我的删除处理程序:(我正在使用“ github.com/gorilla/mux”)
func DeletePerson(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
item := params["id"]
fmt.Println("Item = ", item)
...
在以下curl命令调用时返回Item =“ 2”:
curl -X DELETE http://localhost:8000/address/2
但是,我的测试代码:
func TestDeletePerson(t *testing.T) {
person := &Person{
UniqID: "2",
FirstName: "",
LastName: "",
EmailAddr: "",
PhoneNumb: "",
}
jsonPerson, _ := json.Marshal(person)
request, _ := http.NewRequest("DELETE", "/address/2", bytes.NewBuffer(jsonPerson))
response := httptest.NewRecorder()
DeletePerson(response, request)
DeletePerson的结果返回“”,并且 打印“参数”直接返回
map[]
大问题-我到底在想什么?
我是否设置了另一个标头参数?
答案 0 :(得分:1)
因为您没有初始化路由器。试试这个
func TestDeletePerson(t *testing.T) {
r := mux.NewRouter()
r.HandleFunc("/adress/{id}", DeletePerson).Methods("DELETE")
request, _ := http.NewRequest("DELETE", "/adress/2", nil)
response := httptest.NewRecorder()
r.ServeHTTP(response, request)
}
我还认为您不需要发送Person对象以进行删除
答案 1 :(得分:0)
问题是您的解决方案未测试我的删除处理程序“ DeletePerson”。 Curl用“ curl -X DELETE localhost:8000 / address / 2”行调用“ DeletePerson”;并且以某种方式允许mux.Vars查找明显的map [“ id”:“ 2'”],其中“ 2”是要删除的记录ID。我似乎无法做的就是调用“ DeletePerson:”,它会产生所需的地图参数!什么是gorillia mux.Vars阅读,一些内部标头? – 3小时前的教父