Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

go - What is the proper style and usage of golang Context?

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

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

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...