1
0
mirror of https://github.com/golang/go synced 2024-11-23 12:50:12 -07:00

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
This commit is contained in:
tomocy 2019-09-02 11:24:31 +09:00
parent 55659163b3
commit d91cb36975

View File

@ -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)
}
}