把我的头撞在这上面。我无法获得分配给结构的HTTP响应。
我的structs设置如下:
type DataConnect struct {
Response *Response
}
type Response struct {
response []byte
errors []string
}然后有问题的函数的布局是这样的(为了可读性进行了修剪):
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\n", out) // THIS WORKS
160 d.Response.response = out // THIS DOES NOT WORK
161 }这样做会导致以下错误:
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现在,如果我将DataConnect.Response.response更改为interface{}类型,我可以成功地保存到它,但是我需要在[]byte中保存它,因为稍后我将对内容执行json.Unmarshal。
有没有人知道为什么这不起作用?
发布于 2013-09-12 07:46:55
我怀疑在第160行,d要么是零,要么是d.Response是零。如果这是真的,你需要决定这是否合适,如果不合适,就修改你的代码。
发布于 2013-09-12 08:08:54
我怀疑@alex是正确的,将您的代码更改为查找nil的代码(从第159行开始):
fmt.Printf("%s\n", out) // THIS WORKS
if d != nil && d.Response != nil {
d.Response.response = out // THIS DOES NOT WORK
} else {
// appropriate error logging and handling
}https://stackoverflow.com/questions/18752544
复制相似问题