douzhuozhu9544 2015-11-09 17:39
浏览 125
已采纳

Golang etcd观察者恐慌

All!

I've the code below:

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
", r.Node.Key, r.Node.Value)
        }
}

BUT... When some node (for example 172.20.20.11) is going down the panic is complain regarding the invalid memory address or nil pointer dereference...

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

Could someone explain me what is going on and how to make this simple example to work properly?? Thanks a lot for advice! Alex

  • 写回答

1条回答 默认 最新

  • douxie9347 2015-11-09 18:04
    关注

    The library can close the watchChanchannel. That will return a nil value in your r and then panic when you try to log r.Node. When you get a pointer back, you should check it's not nil. I would also recommend checking if the receiver channel has been closed and act accordingly.

    r, open := <-watchChan
    if !open {
        // channel is closed
    }
    if r == nil {
       // the watch channel return a nil value
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大