Google Cloud Golang: How to parse project/zone/instance from instance URL?

Viewed 143

I'm using compute.NewRegionInstanceGroupManagersService's ListManagedInstances call which returns ManagedInstance's.

ManagedInstance has a field Instance which is an instance url, like https://www.googleapis.com/compute/v1/projects/my-project/zones/us-central1-b/instances/instance-group-z0hf

Now I would like to get more details about this particular instance. So using InstanceService's Get call, the function signature looks like this:

func (r *InstancesService) Get(project string, zone string, instance string) *InstancesGetCall

What's the best way to parse the instance URL (see above) into its project, zone and instance parts? Or is there a way of using another method to pass the instance URL directly?

2 Answers

you could do something like this,

  • parse the URL to get its path
  • split the path by slash component
  • iterate the parts,
  • locate static strings
  • take the next value and assign it appropriately.
package main

import (
    "fmt"
    "net/url"
    "strings"
)

func main() {
    s := "https://www.googleapis.com/compute/v1/projects/my-project/zones/us-central1-b/instances/instance-group-z0hf"
    u, err := url.Parse(s)
    if err != nil {
        panic(err)
    }

    parts := strings.Split(u.Path, "/")

    var project string
    var zone string
    var inst string

    for i := 0; i < len(parts); i++ {
        if parts[i] == "projects" && i+1 < len(parts) {
            project = parts[i+1]
            i++
        } else if parts[i] == "zones" && i+1 < len(parts) {
            zone = parts[i+1]
            i++
        } else if parts[i] == "instances" && i+1 < len(parts) {
            inst = parts[i+1]
            i++
        }
    }

    fmt.Println(project, zone, inst)
}
//Ouptput:
//my-project us-central1-b instance-group-z0hf

Alternatively, use the route engine from gorilla to create a new pattern, apply the route to the url path and collect output results. But it is more complex and probably not justified.

URLs are complex animals, the best way is using the library url.Parse. Then you can use a regex or split to extract the data you need from the path part.

Related