4

我正在使用 GRPC/proto-buffers 在 GoLang 中编写我的第一个 API 端点。我对 GoLang 比较陌生。以下是我为测试用例编写的文件

package my_package

import (
    "context"
    "testing"

    "github.com/stretchr/testify/require"

    "google.golang.org/protobuf/types/known/structpb"
    "github.com/MyTeam/myproject/cmd/eventstream/setup"
    v1handler "github.com/MyTeam/myproject/internal/handlers/myproject/v1"
    v1interface "github.com/MyTeam/myproject/proto/.gen/go/myteam/myproject/v1"
)

func TestEndpoint(t *testing.T) {
    conf := &setup.Config{}

    // Initialize our API handlers
    myhandler := v1handler.New(&v1handler.Config{})

    t.Run("Success", func(t *testing.T) {

        res, err := myhandler.Endpoint(context.Background(), &v1interface.EndpointRequest{
            Data: &structpb.Struct{},
        })
        require.Nil(t, err)

        // Assert we got what we want.
        require.Equal(t, "Ok", res.Text)
    })


}

这是在上面包含的文件EndpointRequest中定义对象的方式:v1.go

// An v1 interface Endpoint Request object.
message EndpointRequest {
  // data can be a complex object.
  google.protobuf.Struct data = 1;
}

这似乎有效。

但现在,我想做一些稍微不同的事情。在我的测试用例中data,我想发送一个带有键/值对的地图/字典,而不是发送一个空对象A: "B", C: "D"。我该怎么做?如果我替换Data: &structpb.Struct{}Data: &structpb.Struct{A: "B", C: "D"},我会得到编译器错误:

invalid field name "A" in struct initializer
invalid field name "C" in struct initializer 
4

1 回答 1

5

您初始化的Data方式意味着您期待以下内容:

type Struct struct {
    A string
    C string
}

但是,structpb.Struct定义如下:

type Struct struct {   
    // Unordered map of dynamically typed values.
    Fields map[string]*Value `protobuf:"bytes,1,rep,name=fields,proto3" json:"fields,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
    // contains filtered or unexported fields
}

显然那里有点不匹配。您需要初始化Fields结构的映射并使用正确的方式设置Value字段。与您显示的代码等效的是:

Data: &structpb.Struct{
    Fields: map[string]*structpb.Value{
        "A": &structpb.Value{
            Kind: &structpb.Value_StringValue{
                StringValue: "B",
            },
        },
        "C": &structpb.Value{
            Kind: &structpb.Value_StringValue{
                StringValue: "D",
            },
        },
    },
}
于 2020-05-23T06:11:16.947 回答