Networking

All network related types and functions can be found in the package net. Oneof the most important functions in there is Dial. Whenyou Dial into a remote system the function returns a Conn interface type,which can be used to send and receive information. The function Dial neatlyabstracts away the network family and transport. So IPv4 or IPv6, TCP or UDP canall share a common interface.

Dialing a remote system (port 80) over TCP, then UDP and lastly TCP over IPv6looks like this18:

  1. conn, e := Dial("tcp", "192.0.32.10:80")
  2. conn, e := Dial("udp", "192.0.32.10:80")
  3. conn, e := Dial("tcp", "[2620:0:2d0:200::10]:80")

If there were no errors (returned in e), you can use conn to read and write.And conn implements the io.Reader and io.Writer interface. 19

But these are the low level nooks and crannies, you will almost always usehigher level packages, such as the http package. For instance a simple Get forhttp:

  1. package main
  2. import (
  3. "fmt"
  4. "http"
  5. "io/ioutil"
  6. )
  7. func main() {
  8. r, err := http.Get("http://www.google.com/robots.txt")
  9. if err != nil {
  10. fmt.Printf("%s\n", err.String())
  11. return
  12. }
  13. b, err := ioutil.ReadAll(r.Body)
  14. r.Body.Close()
  15. if err == nil {
  16. fmt.Printf("%s", string(b))
  17. }
  18. }