Search code examples
goetcd

API to find a key in a etcd cluster


I am trying to write a code where I need to find if a key exists in etcd or not. I tried this:

_, err = kapi.Get(context.Background(), key, nil)
        if err != nil {
          return err      
        } else { ...

But even if the key is not in the cluster, the error is always nil.

Any idea what am I doing wrong here? Or is there any other API call to make?


Solution

  • If you use the go client v3 KV client here: https://godoc.org/go.etcd.io/etcd/clientv3#KV

    It returns the following type: https://godoc.org/go.etcd.io/etcd/etcdserver/etcdserverpb#RangeResponse

    type RangeResponse struct {
        Header *ResponseHeader `protobuf:"bytes,1,opt,name=header" json:"header,omitempty"`
        // kvs is the list of key-value pairs matched by the range request.
        // kvs is empty when count is requested.
        Kvs []*mvccpb.KeyValue `protobuf:"bytes,2,rep,name=kvs" json:"kvs,omitempty"`
        // more indicates if there are more keys to return in the requested range.
        More bool `protobuf:"varint,3,opt,name=more,proto3" json:"more,omitempty"`
        // count is set to the number of keys within the range when requested.
        Count int64 `protobuf:"varint,4,opt,name=count,proto3" json:"count,omitempty"`
    }
    

    So as you see, there is a Count property and a Kvs property, if you want to check that your response contains keys you can just check that Count > 0 or len(res.Kvs) > 0