httprouter恐慌:路径必须以’/’开头,路径为’GET’。

huangapple go评论79阅读模式
英文:

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/httprouterRouter.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()))

huangapple
  • 本文由 发表于 2023年3月27日 06:17:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75850875.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定