What is the net.Listen function in Go?
Overview
The Listen function of the net package in Go creates servers and listens for incoming connections on a local network address.
To use the Listen function, we’ll import the net package into our program as shown below:
import (
"net"
)
Syntax
The syntax of the Listen function is shown below:
Listen(network, address string) (Listener, error)
Parameters
The Listen function accepts the following parameters:
-
network: The named network for communication, e.g., TCP, UDP, IP, etc. -
address: The address of the host server to listen on for connections.
Note: The list of supported networks and rules for their corresponding hosts can be found here.
Return value
The Listen function returns a Listener object that represents a server and an error object.
If the Listen function is able to listen on the specified address successfully, the error object has a value of nil.
Example
The code below shows how the Listen function works in Go.
package main// import necessary packagesimport ("net""fmt")func main(){// initialize the address port number of the serverport := ":8000"// Set up a listener on port 8080 for tcp connectionsln, err := net.Listen("tcp", port)// check if server was successfully createdif err != nil {fmt.Println("The following error occured", err)} else {fmt.Println("The listener object has been created:", ln)}}
Explanation
- Lines 4–7: We import the
netandfmtpackages. - Line 12: We initialize the
portnumber on which theListenfunction will listen. - Line 15: We use the
Listenfunction to create a server that listens fortcpconnections on the specified port. - If the server is successfully created,
errwill benil, and the corresponding message will be output. Otherwise, theifstatement in line 18 will detect the error and print the relevant message if an error occurs.