英文:
Getting nil pointer error when trying to start a unstartedServer from httptest
问题
我正在尝试在我的代码中构建一个模拟的http服务器。我想指定端口号,所以我使用了下面的代码:
l, _ := net.Listen("http", "localhost:49219")
svr := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ... }))
svr.Listener.Close()
svr.Listener = l
svr.Start()
然而,在svr.Start()这一行,我收到了一个错误信息:
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
panic: runtime error: invalid memory address or nil pointer dereference
显然,在那一点上svr不是nil。我想知道为什么会出现这个错误,以及如何修复它?
英文:
I am trying to build a mock httpserver in my code. I want to specify the port number so I have used the below code:
l, _ := net.Listen("http", "localhost:49219")
svr := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ... }))
svr.Listener.Close()
svr.Listener = l
svr.Start()
However, at line svr.Start(), I am getting an error saying:
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
panic: runtime error: invalid memory address or nil pointer dereference
Obviously svr is not nil at that point. I am wondering why I am getting this error and how should I fix this?
答案1
得分: 2
- 
当调用
net.Listen函数时,你需要更新第一个参数(行:l, := net.Listen("http", "localhost:49219"))。 - 
第一个参数应该是
tcp、tcp4、tcp6、unix或者unixpacket,而不是http。 - 
对于IPv4,你可以使用
tcp4。 
示例代码:
l, err := net.Listen("tcp4", "localhost:49219")
if err != nil {
  // 在这里处理错误
}
svr := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ... }))
svr.Listener.Close()
svr.Listener = l
svr.Start()
英文:
- 
You need to update first argument when you are calling
net.Listenfunction ( Line:l, := net.Listen("http", "localhost:49219"). - 
It must be
tcp,tcp4,tcp6,unixorunixpacketinstead ofhttp. - 
For
IPv4, you can usetcp4. 
Example:
l, err := net.Listen("tcp4", "localhost:49219")
if err != nil {
  // handle error here
}
svr := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ... }))
svr.Listener.Close()
svr.Listener = l
svr.Start()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论