在Golang中执行net.DialTCP时如何设置超时时间?

net.DialTCP 似乎是获取net.TCPConn的唯一办法,我不确定在执行 DialTCP时如何设置超时。
func connectAddress(addr *net.TCPAddr, wg *sync.WaitGroup) error {
    start := time.Now()
    conn, err := net.DialTCP("tcp", nil, addr)
    if err != nil {
        log.Printf("Dial failed for address: %s, err: %s", addr.String(), err.Error())
        return err
    }
    elasped := time.Since(start)
    log.Printf("Connected to address: %s in %dms", addr.String(), elasped.Nanoseconds()/1000000)
    conn.Close()
    wg.Done()
    return nil
}

Use net.Dialer with either the Timeout or Deadline fields set.

d := net.Dialer{Timeout: timeout}
conn, err := d.Dial("tcp", addr)
if err != nil {
   // handle error
}

A variation is to call Dialer.DialContext with a deadline or timeout applied to the context.

Type assert to *net.TCPConn if you specifically need that type instead of a net.Conn:

tcpConn, ok := conn.(*net.TCPConn)

One can use net.DialTimeout:

func DialTimeout(network, address string, timeout time.Duration) (Conn, error)
    DialTimeout acts like Dial but takes a timeout.

    The timeout includes name resolution, if required. When using TCP, and the
    host in the address parameter resolves to multiple IP addresses, the timeout
    is spread over each consecutive dial, such that each is given an appropriate
    fraction of the time to connect.

    See func Dial for a description of the network and address parameters.