liveBook · Manning

Net package

As explained in Go in Practice, Second Edition

The Go net package provides portable interfaces for network I/O, including connections, listening, and address handling.

The Go net package supplies common interfaces for network I/O. Use it to connect as a client, listen as a server, and work directly with TCP, UDP, or other connection types. section 1.2.2

Core operations include:

  • Call net.Dial with a connection type and endpoint to establish a connection. section 1.2.2
  • Write requests through the connection and read responses with standard I/O helpers. section 1.2.2
  • Call net.Listen to accept incoming connections on a port. section 1.2.2
  • Use net/http when a higher-level HTTP client or server is more appropriate. section 1.2.2
Listing 1.3 Read TCP status
package main

import (
    "bufio"
    "fmt"
    "log"
    "net"
)

func main() {
    conn, err := net.Dial("tcp", "golang.org:80")     #1
    if err != nil {                               #2
        log.Fatal(err)
    }
    fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n")                 #3
    status, err := bufio.NewReader(conn).ReadString('\n')    #4
    if err != nil {        #5
        log.Fatal(err)
    }
    log.Println(status)    #6
}

A runnable TCP client dials golang.org on port 80, sends an HTTP/1.0 request, reads the response status, and handles errors. section 1.2.2

How Go in Practice, Second Edition covers it

How deep it goes
Demonstrates TCP dialing, request writing, response reading, and listening, while deferring deeper error-handling discussion.
Examples
Uses a TCP request to golang.org and contrasts it with an HTTP GET to example.com.
What you can do after
Apply it via Go's standard library to dial TCP endpoints, exchange data, and listen for incoming connections.
How it connects
Connects TCP, UDP, HTTP, standard I/O, and error handling through client and server networking tasks.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.