gpt4 book ai didi

Golang etcd 观察者 panic

转载 作者:IT王子 更新时间:2023-10-29 02:29:56 31 4
gpt4 key购买 nike

全部!

我有下面的代码:

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)正在关闭时, panic 是提示无效的内存地址或零指针取消引用......

> $ ./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 channel 。这将在您的 r 中返回一个 nil 值,然后当您尝试记录 r.Node 时出现 panic 。当你得到一个指针时,你应该检查它不是 nil。我还建议检查接收方 channel 是否已关闭并采取相应措施。

r, open := <-watchChan
if !open {
// channel is closed
}
if r == nil {
// the watch channel return a nil value
}

关于Golang etcd 观察者 panic ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33614899/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com