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...