gpt4 book ai didi

go - 使用google.golang.org/api/discovery/v1的Golang示例

转载 作者:行者123 更新时间:2023-12-01 22:21:16 28 4
gpt4 key购买 nike

我正在尝试使用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 article,其中包含一些使用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))

关于go - 使用google.golang.org/api/discovery/v1的Golang示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63383002/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com