Skip to content

Commit

Permalink
net: modify example of Dialer
Browse files Browse the repository at this point in the history
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 golang#33743
  • Loading branch information
tomocy committed Sep 2, 2019
1 parent 5565916 commit d608be8
Showing 1 changed file with 9 additions and 26 deletions.
35 changes: 9 additions & 26 deletions src/net/example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.WithDeadline(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)
}
}

Expand Down

0 comments on commit d608be8

Please sign in to comment.