如何使用Go SDK for Google云平台获取项目ID?

moh*_*rma 5 go google-compute-engine google-cloud-platform

我想通过我在系统中使用的服务帐户获取 Go 中的项目 ID,以便每当该代码在 GCP 中的计算实例上运行时,它都应该检索计算实例所在的项目 ID。另外,如果我从本地计算机运行代码,它应该获得与从命令行获取的“gcloud info”命令相同的项目 ID。

有谁知道在 Go 中使用哪个 API 吗?

moh*_*rma 9

找出正确的 API。

package main

import (
    "fmt"
    "golang.org/x/net/context"
    "google.golang.org/api/compute/v1"
    "golang.org/x/oauth2/google"
)

func main() {
    ctx := context.Background()
    credentials, err := google.FindDefaultCredentials(ctx,compute.ComputeScope)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Printf(credentials.ProjectID)
}
Run Code Online (Sandbox Code Playgroud)

  • 使用“error”作为变量名并不是一个好主意 - 有一个具有此名称的_内置_接口 (4认同)