1// Copyright 2017 Google Inc. All Rights Reserved. 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15package main 16 17import ( 18 "encoding/json" 19 "errors" 20 "strings" 21) 22 23// APIsListServiceURL is the URL for the Google APIs Discovery Service 24const APIsListServiceURL = "https://www.googleapis.com/discovery/v1/apis" 25 26// A List represents the results of a call to the apis/list API. 27// https://developers.google.com/discovery/v1/reference/apis/list 28type List struct { 29 Kind string `json:"kind"` 30 DiscoveryVersion string `json:"discoveryVersion"` 31 APIs []*API `json:"items"` 32} 33 34// NewList unmarshals the bytes into a Document. 35func NewList(bytes []byte) (*List, error) { 36 var listResponse List 37 err := json.Unmarshal(bytes, &listResponse) 38 return &listResponse, err 39} 40 41// An API represents the an API description returned by the apis/list API. 42type API struct { 43 Kind string `json:"kind"` 44 ID string `json:"id"` 45 Name string `json:"name"` 46 Version string `json:"version"` 47 Title string `json:"title"` 48 Description string `json:"description"` 49 DiscoveryRestURL string `json:"discoveryRestUrl"` 50 DiscoveryLink string `json:"discoveryLink"` 51 Icons map[string]string `json:"icons"` 52 DocumentationLink string `json:"documentationLink"` 53 Labels []string `json:"labels"` 54 Preferred bool `json:"preferred"` 55} 56 57// APIWithNameAndVersion returns the API with a specified name and version. 58// If version is the empty string, the API name must be unique. 59func (a *List) APIWithNameAndVersion(name string, version string) (*API, error) { 60 var api *API // the API to return 61 versions := make([]string, 0) // the matching version names 62 // Scan the list for matching APIs and versions. 63 for _, item := range a.APIs { 64 if item.Name == name { 65 if version == "" || version == item.Version { 66 api = item 67 versions = append(versions, item.Version) 68 } 69 } 70 } 71 switch { 72 case len(versions) == 0: 73 return nil, errors.New(name + " was not found.") 74 case len(versions) > 1: 75 return nil, errors.New(name + " has multiple versions: " + strings.Join(versions, ", ")) 76 default: 77 return api, nil 78 } 79} 80