The Go Programming Language

zhuting
1 min readApr 20, 2022

Go provides a collection of packages, grouped under net that make it easy to send and receive information through the Internet, make low-level connections, and set up servers, for which Go’s concurrency features are particularly useful.

Here is a simple program called fetch that fetches the content of each specified URL and prints it as uninterpreted text. It’s inspired by the invaluable utility curl .

package mainimport (  "fmt"  "io/ioutil"  "net/http"  "os")func main() {  for _, url := range os.Args[1:] {  resp, err := http.Get(url)  if err != nil {    fmt.Fprintf(os.Stderr, "fetch: %v\n", err)    os.Exit(1)  }  b, err := ioutil.ReadAll(resp.Body)  resp.Body.Close()  if err != nil {    fmt.Fprintf(os.Stderr, "fetch: reading %s: %v\n", url, err)    os.Exit(1)  }  fmt.Fprintf("%s", b)  }}

This program introduces functions from two packages, net/http and io/ioutil . The http.Get function makes an HTTP request and, if there is no error, returns the result in the response struct resp. The Body field of resp contains the server response as a readable stream.

Next, ioutil.ReadAll reads the entire response; the result is stored in b.

The Body stream is closed to avoid leaking resources and Printf writes the response to the standard output.

--

--