如何在 gRPC 流拦截器中获取消息的值

huangapple go评论71阅读模式
英文:

How to get message value in gRPC stream interceptor

问题

我在服务器端实现了一个 gRPC 流拦截器,代码如下:

// 定义服务:
// rpc searchProducts(google.protobuf.StringValue) returns (stream Product);

func (w *wrappedStream) RecvMsg(m interface{}) error {
    log.Printf("%T, %v", m, m)
    return w.ServerStream.RecvMsg(m)
}

// 打印日志:
// *wrapperspb.StringValue, 

使用 %T 可以正确打印出消息类型,但使用 %v 打印的消息值为空白。

我确定服务器端接收到了正确的消息,因为它向客户端返回了正确的内容。

在客户端中,拦截器包装器 RecvMsg 也没有起作用。

英文:

I have implement a gRPC stream interceptor in Server like this:

// Service define:
// rpc searchProducts(google.protobuf.StringValue) returns (stream Product);

func (w *wrappedStream) RecvMsg(m interface{}) error {
    log.Printf("%T, %v", m, m)
    return w.ServerStream.RecvMsg(m)
}

// Log print:
// *wrapperspb.StringValue, 

It can print the message type using %T correctly, but the message value printing by %v is just a blank.

I'm sure that Server received the right message, because it replied Client the right thing.

The interceptor wrapper RecvMsg is not working in Client too.

答案1

得分: 1

w.ServerStream.RecvMsg(m)将数据解组到m中,只需将打印语句移到RecvMsg()调用之后。

func (w *wrappedStream) RecvMsg(m interface{}) error {
    err := w.ServerStream.RecvMsg(m)
    return err
}

log.Printf("%T, %v", m, m)

请注意,我已经将代码中的打印语句移动到了RecvMsg()调用之后。

英文:

w.ServerStream.RecvMsg(m) will unmarshall data into m, just move print after RecvMsg() call.

func (w *wrappedStream) RecvMsg(m interface{}) error {
    err := w.ServerStream.RecvMsg(m)
    log.Printf("%T, %v", m, m)
    return err
}

huangapple
  • 本文由 发表于 2022年4月7日 21:43:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/71783280.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定