在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/GO  網(wǎng)絡(luò)安全/ protobuf3的坑

protobuf3的坑

問(wèn)題描述

protobuf由2升到3之后有個(gè)很煩人的坑:

當(dāng)我返回的值是默認(rèn)值時(shí),protobuf會(huì)自動(dòng)幫我忽略這個(gè)字段

相關(guān)代碼

message UserInfo{
    bool IsAuth = 1;
    string Name = 2;
}

如果IsAuth是false的時(shí)候返回的就是{"Name":"xxxx"}
如果IsAuth是true時(shí),返回的是{"IsAuth":true,"Name":"xxxxx"}

類(lèi)似的問(wèn)題還有很多int32=0,string=""的時(shí)候都會(huì)忽略字段

問(wèn)題來(lái)了

我們跟前端的交互用的是jsonrpc,這個(gè)丟失的字段讓前端處理起來(lái)不是很友好,不知道有沒(méi)有什么辦法解決這種問(wèn)題?

回答
編輯回答
吢丕

不能直接在 proto協(xié)議定義文件中達(dá)成么

2017年7月20日 14:53
編輯回答
離夢(mèng)

有更好的解決辦法的。
proto生成的文件還是最好不要去修改它,存在即為合理。
可以去看看一下這個(gè)。

var pbMarshaler jsonpb.Marshaler

func init() {
    pbMarshaler = jsonpb.Marshaler{
        EmitDefaults: true,
        OrigName:     true,
        EnumsAsInts:  true,
    }
}

有Marshal方法 可以把pb對(duì)象讀到buffer,剩下的就是 buffer.Bytes()了。
這種方式很方便的,建議使用。

2018年2月27日 03:05
編輯回答
青檸
type Req struct {
    Type       int32  `protobuf:"varint,5,opt,name=type" json:"type,omitempty"`
}

刪掉生成的 pb.go 文件的 omitempty

type Req struct {
    Type       int32  `protobuf:"varint,5,opt,name=type" json:"type"`
}

這樣就OK了

2018年4月7日 00:17