Banging my head on this one. I can't get an HTTP Response to assign to a struct.
I have my structs set up like so:
type DataConnect struct {
Response *Response
}
type Response struct {
response []byte
errors []string
}
Then the function in question is laid out like so (trimmed for readability):
137 func (d *DataConnect) send() bool {
...
154 out, err := ioutil.ReadAll(resp.Body)
155 if err != nil {
156 fmt.Println(err)
157 }
158
159 fmt.Printf("%s
", out) // THIS WORKS
160 d.Response.response = out // THIS DOES NOT WORK
161 }
Doing that results in the following error:
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x0 pc=0x36532]
goroutine 1 [running]:
github.com/DataConnect.(*DataConnect).send(0xc2000af4a0, 0x232a00)
github.com/DataConnect/DataConnect.go:160 +0xc22
Now if I change DataConnect.Response.response
to type interface{}
I can save successfully to it, however I need it in []byte
as later I will be doing a json.Unmarshal on the content.
Does anybody have any idea why this isn't working?
I suspect either d is nil or d.Response is nil on line 160. If that is true, you need to decide if that is appropriate and change your code if it is not.
I suspect @alex is correct, change your code to something that looks for nil (from line 159):
fmt.Printf("%s
", out) // THIS WORKS
if d != nil && d.Response != nil {
d.Response.response = out // THIS DOES NOT WORK
} else {
// appropriate error logging and handling
}