-
What would you like to be added?When my local etcd is not started, I run the following code. What confuses me is that err is nil. package main
import (
"time"
clientv3 "go.etcd.io/etcd/client/v3"
)
func main() {
cli, err := clientv3.New(clientv3.Config{
Endpoints: []string{"127.0.0.1:2379"},
DialTimeout: 1 * time.Second,
})
if err != nil {
panic(err.Error())
}
defer cli.Close()
} Without changing the It is used as follows: var err error
cli, err = clientv3.New(clientv3.Config{
Endpoints: []string{"127.0.0.1:2379"},
DialTimeout: 1 * time.Second,
})
if err != nil {
panic(err.Error())
}
defer cli.Close()
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
if err := cli.Ping(ctx); err != nil {
panic(err)
} Why is this needed?Because I didn't know if the client's state was successful or failed after I called |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments
-
My Development Environment:
|
Beta Was this translation helpful? Give feedback.
-
By default grpc client will not block on startup. You can set |
Beta Was this translation helpful? Give feedback.
-
Thanks, you are correct, if package main
import (
"context"
"time"
clientv3 "go.etcd.io/etcd/client/v3"
"google.golang.org/grpc"
)
var cli *clientv3.Client
func main() {
if err := Init(); err != nil {
panic(err)
}
}
func Init() error {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
resultCh := make(chan *clientv3.Client, 1)
errCh := make(chan error, 1)
go func() {
cli, err := clientv3.New(clientv3.Config{
Endpoints: []string{"127.0.0.1:2379"},
DialOptions: []grpc.DialOption{grpc.WithBlock()},
})
if err != nil {
errCh <- err
return
}
resultCh <- cli
}()
select {
case <-ctx.Done():
return ctx.Err()
case err := <-errCh:
return err
case cli = <-resultCh:
return nil
}
} Do you have any better practice for initializing |
Beta Was this translation helpful? Give feedback.
-
DialTimeout doesn't work? |
Beta Was this translation helpful? Give feedback.
-
sorry, I forgot to set |
Beta Was this translation helpful? Give feedback.
By default grpc client will not block on startup. You can set
DialOptions: []grpc.DialOption{grpc.WithBlock()},
to get the behavior you want.