首页 > 解决方案 > 使用 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 调用?

标签: gogoogle-cloud-sdk

解决方案


我已经在 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))

推荐阅读