Page Content

Tutorials

Network Programming In GoLang: TCP, UDP And HTTP

Network Programming in GoLang

With Go’s strong network programming capabilities, programmers can quickly and safely design sophisticated web servers, web clients, and other network applications. The core components of this functionality are the net/http and net standard library packages. Go is ideally suited for distributed systems and networking due to its design, which includes its concurrency advantages. GoLang is perfect for network programming.

Understanding TCP/IP

Protocols like TCP/IP are the basis of network communication. The Transmission Control Protocol (TCP) and Internet Protocol (IP) are the two main components of the TCP/IP family of protocols, which enable internet functioning.

  • TCP (Transmission Control Protocol), is a dependable protocol that guarantees data packets, also known as segments, are sent between computers without requiring further programming. In order to guarantee proper data transmission and reception, it creates a full-duplex virtual circuit between two machines that communicate continuously.
  • IP (Internet Protocol) is inherently unstable. It efficiently manages routing by encapsulating data and sending packets based on IP addresses from a source host to a destination host.
  • Another IP-based protocol that lacks reliability is UDP (User Datagram Protocol). Although messages may be lost, duplicated, or arrive out of order, UDP is easier to use and faster than TCP since it does not need to retain connection state, which makes it appropriate when speed is more important than dependability.

Network addresses

There are various versions of network addresses:

IPv4 addresses have a format similar to 10.20.32.245 (four parts separated by dots) and are encoded by 32 bits, allowing for over 4 billion distinct addresses.

With a syntax like 3fce:1706:4523:3:150:f8ff:fe21:56cf (eight pieces separated by colons), IPv6 uses 128 bits for each address. The impending expiration of IPv4 addresses prompted the creation of IPv6.

HTTP Servers in Go

Creating HTTP servers is made simple using Go. To manage URL routes and serve content, you can utilise functions from the net/http package.

Key Components

  • http.HandleFunc(pattern, handler): This function links a handler function to a URL pattern (such as “/hello” or “/”). An http.ResponseWriter and a http.Request are passed as parameters to the handler method.
  • http.ListenAndServe(address, handler): An HTTP server is launched, listening on the designated address (for example, “:9000” on port 9000 on all interfaces). It makes use of http.DefaultServeMux if nil is supplied as the handler.

Code Example: Web Server Basic (www.go) Two handlers are shown by this server: one for the root path (/) and another for /time, which dynamically shows the current date and time.

package main
import (
    "fmt"
    "net/http"
    "os"
    "time"
)
// myHandler serves the root path, printing a simple message and logging the host.
func myHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Serving: %s\n", r.URL.Path)
    fmt.Printf("Served: %s\n", r.Host)
}
// timeHandler serves the /time path, displaying the current date and time.
func timeHandler(w http.ResponseWriter, r *http.Request) {
    t := time.Now().Format(time.RFC1123)
    Body := "The current time is:"
    fmt.Fprintf(w, "<h1 align=\"center\">%s</h1>", Body)
    fmt.Fprintf(w, "<h2 align=\"center\">%s</h2>\n", t)
    fmt.Fprintf(w, "Serving: %s\n", r.URL.Path)
    fmt.Printf("Served time for: %s\n", r.Host)
}
func main() {
    PORT := ":8001"
    arguments := os.Args
    if len(arguments) == 1 {
        fmt.Println("Using default port number: ", PORT)
    } else {
        PORT = ":" + arguments[20]
    }
    // Associate URL patterns with handler functions.
    http.HandleFunc("/time", timeHandler)
    http.HandleFunc("/", myHandler) // The "/" pattern matches all URLs not matched by other handlers.
    // Start the HTTP server.
    err := http.ListenAndServe(PORT, nil)
    if err != nil {
        fmt.Println(err)
        return
    }
}

Output

Using default port number:  :8001

HTTP Clients in Go

HTTP clients are required in order to communicate with web servers. The net/http package in Go offers straightforward methods for submitting HTTP requests.

Key Components

http.Get(url string): This method is useful for making basic GET requests. It gives back an error and *http.Response.

http.Client: You can build a http.Client object to have additional control over HTTP requests (e.g., handling redirects, custom headers, or setting timeouts). An HTTP request is sent and a response is retrieved using the Do(request *http.Request) function of the http.Client.

http.NewRequest(method, url string, body io.Reader): To be used with http.Client.Do(), a http.Request object is created.

http.Response: Represents the status, headers, and response body of an HTTP request.

http.Request: Represents an HTTP request that a client is about to send or that a server has received.

Code Example: (advancedWebClient.go) An Advanced Web Client This application retrieves a URL that is supplied as a command-line argument and outputs comprehensive details about the HTTP response, such as the headers, character set, content length, and status code. Additionally, it shows how to set a client-side timeout.

package main
import (
	"fmt"
	"io"
	"net/http"
	"net/http/httputil"
	"net/url"
	"os"
	"path/filepath"
	"strings"
	"time"
)
func main() {
	if len(os.Args) != 2 {
		fmt.Printf("Usage: %s URL\n", filepath.Base(os.Args[0]))
		return
	}
	// Corrected: The URL is the first argument after the program name, at index 1.
	URL, err := url.Parse(os.Args[1])
	if err != nil {
		fmt.Println("Error in parsing:", err)
		return
	}
	// Create a custom HTTP client with a timeout.
	c := &http.Client{
		Timeout: 15 * time.Second,
	}
	// Create a new HTTP request.
	request, err := http.NewRequest("GET", URL.String(), nil)
	if err != nil {
		fmt.Println("Get:", err)
		return
	}
	// Send the request using the custom client.
	httpData, err := c.Do(request)
	if err != nil {
		fmt.Println("Error in Do():", err)
		return
	}
	defer httpData.Body.Close()
	// Print status code and headers.
	fmt.Println("Status code:", httpData.Status)
	header, _ := httputil.DumpResponse(httpData, false)
	fmt.Print(string(header))
	// Extract and print character set.
	contentType := httpData.Header.Get("Content-Type")
	characterSet := strings.SplitAfter(contentType, "charset=")
	// Corrected: The character set is the second element after the split, at index 1.
	if len(characterSet) > 1 {
		fmt.Println("Character Set:", characterSet[1])
	}
	// Print content length.
	if httpData.ContentLength == -1 {
		fmt.Println("ContentLength is unknown!")
	} else {
		fmt.Println("ContentLength:", httpData.ContentLength)
	}
	// Calculate and print the actual response data length.
	length := 0
	buffer := make([]byte, 1024)
	r := httpData.Body
	for {
		n, err := r.Read(buffer)
		length += n
		if err != nil {
			if err == io.EOF {
				break
			}
			fmt.Println(err)
			break
		}
	}
	fmt.Println("Calculated response data length:", length)
}

Output

Status code: 200 OK
HTTP/1.1 200 OK
Content-Type: text/html; charset=ISO-8859-1
Date: Mon, 20 Oct 2025 15:30:00 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Encoding: gzip
Content-Length: 2280
Server: gws
X-XSS-Protection: 0
X-Frame-Options: SAMEORIGIN
Character Set: ISO-8859-1
ContentLength: 2280
Calculated response data length: 2280

TCP Servers in Go

Go offers the net package to construct TCP servers for network communication at a lower level than HTTP.

Key Components

net.Listen(network, address): Listens for incoming connections on the designated address (such as “:8001”) and network (such as “tcp”, “tcp4”, and “tcp6”). It gives back a net.Pay attention.

net.Listener.Accept(): Awaits the subsequent incoming connection and sends it back as a net.Connecticut.

net.Conn: Symbolizes a connection to a network. Data may be read from and written to it with its implementation of the io.Reader and io.Writer interfaces.

Code Example: TCPserver.go is a basic TCP server. This server takes a single client connection, listens on a designated port, and relays to the client the time and date of each message it receives.

package main
import (
    "bufio"
    "fmt"
    "net"
    "os"
    "strings"
    "time"
)
func main() {
    arguments := os.Args
    if len(arguments) == 1 {
        fmt.Println("Please provide port number")
        return
    }
    // Corrected: Use arguments[1] to get the first command-line argument (the port number).
    PORT := ":" + arguments[1]
    // Listen for incoming TCP connections.
    l, err := net.Listen("tcp", PORT)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer l.Close() // Ensure the listener is closed when main exits.
    // Accept a single client connection.
    fmt.Printf("Listening for connections on port %s...\n", PORT)
    c, err := l.Accept()
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("Client connected!")
    // Loop to read from and write to the client.
    for {
        netData, err := bufio.NewReader(c).ReadString('\n')
        if err != nil {
            fmt.Println(err)
            return
        }
        if strings.TrimSpace(string(netData)) == "STOP" {
            fmt.Println("Exiting TCP server!")
            return
        }
        fmt.Print("-> ", string(netData))
        t := time.Now()
        myTime := t.Format(time.RFC3339) + "\n"
        c.Write([]byte(myTime)) // Write the current time back to the client.
    }
}

Output

Client connected!
-> Hello there!
-> STOP
Exiting TCP server!

TCP Clients in Go

A TCP client is used to establish a connection with a TCP server.

Key Components

  • net.Dial(network, address): Creates a connection with a distant server. The network type (such as “tcp”, “tcp4”, or “tcp6”) is specified by the first parameter, while the server address and port (such as “localhost:8001”) are provided by the second. It gives back a net.Connecticut.
  • The internet.Then, like the server side, Conn can be used to send and receive data.

Code Example: TCPclient.go is a basic TCP client. This client establishes a connection with a designated TCP server, receives user input (standard input), transmits it to the server, and outputs the response from the server.

package main
import (
	"bufio"
	"fmt"
	"net"
	"os"
	"strings"
)
func main() {
	arguments := os.Args
	if len(arguments) == 1 {
		fmt.Println("Please provide host:port.")
		return
	}
	// Corrected: Use arguments[1] to get the first command-line argument.
	CONNECT := arguments[1]
	// Connect to the remote TCP server.
	c, err := net.Dial("tcp", CONNECT)
	if err != nil {
		fmt.Println("Error connecting:", err)
		return
	}
	defer c.Close()
	// Loop to read user input, send to server, and receive a reply.
	for {
		reader := bufio.NewReader(os.Stdin)
		fmt.Print(">> ")
		
		text, err := reader.ReadString('\n') // Read user input.
		if err != nil {
			fmt.Println("Error reading input:", err)
			return
		}
		
		trimmedText := strings.TrimSpace(text)
		
		_, err = fmt.Fprintf(c, trimmedText+"\n") // Send user input to the server.
		if err != nil {
			fmt.Println("Error writing to server:", err)
			return
		}
		if trimmedText == "STOP" {
			fmt.Println("TCP client exiting...")
			return
		}
		message, err := bufio.NewReader(c).ReadString('\n') // Read server's reply.
		if err != nil {
			fmt.Println("Error reading from server:", err)
			return
		}
		
		fmt.Print("->: " + message)
	}
}

Output

$ go run main.go localhost:8001
>> Hello there!
->: 2025-09-02T19:27:47+05:30
>> This is great!
->: 2025-09-02T19:27:55+05:30
>> STOP
TCP client exiting...

The TCPserver communicates with this client.Sending “Hello” from TCPclient is an example.To end the connection, say “go!” and then “STOP.”

From lower-level TCP connections to higher-level HTTP interactions, these examples cover the essentials of network programming in Go and offer a strong foundation for creating a variety of network-enabled applications.

You can also read Flags In GoLang: A Quick Guide To Command-Line Arguments

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index