全部!我有下面的代码:package mainimport ( "log" "github.com/coreos/go-etcd/etcd")func main() { client := etcd.NewClient( []string{ "http://172.20.20.10:2379", "http://172.20.20.11:2379", "http://172.20.20.12:2379", }, ) for { watchChan := make(chan *etcd.Response) go client.Watch("/config", 0, false, watchChan, nil) log.Println("Waiting for an update...") r := <-watchChan log.Printf(">>> got an updated config: %s: %s\n", r.Node.Key, r.Node.Value) }}但是...当某个节点(例如 172.20.20.11)出现故障时,恐慌会抱怨无效的内存地址或零指针取消引用...> $ ./etcd-watcher2015/11/09 18:46:19 Waiting for an update...panic: runtime error: invalid memory address or nil pointer dereference[signal 0xb code=0x1 addr=0x10 pc=0x22fe]goroutine 1 [running]:main.main() /Users/Stalker/Workspace/src/snippets/etcd-watcher.go:26 +0x2begoroutine 17 [syscall, locked to thread]:runtime.goexit() /Users/Stalker/App/Go/1.5.1/src/runtime/asm_amd64.s:1696 +0x1goroutine 19 [runnable]:net/http.(*persistConn).writeLoop(0xc8200c6dc0) /Users/Stalker/App/Go/1.5.1/src/net/http/transport.go:1009 +0x40ccreated by net/http.(*Transport).dialConn /Users/Stalker/App/Go/1.5.1/src/net/http/transport.go:686 +0xc9d有人可以解释一下发生了什么以及如何使这个简单的示例正常工作吗?非常感谢您的建议!亚历克斯
1 回答
翻过高山走不出你
TA贡献1875条经验 获得超3个赞
图书馆可以关闭watchChan通道。这将返回一个 nil 值r,然后在您尝试 log 时发生恐慌r.Node。当你得到一个指针时,你应该检查它不是nil。我还建议检查接收器通道是否已关闭并采取相应措施。
r, open := <-watchChan
if !open {
// channel is closed
}
if r == nil {
// the watch channel return a nil value
}
- 1 回答
- 0 关注
- 156 浏览
添加回答
举报
0/150
提交
取消