0

全部!

我有下面的代码:

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)出现故障时,恐慌会抱怨无效的内存地址或 nil 指针取消引用......

> $ ./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

有人可以解释一下发生了什么以及如何使这个简单的示例正常工作吗?非常感谢您的建议!亚历克斯

4

1 回答 1

4

图书馆可以关闭watchChan频道。这将在您返回 nil 值,r然后在您尝试登录时出现恐慌r.Node。当你得到一个指针时,你应该检查它不是nil. 我还建议检查接收器通道是否已关闭并采取相应措施。

r, open := <-watchChan
if !open {
    // channel is closed
}
if r == nil {
   // the watch channel return a nil value
}
于 2015-11-09T18:04:23.360 回答