go-micro 微服务学习笔记(2)
使用protobuf传输数据
通过.proto自动生成json接口数据时,会默认添加omitempty,此时若字段为空(例如空串,0,nil),则返回的json数据会忽略该字段,如下图自动生成的数据。
通过查阅其源码(路径protoc-gen-micro/generator/generator.go),可以发现其生成时会自动添加 omitempty字段,如下:
// Generate the type, methods and default constant definitions for this Descriptor.
func (g *Generator) generateMessage(message *Descriptor) {
topLevelFields := []topLevelField{}
oFields := make(map[int32]*oneofField)
...
tag := fmt.Sprintf("protobuf:%s json:%q", g.goTag(message, field, wiretype), jsonName+",omitempty")
oneof := field.OneofIndex != nil
...
}
则可根据自己的需求进行修改,再此就不过多讲述。而如果想让结果为空与否都返回,可以去掉其json字段中的omitempty字段,即可。