google-gcp example
Interacting with google's
gcp
using
google-cloud-go
client libraries.
Documentation and reference,
GitHub Webpage
OVERVIEW
The gcp
SDK for go provides APIs and utilities that developers can use
to build go applications that use gcp
services.
GO GET
Package compute
provides access to the Compute Engine API.
Package oauth2/google
provides support for making Oauth2
authorized and authenticated HTTP requests to Google APIs.
go get -u google.golang.org/api/compute/v1
go get -u golang.org/x/oauth2/google
And import them in your go code,
import "google.golang.org/api/compute/v1"
import "golang.org/x/oauth2/google"
INSTANTIATING
Each API has a,
New
function taking an *http.Client
and
- Returns an API-specific
*Service.
For example,
service, err := compute.New(httpClient)
The HTTP client you pass in to the service must be one
that automatically adds Google-supported Authorization
information to the requests.
CREDENTIALS - SERVICE ACCOUNTS
To get a service for gce
using your google service account
would be as follows,
ctx := context.Background()
// Reads credentials from the specified path.
computeService, err := compute.NewService(ctx, option.WithCredentialsFile(jsonPath))
if err != nil {
log.Fatal(err)
}
Where jsonPath
is your google service account file.
LETS USE THE SERVICE
Now that we have the service, lets use it.
Use the service to get your gce image list,
req := computeService.Images.List(project)
Or use the service to get your gce instance list,
req := computeService.Instances.List(project, zone)
RUN
go run gcp.go