Golang Context的正确样式和用法是什么? [英] What is the proper style and usage of golang Context?

查看:45
本文介绍了Golang Context的正确样式和用法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是golang的新手,并试图更好地了解上下文.

I am new to golang and trying to get a better understanding of context.

在以下代码段中,对我来说似乎已经用上下文实例化了 computeService .为什么在调用 Stop()时必须再次将其传递给 .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
}

在我看来,将ctx传递到 compute.NewService(),然后再次传递到 stopTaggedMachines()

It seems redundant to me that I pass ctx into compute.NewService(), then again into stopTaggedMachines()

这真的是上下文的正确约定或用法吗?为什么我对 svc.Instances.Stop(project,zone,v.Name).Context(ctx).Do()的调用需要再次传递 ctx 一个参数?

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)返回 InstanceStopCall

通过调用 Context(ctx),您可以设置要在此调用的Do方法中使用的上下文.如果上下文被取消,这将允许HTTP请求中止.

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.

Stop方法可能需要很长时间(以分钟为单位).这样,用户可以取消等待VM关闭的操作.

The Stop method can take a long time (as in minutes). This allows a user to cancel waiting for a VM to shutdown.

这篇关于Golang Context的正确样式和用法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆