Created
December 21, 2017 00:49
-
-
Save grant/41d26d8546f6d7bf82dab1bb5458487f to your computer and use it in GitHub Desktop.
Produces a list of Google APIs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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