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
