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 packagesimport ("net""fmt""time")func main(){// initialize the address of the serveraddress := "golang.org:http"// open connection to serverconn, err := net.DialTimeout("tcp", address, 3 * time.Second)// check if connection was successfully establishedif 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, andfmtpackages. - Line 13: We initialize the hostname and address for a server,
golang.org:http. - Line 16: We use the
DialTimeoutfunction to connect to the server through the providedaddressover atcpnetwork. Thetimeoutis set to be3seconds. - If the connection is successful within the
3second timeout,errwill benil, and the corresponding message will be the output. Otherwise, theifstatement in line 19 will detect the error and print the relevant message.- If a timeout occurs, the
DialTimeoutfunction will return thei/o timeouterror message.
- If a timeout occurs, the