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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 关于#java#的问题,请各位专家解答!
  • ¥30 vue+element根据数据循环生成多个table,如何实现最后一列 平均分合并
  • ¥20 pcf8563时钟芯片不启振
  • ¥20 pip2.40更新pip2.43时报错
  • ¥15 换yum源但仍然用不了httpd
  • ¥50 C# 使用DEVMOD设置打印机首选项
  • ¥15 麒麟V10 arm安装gdal
  • ¥20 OPENVPN连接问题
  • ¥15 flask实现搜索框访问数据库
  • ¥15 mrk3399刷完安卓11后投屏调试只能显示一个设备