I am new to golang and trying to get a better understanding of context.
In the below snippet, it appears to me that I've instantiated my computeService
with a context. why do I have to pass it again to the .Context()
function when calling Stop()
?
package main
func stopTaggedMachines(ctx context.Context, svc *compute.Service, project, zone, tag string) ([]string, error) {
var instances []string
f := func(page *compute.InstanceList) error {
for _, v := range page.Items {
if v.Labels["gcp-idler-managed"] == "true" {
result, err := svc.Instances.Stop(project, zone, v.Name).Context(ctx).Do()
if err != nil {
log.Fatal(err)
}
fmt.Printf("[INFO] gcp-machine-idler: Instance in state %v, Stopping %v... Response: %v \n", v.Status, v.Name, result.HTTPStatusCode)
}
}
return nil
}
call := svc.Instances.List("my-project", "us-west1-b")
if err := call.Pages(oauth2.NoContext, f); err != nil {
return instances, nil
}
return instances, nil
}
func main() {
// Use oauth2.NoContext if there isn't a good context to pass in.
ctx := context.Background()
computeService, err := compute.NewService(ctx)
if err != nil {
log.Fatal(err)
}
stopTaggedMachines(ctx, computeService, "my-project", "us-west1-b", "gcp-idler-managed")
return
}
It seems redundant to me that I pass ctx into compute.NewService()
, then again into stopTaggedMachines()
Is this really the correct convention or usage of context? Why does my call to svc.Instances.Stop(project, zone, v.Name).Context(ctx).Do()
need to be passed ctx
yet again as a parameter?
svc.Instances.Stop(project, zone, v.Name)
returnsInstanceStopCall
By calling
Context(ctx)
you are setting the context to be used in this call's Do method. This allows the HTTP request to be aborted if the context is canceled.The Stop method can take a long time (as in minutes). This allows a user to cancel waiting for a VM to shutdown.