From d91cb3697516ccfc3f956e97837404cbfee5922f Mon Sep 17 00:00:00 2001 From: tomocy Date: Mon, 2 Sep 2019 11:24:31 +0900 Subject: [PATCH] net: modify example of Dialer The previous example was unusual because it used (*Dialer).Dial in a goroutine differennt frrom main one and because it is not necessary to receive Conn from the channel since Conn is produced only once, so modify the example to show just how (*Dialer).DialContext is used. Updates #33743 --- src/net/example_test.go | 35 +++++++++-------------------------- 1 file changed, 9 insertions(+), 26 deletions(-) diff --git a/src/net/example_test.go b/src/net/example_test.go index 9aaba4dd2a..ef8c38f9f4 100644 --- a/src/net/example_test.go +++ b/src/net/example_test.go @@ -40,35 +40,18 @@ func ExampleListener() { } func ExampleDialer() { - d := net.Dialer{ - Timeout: 3 * time.Minute, - } - ctx, cancel := context.WithCancel(context.Background()) + var d net.Dialer + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() - connCh := make(chan net.Conn) - go func() { - defer close(connCh) - conn, err := d.DialContext(ctx, "tcp", "localhost:12345") - if err != nil { - log.Fatal(err) - return - } - connCh <- conn - }() + conn, err := d.DialContext(ctx, "tcp", "localhost:12345") + if err != nil { + log.Fatalf("Failed to dial: %v", err) + } + defer conn.Close() - for { - select { - case <-time.After(time.Second): - // You can do cancel() here when something wrong happens. - case conn, ok := <-connCh: - if !ok { - return - } - - conn.Write([]byte("hello, go")) - conn.Close() - } + if _, err := conn.Write([]byte("Hello, World!")); err != nil { + log.Fatal(err) } }