Let's say you want to fetch a set of github users and want to print their nicknames (Login
field in api.github.com
).
Given a User array example:
[{
"login": "simonjefford",
"id": 136,
"avatar_url": "https://avatars1.githubusercontent.com/u/136?v=3",
"gravatar_id": "",
"url": "https://api.github.com/users/simonjefford",
"html_url": "https://github.com/simonjefford",
"followers_url": "https://api.github.com/users/simonjefford/followers",
"following_url": "https://api.github.com/users/simonjefford/following{/other_user}",
"gists_url": "https://api.github.com/users/simonjefford/gists{/gist_id}",
"starred_url": "https://api.github.com/users/simonjefford/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/simonjefford/subscriptions",
"organizations_url": "https://api.github.com/users/simonjefford/orgs",
"repos_url": "https://api.github.com/users/simonjefford/repos",
"events_url": "https://api.github.com/users/simonjefford/events{/privacy}",
"received_events_url": "https://api.github.com/users/simonjefford/received_events",
"type": "User",
"site_admin": false
}]
You need a proper struct to handle it:
type Users []struct {
Login string `json:"login"`
ID int `json:"id"`
AvatarURL string `json:"avatar_url"`
GravatarID string `json:"gravatar_id"`
URL string `json:"url"`
HTMLURL string `json:"html_url"`
FollowersURL string `json:"followers_url"`
FollowingURL string `json:"following_url"`
GistsURL string `json:"gists_url"`
StarredURL string `json:"starred_url"`
SubscriptionsURL string `json:"subscriptions_url"`
OrganizationsURL string `json:"organizations_url"`
ReposURL string `json:"repos_url"`
EventsURL string `json:"events_url"`
ReceivedEventsURL string `json:"received_events_url"`
Type string `json:"type"`
SiteAdmin bool `json:"site_admin"`
}
I suggest you to use json-to-go to have a nice a clean struct given a json.
Then you can do the following:
package main
import (
"fmt"
"encoding/json"
"net/http"
"log"
"io/ioutil"
)
func main() {
response, err := http.Get("https://api.github.com/users?since=135")
if err != nil {
log.Fatal(err)
} else {
defer response.Body.Close()
users := UnmarshalUsers(response)
for _, u := range users {
//Print each user's Login nickname
fmt.Println(u.Login)
}
}
}
Where UnmarshalUsers
is
func UnmarshalUsers(r *http.Response) Users {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
var users Users
err = json.Unmarshal(body, &users)
if err != nil {
panic(err)
}
return users
}