1 回答

TA貢獻1818條經驗 獲得超11個贊
我認為這是因為您的測試不包括路由器,因此未檢測到路徑變量。來,試試這個
// main.go
func router() *mux.Router {
router := mux.NewRouter()
router.HandleFunc("/people", GetPeopleEndpoint).Methods("GET")
router.HandleFunc("/people/{id}", GetPersonEndpoint).Methods("GET")
router.HandleFunc("/people/{id}", CreatePersonEndpoint).Methods("POST")
router.HandleFunc("/people/{id}", DeletePersonEndpoint).Methods("DELETE")
return router
}
并在您的測試用例中,從路由器方法啟動,如下所示
handler := router()
// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
// directly and pass in our Request and ResponseRecorder.
handler.ServeHTTP(rr, req)
現在,如果您嘗試訪問路徑變量 id,它應該出現在 mux 返回的映射中,因為當您從 router() 返回的 mux 路由器實例初始化處理程序時,mux 注冊了它
params := mux.Vars(req)
for index, item := range people {
if item.ID == params["id"] {
people = append(people[:index], people[index+1:]...)
break
}
}
也像您提到的那樣,使用 init 函數進行一次設置。
// main.go
func init(){
SeedData()
}
- 1 回答
- 0 關注
- 163 瀏覽
添加回答
舉報