router.HandleFunc("/v1/m/mailboxes", s.handleGetAllMailboxes()).Methods(http.MethodGet)
func (s *Server) handleGetAllMailboxes() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(mailboxes)
}
}
我正在用 Postman 测试路线。但是每当我点击
http://localhost/v1/m/\*
,
我得到了编码的 Json。
我希望 API 仅在调用正确路径
http://localhost/v1/m/mailboxes
时响应。
尝试了以下代码:
func main() {
router := mux.NewRouter()
router.HandleFunc("/v1/m/mailboxes", handleGetAllMailboxes()).Methods(http.MethodGet)
http.Handle("/", router)
http.ListenAndServe(":8080", nil)
}
func handleGetAllMailboxes() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(`{"a": "b"}`)
}
}
而且我只在
curl http://localhost:8080/v1/m/mailboxes
上得到回复,而在任何其他路线上都没有。
curl http://localhost:8080/v1/m/aa
简单地返回404 page not found
.
也许问题更多在于你如何在你引用的代码部分之后公开你的路线。
此外,最后一个解决方案(不是很好)是使用匹配器:
// Test Routes
router.HandleFunc("/v1/m/mailboxes", s.handleGetAllMailboxes()).Methods(http.MethodGet).MatcherFunc(func(r *http.Request, rm *mux.RouteMatch) bool {
return r.URL.Path == "/v1/m/mailboxes"
})