Chapter 13. sharing work: Goroutines and Channels
Working on one thing at a time isn’t always the fastest way to finish a task. Some big problems can be broken into smaller tasks. Goroutines let your program work on several different tasks at once. Your goroutines can coordinate their work using channels, which let them send data to each other and synchronize so that one goroutine doesn’t get ahead of another. Goroutines let you take full advantage of computers with multiple processors, so that your programs run as fast as possible!
Retrieving web pages
This chapter is going to be about finishing work faster by doing several tasks simultaneously. But first, we need a big task that we can break into little parts. So bear with us for a couple pages while we set the scene...
The smaller a web page is, the faster it loads in visitors’ browsers. We need a tool that can measure the sizes of pages, in bytes.
This shouldn’t be too difficult, thanks to Go’s standard library. The program below uses the net/http
package to connect to a site and retrieve a web page with just a few function calls.
We pass the URL of the site we want to the http.Get
function. It will return an http.Response
object, plus any error it encountered.
The http.Response
object is a struct with a Body
field that ...
Get Head First Go now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.