» Quick Introduction to Go » 2. Intermediate » 2.7 Net

Net

The net package in Go provides a foundation for networking-related operations. It includes functionality for working with network protocols, addresses, and connections.

Simple HTTP Client

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	// Make an HTTP GET request
	response, err := http.Get("https://jsonplaceholder.typicode.com/posts/1")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	defer response.Body.Close()

	// Read the response body
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return
	}

	// Print the response body
	fmt.Println(string(body))
}

Simple HTTP Server

package main

import (
	"fmt"
	"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
	// Handle incoming HTTP requests here
	fmt.Fprintf(w, "Hello, this is a simple HTTP server!")
}

func main() {
	// Register the handler function for the root endpoint "/"
	http.HandleFunc("/", handler)

	// Start the HTTP server on port 8080
	fmt.Println("Server listening on port 8080...")
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Println("Error:", err)
	}
}

Simple TCP Server

package main

import (
	"fmt"
	"net"
)

func handleConnection(conn net.Conn) {
	// Handle incoming connection
	defer conn.Close()

	// Read data from the connection
	buffer := make([]byte, 1024)
	n, err := conn.Read(buffer)
	if err != nil {
		fmt.Println("Error reading:", err)
		return
	}

	// Print received data
	fmt.Printf("Received: %s", buffer[:n])

	// Respond to the client
	conn.Write([]byte("Hello from the server!"))
}

func main() {
	// Listen for incoming connections on port 8080
	listener, err := net.Listen("tcp", ":8080")
	if err != nil {
		fmt.Println("Error listening:", err)
		return
	}
	defer listener.Close()

	fmt.Println("Server listening on port 8080...")

	// Accept incoming connections
	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("Error accepting connection:", err)
			continue
		}

		// Handle the connection in a separate goroutine
		go handleConnection(conn)
	}
}