github.com/gogo/protobuf@v1.3.2/custom_types.md (about) 1 # Custom types 2 3 Custom types is a gogo protobuf extensions that allows for using a custom 4 struct type to decorate the underlying structure of the protocol message. 5 6 # How to use 7 8 ## Defining the protobuf message 9 10 ```proto 11 message CustomType { 12 optional ProtoType Field = 1 [(gogoproto.customtype) = "T"]; 13 } 14 15 message ProtoType { 16 optional string Field = 1; 17 } 18 ``` 19 20 or alternatively you can declare the field type in the protocol message to be 21 `bytes`: 22 23 ```proto 24 message BytesCustomType { 25 optional bytes Field = 1 [(gogoproto.customtype) = "T"]; 26 } 27 ``` 28 29 The downside of using `bytes` is that it makes it harder to generate protobuf 30 code in other languages. In either case, it is the user responsibility to 31 ensure that the custom type marshals and unmarshals to the expected wire 32 format. That is, in the first example, gogo protobuf will not attempt to ensure 33 that the wire format of `ProtoType` and `T` are wire compatible. 34 35 ## Custom type method signatures 36 37 The custom type must define the following methods with the given 38 signatures. Assuming the custom type is called `T`: 39 40 ```go 41 func (t T) Marshal() ([]byte, error) {} 42 func (t *T) MarshalTo(data []byte) (n int, err error) {} 43 func (t *T) Unmarshal(data []byte) error {} 44 func (t *T) Size() int {} 45 46 func (t T) MarshalJSON() ([]byte, error) {} 47 func (t *T) UnmarshalJSON(data []byte) error {} 48 49 // only required if the compare option is set 50 func (t T) Compare(other T) int {} 51 // only required if the equal option is set 52 func (t T) Equal(other T) bool {} 53 // only required if populate option is set 54 func NewPopulatedT(r randyThetest) *T {} 55 ``` 56 57 Check [t.go](test/t.go) for a full example 58 59 # Warnings and issues 60 61 `Warning about customtype: It is your responsibility to test all cases of your marshaling, unmarshaling and size methods implemented for your custom type.` 62 63 Issues with customtype include: 64 * <a href="https://github.com/gogo/protobuf/issues/199">A Bytes method is not allowed.<a/> 65 * <a href="https://github.com/gogo/protobuf/issues/132">Defining a customtype as a fake proto message is broken.</a> 66 * <a href="https://github.com/gogo/protobuf/issues/147">proto.Clone is broken.</a> 67 * <a href="https://github.com/gogo/protobuf/issues/125">Using a proto message as a customtype is not allowed.</a> 68 * <a href="https://github.com/gogo/protobuf/issues/200">cusomtype of type map can not UnmarshalText</a> 69 * <a href="https://github.com/gogo/protobuf/issues/201">customtype of type struct cannot jsonpb unmarshal</a> 70 * <a href="https://github.com/gogo/protobuf/issues/477">Customtype field does not get a generated 'getter' method</a> 71 * <a href="https://github.com/gogo/protobuf/issues/478">Repeated customtype fields generate slices without pointer to the custom type </a>