1. Protobuf⇢Go转换

    这里使用一个测试文件对照说明常用结构的protobuf到golang的转换。只说明关键部分代码,详细内容请查看完整文件。示例文件在目录下。

    在proto文件中使用package关键字声明包名,默认转换成go中的包名与此一致,如果需要指定不一样的包名,可以使用go_package选项:

    示例proto:

    1. // Test 测试
    2. message Test {
    3. int32 age = 1;
    4. int64 count = 2;
    5. double money = 3;
    6. float score = 4;
    7. string name = 5;
    8. bool fat = 6;
    9. bytes char = 7;
    10. // Status 枚举状态
    11. FAIL = 1;
    12. }
    13. Status status = 8;
    14. // Child 子结构
    15. message Child {
    16. string sex = 1;
    17. }
    18. Child child = 9;
    19. map<string, string> dict = 10;
    20. }

    转换结果:

    1. func (m *Test) GetAge() int32 {
    2. if m != nil {
    3. return m.Age
    4. }
    5. }

    枚举类型会生成对应名称的常量,同时会有两个map方便使用:

    定义一个简单的Service,有一个方法Test,接收一个Request参数,返回Response

    1. // TestService 测试服务
    2. service TestService {
    3. // Test 测试方法
    4. rpc Test(Request) returns (Response) {};
    5. }
    6. // Request 请求结构
    7. message Request {
    8. string name = 1;
    9. }
    10. // Response 响应结构
    11. message Response {

    生成的go代码中包含该Service定义的接口,客户端接口已经自动实现了,直接供客户端使用者调用,服务端接口需要由服务提供方实现。