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流式响应解码难题:runtime.JSONPb.Decode返回nil值的有效解决方案

本文分析并解决使用HTTP请求gRPC-Gateway流式响应时,解码返回值失败的问题。问题表现为:HTTP请求的流式响应体内容正确,但runtime.jsonpb.Decode却始终返回nil值。

问题描述:

原始代码中,HTTP请求的流式响应体如下:

{"result":{"code":1,"msg":"1111"}}{"result":{"code":2,"msg":"2222"}}{"result":{"code":3,"msg":"3333"}}{"result":{"code":4,"msg":"4444"}}{"result":{"code":5,"msg":"5555"}}{"result":{"code":6,"msg":"6666"}}

使用runtime.jsonpb.Decode解码时,结果却是一系列nil值。原因在于gRPC-Gateway返回的JSON数据额外封装了一层result字段。直接使用*pb.resp作为解码目标类型导致解码失败。

解决方案:

此问题可以通过以下三步解决:

升级gRPC-Gateway版本: 确保使用最新版本的github.com/grpc-ecosystem/grpc-gateway/v2,例如v2.4.0或更高版本,以避免兼容性问题。

修改proto文件: 在.proto文件中添加一个新的message,匹配gRPC-Gateway返回的JSON结构(包含result字段):

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

修改解码代码: 使用新的httpresp message作为解码目标类型,并使用指针接收解码结果:

var result *pb.httpresp // 使用 *pb.httpresperr := dencoder.Decode(&result) // 使用 &result,传入指针

修改后的单元测试代码示例:

package mainimport (    "bytes"    "context"    "net/http"    "test/pb"    "testing"    "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"    "google.golang.org/grpc")func TestHttpRespStream(t *testing.T) {    // ... (其余代码保持不变) ...    for {        var result *pb.httpresp // 使用 *pb.httpresp        err := dencoder.Decode(&result) // 使用 &result        if err == nil {            t.Logf("resp: %+v", result)        } else {            t.Logf("%+v", err)            break        }    }}

通过以上修改,即可成功解码gRPC-Gateway返回的流式响应数据。 记住要重新生成代码以反映.proto文件的更改。

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

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

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
Go语言中,包初始化和变量赋值过程中如何避免局部变量遮蔽全局变量?
上一篇 2025年12月15日 05:33:53
Go语言除了channel,还有什么其他阻塞程序的方法?
下一篇 2025年12月15日 05:34:09

相关推荐

发表回复

登录后才能评论
关注微信