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"
)
The syntax of the DialTimeout
function is shown below:
DialTimeout(network, address string, timeout time.Duration) (Conn, error)
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.
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
.
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)}}
net
, time
, and fmt
packages.golang.org:http
.DialTimeout
function to connect to the server through the provided address
over a tcp
network. The timeout
is set to be 3
seconds.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.
DialTimeout
function will return the i/o timeout
error message.