Essential Go HTTP Client  Edit on GitHub      File Issue

GET with URL parameters and a JSON response

This example shows how to properly encode URL parameters for GET request and parse JSON output returned by Stack Exchange API returning information about Stack Overflow posts.

type postItem struct {
	Score int    `json:"score"`
	Link  string `json:"link"`
}

type postsType struct {
	Items []postItem `json:"items"`
}

values := url.Values{
	"order": []string{"desc"},
	"sort":  []string{"activity"},
	"site":  []string{"stackoverflow"},
}

// URL parameters can also be programmatically set
values.Set("page", "1")
values.Set("pagesize", "10")

uri := "https://api.stackexchange.com/2.2/posts?"
client := &http.Client{
	Timeout: 15 * time.Second,
}
resp, err := client.Get(uri + values.Encode())
if err != nil {
	log.Fatalf("http.Get() failed with '%s'\n", err)
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
	d, _ := ioutil.ReadAll(resp.Body)
	log.Fatalf("Request was '%s' (%d) and not OK (200). Body:\n%s\n", resp.Status, resp.StatusCode, string(d))
}

dec := json.NewDecoder(resp.Body)
var p postsType
err = dec.Decode(&p)
if err != nil {
	log.Fatalf("dec.Decode() failed with '%s'\n", err)
}

fmt.Println("Top 10 most recently active StackOverflow posts:")
fmt.Println("Score", "Link")
for _, post := range p.Items {
	fmt.Println(post.Score, post.Link)
}
Top 10 most recently active StackOverflow posts:
Score Link
0 https://stackoverflow.com/q/49189560
2 https://stackoverflow.com/q/23843329
0 https://stackoverflow.com/a/49189697
0 https://stackoverflow.com/a/49189696
1 https://stackoverflow.com/q/49189079
0 https://stackoverflow.com/q/49189695
1 https://stackoverflow.com/q/49188898
0 https://stackoverflow.com/q/35025270
0 https://stackoverflow.com/a/49189631
0 https://stackoverflow.com/q/49189317
  ↑ ↓ to navigate     ↵ to select     Esc to close