Home > Article > Backend Development > nil pointer error when trying to start a non-started server from httptest
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.
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?
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:
65bd95abbd7cThe 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!