无效操作 - 不匹配的类型 string 和 nil

我正在尝试创建一个连接到 Google Cloud API 的 Go RESTful API。


发生了一个问题,描述为:无效操作:req.ParentId != nil(字符串和 nil 类型不匹配)


在创建本地 API 之前,我设法编写了一个 Go 模块,该模块可以连接、验证和从 Google Cloud 提取数据。我现在正在将该模块迁移为带有路径的 Restful API。


该模块的重点是获取所有当前正在运行的虚拟机的列表。


这是将其更改为restful API(有效)之前的模块:


package main


import (

    "fmt"


    "example.com/compute"


    "bytes"

)


func main() {

    buf := new(bytes.Buffer)


    // Get a message and print it.

    r.HandleFunc("/virtualmachines", ListAllInstances)

    err := compute.ListAllInstances(buf, "unique-string-id")

    if err != nil {

        panic(err)

    }

    fmt.Println(buf.String()) // <======= Print buf contents!

}



// new file:


package compute


// [START compute_instances_list_all]

import (

    "context"

    "fmt"

    "io"


    compute "cloud.google.com/go/compute/apiv1"

    "google.golang.org/api/iterator"

    computepb "google.golang.org/genproto/googleapis/cloud/compute/v1"

    "google.golang.org/protobuf/proto"

)


// listAllInstances prints all instances present in a project, grouped by their zone.

func ListAllInstances(w io.Writer, projectID string) error {

    // projectID := "your_project_id"

    ctx := context.Background()

    instancesClient, err := compute.NewInstancesRESTClient(ctx)



    if err != nil {

        return fmt.Errorf("NewInstancesRESTClient: %v", err)

    }

    defer instancesClient.Close()


    // Use the `MaxResults` parameter to limit the number of results that the API returns per response page.

    req := &computepb.AggregatedListInstancesRequest{

        Project:    projectID,

        MaxResults: proto.Uint32(6),

    }


    it := instancesClient.AggregatedList(ctx, req)

    fmt.Fprintf(w, "Instances found:\n")

    // Despite using the `MaxResults` parameter, you don't need to handle the pagination

    // yourself. The returned iterator object handles pagination

    // automatically, returning separated pages as you iterate over the results.

ParentId是罪魁祸首(滚动下方查看完整错误)。我插入的字符串在上面的代码中似乎不起作用。Google Cloud API 正在尝试找出项目的父 ID。如何修复上面的代码?


婷婷同学_
浏览 102回答 2
2回答

慕村225694

我有同样的问题,通过降级 1 commit 解决:&nbsp;go&nbsp;get&nbsp;google.golang.org/genproto@81c1377https://github.com/googleapis/go-genproto/commits/main

心有法竹

是您的代码中的错误还是只是在发布中?在出版物中我看到req&nbsp;:=&nbsp;&computepb.AggregatedListInstancesRequest{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Project:&nbsp;&nbsp;&nbsp;&nbsp;"unqie-string-id, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;MaxResults:&nbsp;proto.Uint32(16), &nbsp;&nbsp;&nbsp;&nbsp;}但应该是req&nbsp;:=&nbsp;&computepb.AggregatedListInstancesRequest{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Project:&nbsp;&nbsp;&nbsp;&nbsp;"unqie-string-id", &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;MaxResults:&nbsp;proto.Uint32(16), &nbsp;&nbsp;&nbsp;&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go