Home  >  Article  >  Backend Development  >  nil pointer error when trying to start a non-started server from httptest

nil pointer error when trying to start a non-started server from httptest

WBOY
WBOYforward
2024-02-12 19:33:21497browse

尝试从 httptest 启动未启动的服务器时出现 nil 指针错误

php editor Strawberry will answer a common question for everyone: "A nil pointer error occurs when trying to start an unstarted server from httptest." While doing HTTP testing, sometimes we may encounter this error. This is because httptest is trying to connect to a server that has not yet been started, resulting in a nil pointer error. Before solving this problem, we need some background knowledge.

Question content

I'm trying to build a mock httpserver in my code. I want to specify the port number, so I used the following 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 the svr.start() line, I get an error message:

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 zero at this time. I want to know why this error occurs and how I should fix it?

Solution

  • The first parameter needs to be updated when calling the net.listen function (line: l, := net.listen("http", "localhost:49219").

  • must be tcp, tcp4, tcp6, unix or unixpacket, not http.

  • For ipv4, you can use tcp4.

Example:

65bd95abbd7c

The above is the detailed content of nil pointer error when trying to start a non-started server from httptest. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete