How to Use net.Dial and net.DialContext in Go

Web
Use net.Dial for basic connections and net.DialContext to add timeouts and cancellation support to your Go network code.

Use net.Dial for simple blocking connections and net.DialContext when you need timeouts or cancellation.

// Simple blocking connection
conn, err := net.Dial("tcp", "example.com:80")
if err != nil {
    // handle error
}

// Connection with timeout and cancellation
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
conn, err := net.DialContext(ctx, "tcp", "example.com:80")
if err != nil {
    // handle error
}