Home >Backend Development >Golang >Go HTTP Client: How to Avoid 'panic: runtime error: invalid memory address or nil pointer dereference'?
Go: panic: runtime error: invalid memory address or nil pointer dereference
When running a Go program, a panic can occur due to an invalid memory address or nil pointer dereference. This error message often indicates a runtime issue rather than a specific program bug.
In this case, the provided Go code demonstrates potential problems with HTTP client handling.
The Issue
The code uses the func (*Client) Do method to make HTTP requests. However, it fails to check for errors returned by the client before attempting to access the response body.
The Solution
According to the documentation for func (*Client) Do, even if a non-2xx HTTP status code is received, it does not result in an error. Instead, the error is only returned if it's caused by client policy or an HTTP protocol error.
The code, however, checks for errors after accessing the response body (res.Body). This can lead to an error being thrown due to an invalid memory address or nil pointer dereference.
To resolve this issue, the code should be modified to check for errors before accessing the response body, like so:
res, err := client.Do(req) if err != nil { return nil, err } defer res.Body.Close()
The above is the detailed content of Go HTTP Client: How to Avoid 'panic: runtime error: invalid memory address or nil pointer dereference'?. For more information, please follow other related articles on the PHP Chinese website!