【问题标题】:Defining custom go struct tags for protobuf message fields为 protobuf 消息字段定义自定义 go struct 标签
【发布时间】:2019-01-20 13:35:08
【问题描述】:

我是grpc 的新手,我一直在尝试从网络服务器获取json 响应。然后存根可以从rpc 服务器请求json

在我的.proto 文件中,我创建了一个消息类型:

message Post {
    int64 number = 1;
    string now = 2;
    string name = 3;
}

但我无法编组number 字段,因为protoc 生成带有number 标签的结构pb.go 文件:

{
        "no": "23",
        "now": "12:06:46",
        "name": "bob"
}

如何强制Message 使用除消息字段的小写名称之外的标记进行“转换”?比如使用json标签no,即使Message中的字段名是number

【问题讨论】:

    标签: go protocol-buffers grpc


    【解决方案1】:

    您可以使用 json_name 在 proto 消息定义上设置 proto3 字段选项

    message Post {
        int64 number = 1 [json_name="no"];
        string now = 2;
        string name = 3;
    }
    

    link to the docs

    【讨论】:

    • 我已经尝试过了,编译后的结构字段将具有以下标签:Number string protobuf:"bytes,5,opt,name=no,json=com,proto3" json:"number ,omitempty"``
    • .proto文件中的json_name选项与生成的json标签无关,而是与官方protobuf-to-JSON映射中使用的名称:developers.google.com/protocol-buffers/docs/proto3#json,即在jsonpb 包中实现。 reference
    • 伙计,你成就了我的一周!非常感谢。
    【解决方案2】:
    import "github.com/gogo/protobuf/gogoproto/gogo.proto";
    
    // Result example:
    // type Post struct {
    //    Number int64 `protobuf:"bytes,1,opt,name=number,json=no1,proto3" json:"no2"`
    // }
    message Post {
        int64 number = 1 [json_name="no1", (gogoproto.jsontag) = "no2"];
    }
    

    ,在哪里:

    • no1 - jsonpb marshal/unmarshal
    • 的新名称
    • no2 - json marshal/unmarshal
    • 的新名称

    jsonpb 示例:

    import (
        "bytes"
        "testing"
        "encoding/json"
    
        "github.com/golang/protobuf/jsonpb"
        "github.com/stretchr/testify/require"
    )
    
    func TestJSON(t *testing.T) {
        msg := &Post{
            Number: 1,
        }
    
        buf := bytes.NewBuffer(nil)
    
        require.NoError(t, (&jsonpb.Marshaler{}).Marshal(buf, msg))
        require.Equal(t, `{"no1":1}`, buf.String())
    
        buf.Truncate(0)
    
        require.NoError(t, json.NewEncoder(buf).Encode(msg))
        require.Equal(t, `{"no2":1}`, buf.String())
    }
    

    更多关于protobuf的信息extensions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-08
      • 2022-09-30
      • 1970-01-01
      • 2018-03-18
      • 1970-01-01
      • 1970-01-01
      • 2019-07-07
      • 1970-01-01
      相关资源
      最近更新 更多