What is the net.Dial function in Golang?

The Dial function of the net package in Golang connects to a server address on a named network.

To use the Dial function, you will need to import the net package into your program, as shown below:

import (
   "net"
)

Syntax

The syntax of the Dial function is shown below:

Dial(network, address string) (Conn, error)

Parameters

The Dial 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 to communicate to.

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

Return value

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

If the Dial function successfully establishes the connection, the error object has a value of nil.

Code

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

package main
// import necessary packages
import (
"net"
"fmt"
)
func main(){
// initialize the address of the server
address := "golang.org:http"
// open connection to server
conn, err := net.Dial("tcp", address)
// 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

In the code above:

  • Lines 4-7: Import the net and fmt packages.
  • Line 12: Initialize the hostname and address for a server, golang.org:http.
  • Line 15: Use the Dial function to connect to the server through the provided address over a tcp network.
  • If the connection is successful, err will be nil, and the corresponding message will be output. Otherwise, the if statement in line 18 will detect the error and print the relevant message if an error occurs.

Free Resources