从net/http mux迁移到httprouter测试失败,触发路径格式panic
解决httprouter迁移时的"path must begin with '/'" panic问题
你的问题出在httprouter.HandlerFunc的参数顺序和你之前用的net/http mux不一致,导致参数传反触发了panic。
httprouter的HandlerFunc方法要求第一个参数是HTTP方法,第二个参数是路径,但你的代码里把路径"/api"放在了第一个位置,HTTP方法http.MethodGet放在了第二个位置。这会让httprouter错误地把"GET"当成路径处理,而路径必须以/开头,所以抛出了path must begin with '/' in path 'GET'的panic。
修正后的代码
mux := httprouter.New() mux.HandlerFunc(http.MethodGet, "/api", wrapper(s.rootHandler()))
补充说明
httprouter的HandlerFunc签名为:
func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc)
而标准库的http.ServeMux相关方法通常是先路径后方法,迁移时一定要注意这种参数顺序的差异,避免类似问题。
内容的提问来源于stack exchange,提问作者puppeteer701
相关产品推荐
相关产品推荐

