The most important thing to explore in grequests is not the HTTP functions, but the RequestOptions struct. It is a very big struct that holds various kinds of information regarding the type of API method being used. If the REST method is GET, RequestOptions holds the Params property. If the method is a POST, the struct will have a Data property. Whenever we make a request to a URL endpoint, we get a response back. Let's look at the structure of the response. From the official documentation, the response looks like this:
type Response struct { Ok bool Error error RawResponse *http.Response StatusCode int Header http.Header }
The Ok property of the response holds information about whether a request was successful or not. If something went wrong, an error will be found in the Error property. RawResponse is the Go HTTP response that will be used by other functions of the grequests response. StatusCode and Header store the status codes of the response and header details, respectively. There are a few functions in Response that are useful
- Response.JSON()
- Response.XML()
- Response.String()
- Response.Bytes()
The data from the response can be filled into a generic map by the preceding functions. Let's take a look at an example, that is requestExample/jsonRequest.go:
package main import ( "github.com/levigross/grequests" "log" ) func main() { resp, err := grequests.Get("http://httpbin.org/get", nil) // You can modify the request by passing an optional
// RequestOptions struct if err != nil { log.Fatalln("Unable to make request: ", err) } var returnData map[string]interface{} resp.JSON(&returnData) log.Println(returnData) }
Here, we declared an interface to hold the JSON values. Then, we populated returnData (empty interface) using the resp.JSON function. This program prints the map instead of plain JSON.
In the next section, we'll understand how GitHub API version 3 works and use our knowledge of command-line arguments to develop a client that fetches useful information from the GitHub API.