Dynamic Discovery Client For GCP Golang

Viewed 147

I've recently shifted from python to golang. I had been using python to work with GCP.

I used to pass in the scopes and mention the discovery client I wanted to create like this :

def get_client(scopes, api, version="v1"):
    service_account_json = os.environ.get("SERVICE_ACCOUNT_KEY_JSON", None)
    if service_account_json is None:
        sys.exit("Exiting !!! No SSH_KEY_SERVICE_ACCOUNT env var found.")
    credentials = service_account.Credentials.from_service_account_info(
        json.loads(b64decode(service_account_json)), scopes=scopes
    )
    return discovery.build(api, version, credentials=credentials, cache_discovery=False)

And this would create my desired discovery client, whether it be compute engine service or sqladmin

However in go I don't seem to find this. I found this : https://pkg.go.dev/google.golang.org/api/discovery/v1

For any client that I want to create I would've to import that and then create that, like this :

https://cloud.google.com/resource-manager/reference/rest/v1/projects/list#examples

package main


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

func main() {
        ctx := context.Background()

        c, err := google.DefaultClient(ctx, cloudresourcemanager.CloudPlatformScope)
        if err != nil {
                log.Fatal(err)
        }

        cloudresourcemanagerService, err := cloudresourcemanager.New(c)
        if err != nil {
                log.Fatal(err)
        }

        req := cloudresourcemanagerService.Projects.List()
        if err := req.Pages(ctx, func(page *cloudresourcemanager.ListProjectsResponse) error {
                for _, project := range page.Projects {
                        // TODO: Change code below to process each `project` resource:
                        fmt.Printf("%#v\n", project)
                }
                return nil
        }); err != nil {
                log.Fatal(err)
        }
}

So I've to import each client library to get the client for that. "google.golang.org/api/cloudresourcemanager/v1"

There's no dynamic creation of it.

Is it even possible, cause go is strict type checking

Thanks.

1 Answers

No, this is not possible with the Golang Google Cloud library.

You've nailed the point on the strict type checking, as it would definitely defeat the benefits of compile time type checking. It would also be a bad Golang practice to return different objects with different signatures, as we don't do duck typing and instead we rely on interface contracts.

Golang is boring and verbose, and it's like that by design :)

Related