Golang etcd 观察者恐慌
Golang etcd watcher panic
全部!
我有以下代码:
package main
import (
"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-watcher
2015/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 +0x2be
goroutine 17 [syscall, locked to thread]:
runtime.goexit()
/Users/Stalker/App/Go/1.5.1/src/runtime/asm_amd64.s:1696 +0x1
goroutine 19 [runnable]:
net/http.(*persistConn).writeLoop(0xc8200c6dc0)
/Users/Stalker/App/Go/1.5.1/src/net/http/transport.go:1009 +0x40c
created by net/http.(*Transport).dialConn
/Users/Stalker/App/Go/1.5.1/src/net/http/transport.go:686 +0xc9d
有人可以向我解释发生了什么以及如何使这个简单的示例正常工作吗?
非常感谢您的建议!
亚历克斯
图书馆可以关闭watchChan
频道。这将 return 在你的 r
中一个 nil 值然后当你尝试记录 r.Node
时恐慌。
当你得到一个指针时,你应该检查它不是 nil
。我还建议检查接收器通道是否已关闭并采取相应措施。
r, open := <-watchChan
if !open {
// channel is closed
}
if r == nil {
// the watch channel return a nil value
}
全部!
我有以下代码:
package main
import (
"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-watcher
2015/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 +0x2be
goroutine 17 [syscall, locked to thread]:
runtime.goexit()
/Users/Stalker/App/Go/1.5.1/src/runtime/asm_amd64.s:1696 +0x1
goroutine 19 [runnable]:
net/http.(*persistConn).writeLoop(0xc8200c6dc0)
/Users/Stalker/App/Go/1.5.1/src/net/http/transport.go:1009 +0x40c
created by net/http.(*Transport).dialConn
/Users/Stalker/App/Go/1.5.1/src/net/http/transport.go:686 +0xc9d
有人可以向我解释发生了什么以及如何使这个简单的示例正常工作吗? 非常感谢您的建议! 亚历克斯
图书馆可以关闭watchChan
频道。这将 return 在你的 r
中一个 nil 值然后当你尝试记录 r.Node
时恐慌。
当你得到一个指针时,你应该检查它不是 nil
。我还建议检查接收器通道是否已关闭并采取相应措施。
r, open := <-watchChan
if !open {
// channel is closed
}
if r == nil {
// the watch channel return a nil value
}