go - 使用 google.golang.org/api/discovery/v1 的 Golang 示例
问题描述
我正在尝试使用 Go 发现来调用还没有客户端库的 API。但我找不到一个例子。
目标是使用 net/http 替换:
func AnotherFunc() {
// get short-lived oauth access token so we can make authenticated API call
accessToken, _ := getOauthAccessToken()
client := &http.Client{}
rolesQueryString := ""
for _, r := range configs.CustomOwnerRoles {
rolesQueryString += "analysisQuery.accessSelector.roles=" +
url.QueryEscape(r) + "&"
}
// documentation for this api call can be found here:
// https://cloud.google.com/asset-inventory/docs/reference/rest/v1p4beta1/TopLevel/analyzeIamPolicy
// we're making a REST api call instead of using client libraries because this is a new
// API, and the client libraries haven't been generated for it yet.
req, err := http.NewRequest("GET", "https://cloudasset.googleapis.com/v1p4beta1/"+
configs.OrganizationID+
":analyzeIamPolicy?"+
rolesQueryString+
"&analysisQuery.identitySelector.identity="+
url.QueryEscape("user:"+user)+
"&analysisQuery.resourceSelector.fullResourceName="+
url.QueryEscape("//cloudresourcemanager.googleapis.com/projects/"+projectID)+
"&options.expandGroups=true", nil)
}
我想使用发现库,但仅此而已:
api := flag.String("api", "cloudasset", "api to query")
resource := flag.String("resource", "", "resource to generate")
version := flag.String("version", "v1p4beta1", "api version to query")
flag.Parse()
if *api == "" || *resource == "" {
flag.PrintDefaults()
log.Fatal("usage: go run schemagen.go -api $API -resource $RESOURCE -version $VERSION")
}
ctx := context.Background()
discoveryService, err := discovery.NewService(ctx)
if err != nil {
log.Fatal(fmt.Errorf("Error creating service: %v", err))
}
resp, err := discoveryService.Apis.GetRest(*api, *version).Fields("schemas").Do()
如何使用resp
来继续 API 调用?
解决方案
我已经在 go 中寻找了有关使用发现 API 的示例,我可以看到基本上没有什么可以轻松使用。
我找到了一篇 Medium 文章,其中包含一些使用 RESTFUL API 资源(例如Cloud Discovery Service )的指导。
我认为答案是您需要调用 resp.Body.Close() 以确保正确处理资源,稍后在示例中有几种获取数据的方法,因此您必须添加类似这个:
defer resp.Body.Close()
body, err := http.ioutil.ReadAll(resp.Body)
if err ≠ nil {
log.Failure(err)
}
log.Println(string(body))
推荐阅读
- io - 在 Julia 中列出 IO
- mysql - 如何计算 MySQL 查询中两个哈希之间的差异?
- php - PHP 更新表过早
- python - Winsock,获取 html 响应
- php - 如果客户碰巧在 Woocommerce 中以访客身份结账,我们可以将订单自动链接到客户的帐户吗?
- excel - 在继续之前关闭选项卡
- python - TypeError:列表索引必须是整数,而不是浮点数(Python2)
- mysql - SQL查询IN子句:传递列表时如何转义特殊字符
- python - Python 命令提示符中的制表符/缩进错误
- git - 在父存储库上 git pull 后合并子模块更改