英文:
httprouter panic: path must begin with '/' in path 'GET'
问题
我正在将处理程序从net/http/mux迁移到httprouter,但我的测试失败了。我正在向在单独的Go协程中运行的服务器发送请求。httprouter抱怨路径必须以/开头,不确定为什么。
httprouter的实现:
mux := httprouter.New()
mux.HandlerFunc("/api", http.MethodGet, wrapper(s.rootHandler()))
测试调用路径:
req, err := http.NewRequest(http.MethodGet, "http://localhost:8080/api", nil)
req.Header.Set("Content-Type", "application/json")
if err != nil {
return err
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close() //nolint:errcheck
if res.StatusCode != http.StatusOK {
return errors.New("server not yet running")
}
不确定为什么会引发恐慌。使用net/http mux运行时没有问题。
英文:
I am moving my handler from net/http / mux to httprouter and my tests are failing. I am doing a request to a server running in a separate go routine. httprouter is complaining that the path must start with /, not sure why.
httprouter implementation:
mux := httprouter.New()
mux.HandlerFunc("/api", http.MethodGet, wrapper(s.rootHandler()))
test calling the pth
req, err := http.NewRequest(http.MethodGet, "http://localhost:8080/api", nil)
req.Header.Set("Content-Type", "application/json")
if err != nil {
return err
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close() //nolint:errcheck
if res.StatusCode != http.StatusOK {
return errors.New("server not yet running")
}
Not sure it is throwing a panic. It has no issues running with net/http mux.
答案1
得分: 1
如@mkopriva所提到的,julienschmidt/httprouter的Router.HandlerFunc(method, path string, handler http.HandlerFunc)
函数将路径作为第二个参数,方法作为第一个参数。
但是在标准的net/http中,Serve.HandleFunc(pattern string, handler http.HandlerFunc)
函数将路径作为第一个参数。
所以将代码中的部分修改为:
mux.HandlerFunc(http.MethodGet, "/api", wrapper(s.rootHandler()))
英文:
As @mkopriva mentioned, julienschmidt/httprouter Router.HandlerFunc(method, path string, handler http.HandlerFunc)
takes the path as the second argument, as well as the method in the first argument.
But in the standard net/http Serve.HandleFunc(pattern string, handler http.HandlerFunc)
we have the path as the first argument.
So change:
mux.HandlerFunc("/api", http.MethodGet, wrapper(s.rootHandler()))
into
mux.HandlerFunc(http.MethodGet, "/api", wrapper(s.rootHandler()))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论