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:
conn, e := Dial("tcp", "192.0.32.10:80")
conn, e := Dial("udp", "192.0.32.10:80")
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:
package main
import (
"fmt"
"http"
"io/ioutil"
)
func main() {
r, err := http.Get("http://www.google.com/robots.txt")
if err != nil {
fmt.Printf("%s\n", err.String())
return
}
b, err := ioutil.ReadAll(r.Body)
r.Body.Close()
if err == nil {
fmt.Printf("%s", string(b))
}
}