What is the net.DialTimeout function in Golang?

Overview

The DialTimeout function of the net package in Golang connects to a server address on a named network before a specified timeout.

To use the DialTimeout function, we import the net package into our program as shown below:

import (
   "net"
)

Syntax

The syntax of the DialTimeout function is shown below:

DialTimeout(network, address string, timeout time.Duration) (Conn, error)

Parameters

The DialTimeout function accepts the following parameters:

  • network: The named network for communication, e.g., TCP, UDP, IP, etc.

  • address: A string that identifies the address of the server with which to communicate.

  • timeout: The amount of time the function waits for a connection to be accepted.

Note: The list of supported networks and rules for their corresponding hosts can be found here.

Return value

The DialTimeout function returns a Conn object that represents a network connection and an error object.

If the DialTimeout function successfully establishes the connection within the specified timeout, the error object has a value of nil.

Example

The code below shows how the DialTimeout function works in Golang.

package main
// import necessary packages
import (
"net"
"fmt"
"time"
)
func main(){
// initialize the address of the server
address := "golang.org:http"
// open connection to server
conn, err := net.DialTimeout("tcp", address, 3 * time.Second)
// check if connection was successfully established
if err != nil {
fmt.Println("The following error occured", err)
} else {
fmt.Println("The connection was established to", conn)
}
}

Explanation

  • Lines 4–8: We import the net, time, and fmt packages.
  • Line 13: We initialize the hostname and address for a server, golang.org:http.
  • Line 16: We use the DialTimeout function to connect to the server through the provided address over a tcp network. The timeout is set to be 3 seconds.
  • If the connection is successful within the 3 second timeout, err will be nil, and the corresponding message will be the output. Otherwise, the if statement in line 19 will detect the error and print the relevant message.
    • If a timeout occurs, the DialTimeout function will return the i/o timeout error message.

Free Resources