This commit is contained in:
iamqizhao 2016-08-23 19:23:04 -07:00
Родитель 60c350b0e9
Коммит 7eae19acb7
2 изменённых файлов: 15 добавлений и 9 удалений

Просмотреть файл

@ -221,19 +221,29 @@ func Dial(target string, opts ...DialOption) (*ClientConn, error) {
}
// DialContext creates a client connection to the given target. ctx can be used to
// cancel or expire the pending connecting. Once the initial connection is done,
// the cancellation and expiration of ctx will not affect the connection.
// cancel or expire the pending connecting. Once this function returns, the
// cancellation and expiration of ctx will be noop. Users should call ClientConn.Close
// to terminate all the pending operations after this function returns.
func DialContext(ctx context.Context, target string, opts ...DialOption) (*ClientConn, error) {
cc := &ClientConn{
target: target,
conns: make(map[Address]*addrConn),
}
cc.ctx, cc.cancel = context.WithCancel(context.Background())
done := make(chan struct{})
defer close(done)
go func() {
select {
case <-ctx.Done():
cc.Close()
case <-done:
select {
case <-ctx.Done():
cc.Close()
default:
}
case <-cc.ctx.Done():
// ClientConn.Close has been called.
}
}()

Просмотреть файл

@ -71,13 +71,9 @@ func TestTLSDialTimeout(t *testing.T) {
func TestDialContextCancel(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
go cancel()
conn, err := DialContext(ctx, "Non-Existent.Server:80", WithBlock(), WithInsecure())
if err == nil {
conn.Close()
}
if err != context.Canceled {
t.Fatalf("DialContext(_, _) = %v, %v, want %v", conn, err, context.Canceled)
cancel()
if _, err := DialContext(ctx, "Non-Existent.Server:80", WithBlock(), WithInsecure()); err != context.Canceled && err != ErrClientConnClosing {
t.Fatalf("grpc.DialContext(%v, _) = _, %v, want _, %v or %v", ctx, err, context.Canceled, ErrClientConnClosing)
}
}