Skip to content

Instantly share code, notes, and snippets.

@grant
Created December 21, 2017 00:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grant/41d26d8546f6d7bf82dab1bb5458487f to your computer and use it in GitHub Desktop.
Save grant/41d26d8546f6d7bf82dab1bb5458487f to your computer and use it in GitHub Desktop.
Produces a list of Google APIs
package snippets
import (
"testing"
"github.com/stretchr/testify/assert"
"net/http"
"time"
"encoding/json"
"log"
"fmt"
"sort"
)
// https://www.googleapis.com/discovery/v1/apis
type Item struct {
Kind string `json:"kind"`
ID string `json:"id"`
Name string `json:"name"`
Version string `json:"version"`
Title string `json:"title"`
Description string `json:"description"`
DiscoveryRestURL string `json:"discoveryRestUrl"`
Icons struct {
X16 string `json:"x16"`
X32 string `json:"x32"`
} `json:"icons"`
DocumentationLink string `json:"documentationLink"`
Preferred bool `json:"preferred"`
}
type APIs struct {
Kind string `json:"kind"`
DiscoveryVersion string `json:"discoveryVersion"`
Items []Item `json:"items"`
}
func TestAPIVersions(t *testing.T) {
t.Log("Testing...")
assert := assert.New(t)
// Get the APIs
apis := getAPIs()
// Group APIs by title
apiByTitle := make(map[string][]*Item)
for _, apiItem := range apis.Items {
if apiByTitle[apiItem.Title] == nil {
apiByTitle[apiItem.Title] = []*Item{}
}
item := apiItem
apiByTitle[apiItem.Title] = append(apiByTitle[apiItem.Title], &item)
}
// Create the API strings
strings := []string{}
for _, apiGroup := range apiByTitle {
apiGroupString := apiGroup[0].Name + ": "
for _, apiItem := range apiGroup {
apiGroupString += apiItem.Version + " "
}
strings = append(strings, apiGroupString)
}
sort.Strings(strings)
// Print the APIs
for _, s := range strings {
fmt.Println("- " + s)
}
assert.Equal(3, 3, "good")
}
func getAPIs() *APIs {
url := "https://www.googleapis.com/discovery/v1/apis"
apis := &APIs{}
err := getJson(url, apis)
if err != nil {
log.Print("Unable to get JSON.")
panic(err)
return nil
}
return apis
}
func getJson(url string, target interface{}) error {
client := &http.Client{Timeout: 10 * time.Second}
r, err := client.Get(url)
if err != nil {
return err
}
defer r.Body.Close()
return json.NewDecoder(r.Body).Decode(target)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment