如何使用Go SDK for Google Cloud Platform获取项目ID?

I would like to fetch project-id in Go through the service account I am using in my system so that whenever that code runs on a compute instance in GCP, it should retrieve the project-id where the compute instance lies. Also if I run the code from my local machine, it should get the project-id same as "gcloud info" command gets from command line.

Does anyone have any idea which API to use in Go?

Figured out the correct 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, error := google.FindDefaultCredentials(ctx,compute.ComputeScope)
    if error != nil {
        fmt.Println(error)
    }

    fmt.Printf(credentials.ProjectID)
}

You can find out the project ID of the Compute Engine instance by using the Google Cloud API [1] with a GET request to http://metadata.google.internal/computeMetadata/v1/project/project-id with the header “Metadata-Flavor: Google” in order to be allowed.

It can be tested in the Cloud Shell or a secure shell (SSH) terminal by using:

curl "http://metadata.google.internal/computeMetadata/v1/project/project-id" -H "Metadata-Flavor: Google"

[1] : https://cloud.google.com/compute/docs/storing-retrieving-metadata#default