dongmeng2687 2017-12-01 18:34 采纳率: 0%
浏览 668
已采纳

客户端上的gRPC上下文

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.

  • 写回答

1条回答 默认 最新

  • dongluanban3536 2017-12-04 18:14
    关注

    I finally found my way: https://github.com/grpc/grpc-go/blob/master/Documentation/grpc-metadata.md

    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(
        context.Background(),
        proto.MyMessage{},
        grpc.Header(&header),
        grpc.Trailer(&trailer),
    )
    

    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"}))

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格