14. Using the Go HTTP Client
Activity 14.01: Requesting Data from a Web Server and Processing the Response
Solution:
- Add the necessary imports:
package main import ( Â Â Â Â "encoding/json" Â Â Â Â "fmt" Â Â Â Â "io/ioutil" Â Â Â Â "log" Â Â Â Â "net/http" )
Here,
encoding/json
is used to parse the response and marshal it into the structs.fmt
is used to print out the counts andio/ioutil
is used to read in the response body.log
is used if something goes wrong to output the error.net/http
is what we use to do the GET request. - Create structs to parse the data:
type Names struct { Â Â Â Â Names []string `json:"names"` }
- Create a function called
getDataAndParseResponse()
that returns two integers:func getDataAndParseResponse() (int, int) {
- Send a
GET
request to the server:Â Â Â Â r, err := http...