Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
Grpc-Gateway流式响应解码失败:如何解决runtime.JSONPb.Decode返回nil值?_创想鸟

Grpc-Gateway流式响应解码失败:如何解决runtime.JSONPb.Decode返回nil值?

grpc-gateway流式响应解码失败:如何解决runtime.jsonpb.decode返回nil值?

Grpc-Gateway流式响应解码失败问题及解决方案

本文分析并解决使用Grpc-Gateway处理HTTP请求的流式响应解码失败问题。现象是:流式响应体打印正确,但runtime.jsonpb.Decode返回nil。

根本原因在于Grpc-Gateway版本过低和Proto文件定义与实际返回数据结构不符。旧代码直接将响应解码为pb.resp类型,而Grpc-Gateway实际返回包含result字段的JSON数据,导致解码失败。

解决方案:三步走

升级Grpc-Gateway: 将github.com/grpc-ecosystem/grpc-gateway升级到最新版本(例如v2.4.0或更高)。低版本可能存在兼容性问题或bug。

调整Proto文件定义: 由于响应包含result字段,需要在Proto文件中添加新的message来匹配。修改后的Proto文件如下:

message resp {  int32 code = 1;  string msg = 2;}message httpresp {  resp result = 1;}

httpresp message精确匹配Grpc-Gateway的JSON响应结构。

修改解码代码: 解码时使用pb.httpresp类型接收结果,并正确使用地址符&。修改后的解码代码:

    jsonb := new(runtime.JSONPb)    dencoder := jsonb.NewDecoder(resp.Body)    for {        var result *pb.Httpresp // 使用pb.Httpresp类型        err := dencoder.Decode(&result) // 使用地址符&        if err == nil {            t.Logf("resp: %+v", result)        } else {            t.Logf("%+v", err)            break        }    }

通过以上步骤,即可成功解析流式响应中的每个httpresp消息。修改后的单元测试代码将正确打印每个消息内容,验证问题已解决。

以上就是Grpc-Gateway流式响应解码失败:如何解决runtime.JSONPb.Decode返回nil值?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1385251.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
MongoDB子文档排序:如何高效地对嵌套文档进行排序?
上一篇 2025年12月15日 04:59:07
Go模板中如何用动态键访问Map数据?
下一篇 2025年12月15日 04:59:17

相关推荐

发表回复

登录后才能评论
关注微信