如何使用Go列出Google Cloud Platform上正在运行的实例

I'm trying to learn Go by managing Google Cloud Platform. I didn't understand how to use related functions about Compute. The goal is listing instances with some go code.

This is https://godoc.org/google.golang.org/api/compute/v1#InstancesService.List the related function.

func (r *InstancesService) List(project string, zone string) *InstancesListCall

There are two structs, InstancesService and InstancesListCall

As far as i understand i should define these structs but it's not clear the things should be defined in the structs. I've searched for examples but many of them using rest calls instead of golang api. Have any idea how to list instances with go?

i had to write something like this today and googling for examples turned up surprisingly little. i've written up what i learned below, however, i'm quite new to golang so maybe smarter people can suggest improvements.

my work in progress is at: https://github.com/grenade/rubberneck


if you want to run your go program from a development pc that is not on the google compute platform:

package main

import (

  "golang.org/x/net/context"
  "google.golang.org/api/compute/v1"
  "golang.org/x/oauth2/google"

  "fmt"
  "strings"
)

func main() {
  projects := [...]string{
    "my-project-one",
    "my-project-two",
  }
  filters := [...]string{
    "status = RUNNING",
    "name != my-uninteresting-instance-one",
    "name != my-uninteresting-instance-two",
  }

  ctx := context.Background()
  client, err := google.DefaultClient(ctx,compute.ComputeScope)
  if err != nil {
    fmt.Println(err)
  }
  computeService, err := compute.New(client)
  for _, project := range projects {
    zoneListCall := computeService.Zones.List(project)
    zoneList, err := zoneListCall.Do()
    if err != nil {
      fmt.Println("Error", err)
    } else {
      for _, zone := range zoneList.Items {
        instanceListCall := computeService.Instances.List(project, zone.Name)
        instanceListCall.Filter(strings.Join(filters[:], " "))
        instanceList, err := instanceListCall.Do()
        if err != nil {
          fmt.Println("Error", err)
        } else {
          for _, instance := range instanceList.Items {
            if workerType, isWorker := instance.Labels["worker-type"]; isWorker {
              m := strings.Split(instance.MachineType, "/")
              fmt.Printf("cloud: gcp, zone: %v, name: %v, instance id: %v, machine type: %v, worker type: %v, launch time: %v
",
                zone.Name,
                instance.Name,
                instance.Id,
                m[len(m)-1],
                workerType,
                instance.CreationTimestamp)
            }
          }
        }
      }
    }
  }
}