douhang5460 2019-06-26 06:54
浏览 45

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?

  • 写回答

1条回答 默认 最新

  • donglu5728 2019-06-26 07:34
    关注

    svc.Instances.Stop(project, zone, v.Name) returns InstanceStopCall

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码