声明:版权所有,谢绝转载。
在 go 中使用 google protobuf,有两个可选用的包: goprotobuf(go 官方出品)和gogoprotobuf(gogo 组织出品 )。
gogoprotobuf 能够完全兼容 google protobuf。而且经过我一些测试,它生成大代码质量确实要比 goprotobuf 高一些,主要是它在 goprotobuf 之上 extend 了一些 option。这些 option 也是有级别区分的,有的 option 只能修饰 field,有的可以修饰 enum,有的可以修饰 message,有的是修饰 package(即对整个文件都有效)。下面一一说明其一些选项的意义。
另外,本文的所有 proto 示例都是 proto v3 格式。
1 gogoproto.goproto_enum_prefix
如果选项为 false,则生成的代码中不加 “E_”。
pb code:enum E {// option (gogoproto.goproto_enum_prefix) = false;A = 0;B = 2;}go code:const (// option (gogoproto.goproto_enum_prefix) = false;E_A E = 0E_B E = 2)orpb code:enum E {// option (gogoproto.goproto_enum_prefix) = false;A = 0;B = 2;}go code:const (A E = 0B E = 2)
2 gogoproto.goproto_getters
如果选项为 false,则不会为 message 的每个 field 生成一个 Get 函数。
pb code:message test {E e = 1;}go code:type Test struct {E *E `protobuf:"varint,1,opt,name=e,enum=test.E" json:"e,omitempty"`XXX_unrecognized []byte `json:"-"`}func (m *Test) GetE() E {if m != nil && m.E != nil {return *m.E}return A}orpb code:message test {option (gogoproto.goproto_getters) = false;E e = 1;}go code:type Test struct {E *E `protobuf:"varint,1,opt,name=e,enum=test.E" json:"e,omitempty"`XXX_unrecognized []byte `json:"-"`}
3 gogoproto.face
当这个选项为 true 的时候,会为 message 生成相应的 interface。
message test {option (gogoproto.goproto_getters) = false;option (gogoproto.face) = true;string msg = 1;}type Test struct {Msg *string `protobuf:"bytes,1,opt,name=msg" json:"msg,omitempty"`XXX_unrecognized []byte `json:"-"`}func (m *Test) Reset() { *m = Test{} }func (m *Test) String() string { return proto.CompactTextString(m) }func (*Test) ProtoMessage() {}func init() {proto.RegisterEnum("test.E", E_name, E_value)}type TestFace interface {Proto() github_com_gogo_protobuf_proto.MessageGetMsg() *string}func (this *Test) Proto() github_com_gogo_protobuf_proto.Message {return this}func (this *Test) TestProto() github_com_gogo_protobuf_proto.Message {return NewTestFromFace(this)}func (this *Test) GetMsg() *string {return this.Msg}func NewTestFromFace(that TestFace) *Test {this := &Test{}this.Msg = that.GetMsg()return this}
这个选项要求 goproto_getters 选项为 false,即只生成 interface 相应的 method。否则,你会收到如下 error:
panic: face requires getters to be disabled please use gogoproto.getters or gogoproto.getters_all and set it to falsegoroutine 1 [running]:github.com/gogo/protobuf/plugin/face.(*plugin).Generate(0x2086c00a0, 0x20870b780)/Users/Alex/bin/go/src/github.com/gogo/protobuf/plugin/face/face.go:164 +0x37dgithub.com/gogo/protobuf/protoc-gen-gogo/generator.(*Generator).runPlugins(0x2087001c0, 0x20870b780)/Users/Alex/bin/go/src/github.com/gogo/protobuf/protoc-gen-gogo/generator/generator.go:1008 +0x91github.com/gogo/protobuf/protoc-gen-gogo/generator.(*Generator).generate(0x2087001c0, 0x20870b780)/Users/Alex/bin/go/src/github.com/gogo/protobuf/protoc-gen-gogo/generator/generator.go:1047 +0x3e1github.com/gogo/protobuf/protoc-gen-gogo/generator.(*Generator).GenerateAllFiles(0x2087001c0)/Users/Alex/bin/go/src/github.com/gogo/protobuf/protoc-gen-gogo/generator/generator.go:994 +0x249main.main()/Users/Alex/bin/go/src/github.com/gogo/protobuf/protoc-gen-gogo/main.go:96 +0x31d
4 gogoproto.nullable
有没有注意到上面的示例中 Test 的成员 msg 类型为 string*,当你要向它赋值的时候,可能要写出如下代码:
var test Testtest.Msg = new(string)*test.Msg = "test.msg"ortest := Test{Msg:proto.String("hello")}
是不是感觉很麻烦?而且生成一堆临时对象,不利于 gc。此时如果 nullable 选项为 false,就不用这么麻烦了
pb code:message test {string msg = 1 [(gogoproto.nullable) = false];}go code:type Test struct {Msg string `protobuf:"bytes,1,opt,name=msg" json:"msg"`XXX_unrecognized []byte `json:"-"`}
严格地说,nullable 这个 option 是违背 protobuf 的初衷的。使用了它之后,message 序列化的时候,gogo 会为 message 的每个 field 设置一个值,而 google protobuf 则是要求如果一个 option 的 field 没有被赋值,则序列化的时候不会把这个成员序列化进最终结果的。gogo 官方的详尽解释是:
The protocol buffer specification states, somewhere, that you should be able to tell whether a field is set or unset. With the option nullable=false this feature is lost, since your non-nullable fields will always be set. It can be seen as a layer on top of protocol buffers, where before and after marshalling all non-nullable fields are set and they cannot be unset.
ref: https://godoc.org/code.google.com/p/gogoprotobuf/gogoproto
注意: bytes 成员不要使用这个 option,否则会收到编译警告 “WARNING: field Message.Data is a non-nullable bytes type, nullable=false has no effect”
5 gogoproto.customname
在生成的代码中修改成员的名称,这个选项在这种情况下非常有用:field 的名称与 message 的 method 的名称一样。
pb code:message test {option (gogoproto.goproto_getters) = false;string msg = 1 [(gogoproto.nullable) = false, (gogoproto.customname) = "MyMsg"];}go code:type Test struct {MyMsg string `protobuf:"bytes,1,opt,name=msg" json:"msg"`XXX_unrecognized []byte `json:"-"`}
类似的选项还有 gogoproto.customtype,不再赘述。
6 gogoproto.goproto_stringer
此选项不设置的时候,其为 true。当这个选项为 false 的时候,gogo 不再为 message 对一个的 struct 生成 String() 方法。这个选项建议不要设置为 false。
pb code:message test {option (gogoproto.goproto_stringer) = true;string msg = 1 [(gogoproto.nullable) = false, (gogoproto.customname) = "MyMsg"];}go code:type Test struct {MyMsg string `protobuf:"bytes,1,opt,name=msg" json:"msg"`XXX_unrecognized []byte `json:"-"`}func (m *Test) Reset() { *m = Test{} }func (m *Test) String() string { return proto.CompactTextString(m) }func (*Test) ProtoMessage() {}orpb code:option (gogoproto.goproto_getters_all) = false;message test {option (gogoproto.goproto_stringer) = false;string msg = 1 [(gogoproto.nullable) = false, (gogoproto.customname) = "MyMsg"];}go code:type Test struct {MyMsg string `protobuf:"bytes,1,opt,name=msg" json:"msg"`XXX_unrecognized []byte `json:"-"`}func (m *Test) Reset() { *m = Test{} }func (*Test) ProtoMessage() {}
7 gogoproto.gostring
这个选项为 message 级别,为 true 的时候,gogo 会为相应的 message 生成 GoString() 方法。如果想为所有的 message 生成之类函数,可以设置 package 级别的 gogoproto.stringer_all 为 true。
pb code:option (gogoproto.goproto_getters_all) = false;message test {option (gogoproto.gostring) = true;string msg = 1 [(gogoproto.nullable) = false, (gogoproto.customname) = "MyMsg"];}go code:type Test struct {MyMsg string `protobuf:"bytes,1,opt,name=msg" json:"msg"`XXX_unrecognized []byte `json:"-"`}func (m *Test) Reset() { *m = Test{} }func (m *Test) String() string { return proto.CompactTextString(m) }func (*Test) ProtoMessage() {}func init() {proto.RegisterEnum("test.E", E_name, E_value)}func (this *Test) GoString() string {if this == nil {return "nil"}s := strings.Join([]string{`&test.Test{` +`MyMsg:` + fmt.Sprintf("%#v", this.MyMsg),`XXX_unrecognized:` + fmt.Sprintf("%#v", this.XXX_unrecognized) + `}`}, ", ")return s}
gogoproto.stringer_all
pb code:option (gogoproto.goproto_getters_all) = false;option (gogoproto.gostring_all) = true;message test {string msg = 1 [(gogoproto.nullable) = false, (gogoproto.customname) = "MyMsg"];}go code:type Test struct {MyMsg string `protobuf:"bytes,1,opt,name=msg" json:"msg"`XXX_unrecognized []byte `json:"-"`}func (m *Test) Reset() { *m = Test{} }func (m *Test) String() string { return proto.CompactTextString(m) }func (*Test) ProtoMessage() {}func init() {proto.RegisterEnum("test.E", E_name, E_value)}func (this *Test) GoString() string {if this == nil {return "nil"}s := strings.Join([]string{`&test.Test{` +`MyMsg:` + fmt.Sprintf("%#v", this.MyMsg),`XXX_unrecognized:` + fmt.Sprintf("%#v", this.XXX_unrecognized) + `}`}, ", ")return s}
测试用例:
package mainimport ("fmt""strings")type Test struct {MyMsg string `protobuf:"bytes,1,opt,name=msg" json:"msg"`XXX_unrecognized []byte `json:"-"`}func (this *Test) GoString() string {if this == nil {return "nil"}s := strings.Join([]string{`&test.Test{` +`MyMsg:` + fmt.Sprintf("%#v", this.MyMsg),`XXX_unrecognized:` + fmt.Sprintf("%#v", this.XXX_unrecognized) + `}`}, ", ")return s}func main() {var test Testtest.MyMsg = "hello, world!"fmt.Printf("%#v\n", test)}
8 populate & populate_all
这个选项为 message 级别,当设置其值为 true 的时候,gogo 会为每个 message 生成一个 NewPopulated 函数。
pb code:option (gogoproto.populate_all) = true;message B {optional A A = 1 [(gogoproto.nullable) = false, (gogoproto.embed) = true];repeated bytes G = 2 [(gogoproto.customtype) = "github.com/gogo/protobuf/test/custom.Uint128", (gogoproto.nullable) = false];}go code:func NewPopulatedB(r randyExample, easy bool) *B {this := &B{}v2 := NewPopulatedA(r, easy)this.A = *v2if r.Intn(10) != 0 {v3 := r.Intn(10)this.G = make([]github_com_gogo_protobuf_test_custom.Uint128, v3)for i := 0; i < v3; i++ {v4 := github_com_gogo_protobuf_test_custom.NewPopulatedUint128(r)this.G[i] = *v4}}if !easy && r.Intn(10) != 0 {this.XXX_unrecognized = randUnrecognizedExample(r, 3)}return this}
如果 gogo 为 message 生成了 test 函数,这些函数就会调用 NewPopulated 函数。如果用户没有使用这个选项但是使用了 test 选项,则用户需自定义 NewPopulated 函数。
由于 oschina 对博文长度有限制,剩余部分转下文《gogoprotobuf 使用 (下)》。
https://my.oschina.net/alexstocks/blog/387031
