Go 如何在gRPC Protobuf中为接口创建类型?

Go 如何在gRPC Protobuf中为接口创建类型?,go,protocol-buffers,grpc,Go,Protocol Buffers,Grpc,我们为所有微服务提供了通用的身份验证服务。 当我们在响应中验证请求时,我们发送如下所示的JSON { Auth: bool, Body: interface{} } 在编写proto3语法时,我们如何编写接口类型之类的东西 我尝试过使用任何类型,但我无法使用它,因为我们需要在类型url中传递消息类型,而我无法生成该类型 用于响应的原始消息 message AuthResponse { bool Auth = 1; google.protobuf.Any Body

我们为所有微服务提供了通用的身份验证服务。 当我们在响应中验证请求时,我们发送如下所示的JSON

{
    Auth: bool,
    Body: interface{}
}
在编写proto3语法时,我们如何编写接口类型之类的东西

我尝试过使用任何类型,但我无法使用它,因为我们需要在类型url中传递消息类型,而我无法生成该类型

用于响应的原始消息

message AuthResponse {
    bool Auth = 1;
    google.protobuf.Any Body = 2;
}

有人能帮忙吗?

您可以将
正文
类型设置为
字节

如果您有一组预定义的类型,那么我建议您将
Auth
struct更改为如下内容:

type AuthResponse struct {
    Auth bool
    Body Encodable
}

// Encodable defines types that can be encoded into a byte slice.
type Encodable interface {
    Encode() []byte
}
然后,在每个类型上实现
Encode()[]字节

或者,如果
Body
字段可以是任何内容,那么除了
Encode
函数外,可能还有类似的解决方案:

type AuthResponse struct {
    Auth bool
    Body Encodable
}

// Encodable defines types that can be encoded into a byte slice.
type Encodable interface {
    Encode() []byte
}
func编码(接口{})[]字节

不过,在这种情况下,您可能需要使用一些反射魔法,以便将其编码为某个字节片。您甚至可以使用
JSON


我希望这有帮助

您可以将
正文
类型设置为
字节

如果您有一组预定义的类型,那么我建议您将
Auth
struct更改为如下内容:

type AuthResponse struct {
    Auth bool
    Body Encodable
}

// Encodable defines types that can be encoded into a byte slice.
type Encodable interface {
    Encode() []byte
}
然后,在每个类型上实现
Encode()[]字节

或者,如果
Body
字段可以是任何内容,那么除了
Encode
函数外,可能还有类似的解决方案:

type AuthResponse struct {
    Auth bool
    Body Encodable
}

// Encodable defines types that can be encoded into a byte slice.
type Encodable interface {
    Encode() []byte
}
func编码(接口{})[]字节

不过,在这种情况下,您可能需要使用一些反射魔法,以便将其编码为某个字节片。您甚至可以使用
JSON

我希望这有帮助