Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 
", 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
356 views
Welcome To Ask or Share your Answers For Others

1 Answer

Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...