Complete Guide to the net Package in Go

Web
The Go net package provides a unified interface for TCP, UDP, and Unix network I/O operations.

The net package in Go provides a simple, uniform interface for network I/O, supporting TCP, UDP, IP, and Unix domain sockets. Use net.Listen to start a server and net.Dial to connect to one.

package main

import (
	"fmt"
	"net"
	"io"
)

func main() {
	// Start a TCP server
	listener, err := net.Listen("tcp", ":8080")
	if err != nil {
		panic(err)
	}
	defer listener.Close()

	// Accept a connection
	conn, err := listener.Accept()
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	// Read and write data
	buf := make([]byte, 1024)
	conn.Write([]byte("Hello from server"))
	n, _ := io.ReadFull(conn, buf)
	fmt.Printf("Received: %s\n", string(buf[:n]))
}