当前位置:首页 > 文章列表 > Golang > Go问答 > 使用 Golang 客户端库向 GCP 计算批量发出请求

使用 Golang 客户端库向 GCP 计算批量发出请求

来源:stackoverflow 2024-03-09 10:27:24 0浏览 收藏

小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《使用 Golang 客户端库向 GCP 计算批量发出请求》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

问题内容

是否可以使用 Go 的 Google API 客户端库执行批量请求?

更准确地说,我想删除一些磁盘;如果我可以避免对每个磁盘的请求,那就太好了。

我指的是批量请求功能: https://cloud.google.com/compute/docs/api/how-tos/batch

我正在使用的客户端库: https://github.com/googleapis/google-api-go-client

似乎还有另一个客户端库,但不支持计算引擎,只有元数据(?): https://github.com/GoogleCloudPlatform/google-cloud-go


解决方案


我不确定,但我认为这是可以完成的,因为我们可以使用 api 调用删除磁盘。 批量请求由多个api调用组合成一个http请求,可以发送到API discovery document中指定的batchpath。默认路径为/batch/api_name/api_version。

Example看一下批量请求Here的格式

// method id "compute.disks.delete":

type DisksDeleteCall struct {
    s          *Service
    project    string
    zone       string
    disk       string
    urlParams_ gensupport.URLParams
    ctx_       context.Context
    header_    http.Header
}

// Delete: Deletes the specified persistent disk. Deleting a disk
// removes its data permanently and is irreversible. However, deleting a
// disk does not delete any snapshots previously made from the disk. You
// must separately delete snapshots.
// For details, see https://cloud.google.com/compute/docs/reference/latest/disks/delete
func (r *DisksService) Delete(project string, zone string, disk string) *DisksDeleteCall {
    c := &DisksDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
    c.project = project
    c.zone = zone
    c.disk = disk
    return c
}

// RequestId sets the optional parameter "requestId": An optional
// request ID to identify requests. Specify a unique request ID so that
// if you must retry your request, the server will know to ignore the
// request if it has already been completed.
//
// For example, consider a situation where you make an initial request
// and the request times out. If you make the request again with the
// same request ID, the server can check if original operation with the
// same request ID was received, and if so, will ignore the second
// request. This prevents clients from accidentally creating duplicate
// commitments.
//
// The request ID must be a valid UUID with the exception that zero UUID
// is not supported (00000000-0000-0000-0000-000000000000).
func (c *DisksDeleteCall) RequestId(requestId string) *DisksDeleteCall {
    c.urlParams_.Set("requestId", requestId)
    return c
}

// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *DisksDeleteCall) Fields(s ...googleapi.Field) *DisksDeleteCall {
    c.urlParams_.Set("fields", googleapi.CombineFields(s))
    return c
}

// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *DisksDeleteCall) Context(ctx context.Context) *DisksDeleteCall {
    c.ctx_ = ctx
    return c
}

// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *DisksDeleteCall) Header() http.Header {
    if c.header_ == nil {
        c.header_ = make(http.Header)
    }
    return c.header_
}

func (c *DisksDeleteCall) doRequest(alt string) (*http.Response, error) {
    reqHeaders := make(http.Header)
    for k, v := range c.header_ {
        reqHeaders[k] = v
    }
    reqHeaders.Set("User-Agent", c.s.userAgent())
    var body io.Reader = nil
    c.urlParams_.Set("alt", alt)
    c.urlParams_.Set("prettyPrint", "false")
    urls := googleapi.ResolveRelative(c.s.BasePath, "{project}/zones/{zone}/disks/{disk}")
    urls += "?" + c.urlParams_.Encode()
    req, _ := http.NewRequest("DELETE", urls, body)
    req.Header = reqHeaders
    googleapi.Expand(req.URL, map[string]string{
        "project": c.project,
        "zone":    c.zone,
        "disk":    c.disk,
    })
    return gensupport.SendRequest(c.ctx_, c.s.client, req)
}

// Do executes the "compute.disks.delete" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *DisksDeleteCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
    gensupport.SetOptions(c.urlParams_, opts...)
    res, err := c.doRequest("json")
    if res != nil && res.StatusCode == http.StatusNotModified {
        if res.Body != nil {
            res.Body.Close()
        }
        return nil, &googleapi.Error{
            Code:   res.StatusCode,
            Header: res.Header,
        }
    }
    if err != nil {
        return nil, err
    }
    defer googleapi.CloseBody(res)
    if err := googleapi.CheckResponse(res); err != nil {
        return nil, err
    }
    ret := &Operation{
        ServerResponse: googleapi.ServerResponse{
            Header:         res.Header,
            HTTPStatusCode: res.StatusCode,
        },
    }
    target := &ret
    if err := gensupport.DecodeResponse(target, res); err != nil {
        return nil, err
    }
    return ret, nil
    // {
    //   "description": "Deletes the specified persistent disk. Deleting a disk removes its data permanently and is irreversible. However, deleting a disk does not delete any snapshots previously made from the disk. You must separately delete snapshots.",
    //   "httpMethod": "DELETE",
    //   "id": "compute.disks.delete",
    //   "parameterOrder": [
    //     "project",
    //     "zone",
    //     "disk"
    //   ],
    //   "parameters": {
    //     "disk": {
    //       "description": "Name of the persistent disk to delete.",
    //       "location": "path",
    //       "required": true,
    //       "type": "string"
    //     },
    //     "project": {
    //       "description": "Project ID for this request.",
    //       "location": "path",
    //       "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?))",
    //       "required": true,
    //       "type": "string"
    //     },
    //     "requestId": {
    //       "description": "An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed.\n\nFor example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments.\n\nThe request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).",
    //       "location": "query",
    //       "type": "string"
    //     },
    //     "zone": {
    //       "description": "The name of the zone for this request.",
    //       "location": "path",
    //       "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?",
    //       "required": true,
    //       "type": "string"
    //     }
    //   },
    //   "path": "{project}/zones/{zone}/disks/{disk}",
    //   "response": {
    //     "$ref": "Operation"
    //   },
    //   "scopes": [
    //     "https://www.googleapis.com/auth/cloud-platform",
    //     "https://www.googleapis.com/auth/compute"
    //   ]
    // }

}

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《使用 Golang 客户端库向 GCP 计算批量发出请求》文章吧,也可关注golang学习网公众号了解相关技术文章。

版本声明
本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
真我12 Pro系列即将亮相国内市场,潜望式长焦镜头备受关注真我12 Pro系列即将亮相国内市场,潜望式长焦镜头备受关注
上一篇
真我12 Pro系列即将亮相国内市场,潜望式长焦镜头备受关注
正确的关闭渠道方式
下一篇
正确的关闭渠道方式
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    542次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    508次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    497次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    484次学习
查看更多
AI推荐
  • 毕业宝AIGC检测:AI生成内容检测工具,助力学术诚信
    毕业宝AIGC检测
    毕业宝AIGC检测是“毕业宝”平台的AI生成内容检测工具,专为学术场景设计,帮助用户初步判断文本的原创性和AI参与度。通过与知网、维普数据库联动,提供全面检测结果,适用于学生、研究者、教育工作者及内容创作者。
    23次使用
  • AI Make Song:零门槛AI音乐创作平台,助你轻松制作个性化音乐
    AI Make Song
    AI Make Song是一款革命性的AI音乐生成平台,提供文本和歌词转音乐的双模式输入,支持多语言及商业友好版权体系。无论你是音乐爱好者、内容创作者还是广告从业者,都能在这里实现“用文字创造音乐”的梦想。平台已生成超百万首原创音乐,覆盖全球20个国家,用户满意度高达95%。
    33次使用
  • SongGenerator.io:零门槛AI音乐生成器,快速创作高质量音乐
    SongGenerator
    探索SongGenerator.io,零门槛、全免费的AI音乐生成器。无需注册,通过简单文本输入即可生成多风格音乐,适用于内容创作者、音乐爱好者和教育工作者。日均生成量超10万次,全球50国家用户信赖。
    30次使用
  •  BeArt AI换脸:免费在线工具,轻松实现照片、视频、GIF换脸
    BeArt AI换脸
    探索BeArt AI换脸工具,免费在线使用,无需下载软件,即可对照片、视频和GIF进行高质量换脸。体验快速、流畅、无水印的换脸效果,适用于娱乐创作、影视制作、广告营销等多种场景。
    34次使用
  • SEO标题协启动:AI驱动的智能对话与内容生成平台 - 提升创作效率
    协启动
    SEO摘要协启动(XieQiDong Chatbot)是由深圳协启动传媒有限公司运营的AI智能服务平台,提供多模型支持的对话服务、文档处理和图像生成工具,旨在提升用户内容创作与信息处理效率。平台支持订阅制付费,适合个人及企业用户,满足日常聊天、文案生成、学习辅助等需求。
    36次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码