2017-12-01 18:34
采纳率: 0%
浏览 517


I am building a client/server system in go, using gRPC and protobuf (and with a gRPC gateway to REST).

I use metadata in the context on the server side to carry authentication data from the client, and that works perfectly well.

Now, I'd like the server to set some metadata keys/values so that the client can get them, alongside with the response. How can I do that? Using SetHeader and SendHeader? Ideally, I'd like every single response from the server to integrate that metadata (can be seen as some kind of UnaryInterceptor, but on the response rather than the request?)

Here is the code for the server and for the client.

图片转代码服务由CSDN问答提供 功能建议

我正在使用gRPC和protobuf(以及通向REST的gRPC网关)构建客户端/服务器系统 。

我在其中使用元数据 服务器端的上下文可以携带来自客户端的身份验证数据,并且效果很好。

现在,我希望服务器设置一些元数据键/值,以便客户端 可以得到他们,以及回应。 我怎样才能做到这一点? 使用 SetHeader SendHeader ? 理想情况下,我希望服务器的每个响应都可以集成该元数据(可以看作是 UnaryInterceptor ,但是响应而不是请求吗?)


  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongluanban3536 2017-12-04 18:14

    I finally found my way:

    So basically, grpc.SetHeader() + grpc.SendHeader() and grpc.SetTrailer() are totally what I was looking for. On the client side, grpc.Header() and grpc.Trailer() functions need to be passed to the RPC call, and their argument is a metadata.MD object to be filled.

    On the client side, define your receiving metadata:

    var header, trailer metadata.MD

    Then, pass it to the SomeRPCCall() unary RPC:

    response, err := client.SomeRPCCall(

    And now, you can check what's in your metadata:

    for key, value := range header {
        fmt.Printf("%s => %s", key, value)
    for key, value := range trailer {
        fmt.Printf("%s => %s", key, value)

    On the server side, you can:

    • force the data to be sent right after the RPC is received (but before it's processed):

      grpc.SendHeader(ctx, metadata.New(map[string]string{"my-key": "my-value"}))

    • or set & send the metadata at the end of the RPC process (along with the Status):

      grpc.SetTrailer(ctx, metadata.New(map[string]string{"my-key": "my-value"}))

    打赏 评论

相关推荐 更多相似问题