Home > Backend Development > Golang > 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
Release: 2024-02-12 19:33:21
forward
589 people have browsed it

尝试从 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()
Copy after login

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
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template