在尝试从httptest启动一个未启动的服务器时,出现了空指针错误。

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

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"))。

  • 第一个参数应该是tcptcp4tcp6unix或者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.Listen function ( Line: l, := net.Listen("http", "localhost:49219").

  • It must be tcp, tcp4, tcp6, unix or unixpacket instead of http.

  • For IPv4, you can use tcp4.

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()


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

发表评论

匿名网友

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

确定