Google’s Cloud Platform documentation is top of the line. Even with the documentation though, it took me some time to figure out how to use the Cloud Vision API from a Go application running on a Compute Engine instance. All the right information is there, but it’s scattered. Below I’ve compiled this information into a few steps.
Authenticating with the Cloud Vision API involves more setup than the Cloud Datastore, Cloud Pub/Sub and Cloud Storage. The client libraries for the latter use Google Application Default Credentials and “just work” when running on a Compute Engine instance. In order to authenticate with the Cloud Vision API, you need to create a service account key and instruct the client library to use that key when sending API requests. See Authenticating to the Cloud Vision API for more details.
Prerequisites
- You have a Google Cloud project
- You have a Compute Engine instance and a service account associated with it (e.g. 123456789-compute@developer.gserviceaccount.com)
- You have a Go app that uses the Cloud Vision API client library
Steps
Enable the Cloud Vision API for your project: https://console.cloud.google.com/apis/api/vision.googleapis.com/overview
If you haven’t already, create a JSON key for the service account running the Compute Engine instance: https://console.cloud.google.com/iam-admin/serviceaccounts/project. Click the dropdown beside the service account, click Create Key and select the JSON key type.
Copy the key JSON file to your Compute Engine instance
When creating the Vision API client in Go, provide the service account file with
option.WithServiceAccountFile("/path/to/key.json")
:visionClient, err := vision.NewImageAnnotatorClient(ctx, option.WithServiceAccountFile("/path/to/key.json")) if err != nil { return nil, nil, errors.Wrap(err, "Error creating vision client") }