首页 > 其他 > 详细

Go使用protobuf

时间:2019-01-03 11:38:39      阅读:136      评论:0      收藏:0      [点我收藏+]

本文更新于2019-01-03。

  1. https://github.com/protocolbuffers/protobuf/releases下载protoc(如:Windows则下载protoc-3.6.1-win32.zip)。protoc命令位于bin目录下。
  2. go get github.com/golang/protobuf
  3. 编译github.com/golang/protobuf/protoc-gen-go。因protoc需调用protoc-gen-go,故需将protoc-gen-go放在环境变量PATH指定的目录中,或protoc所在的目录。
  4. 定义proto文件。如:

    syntax = "proto2";
    package example;
    
    enum FOO { X = 17; };
    
    message Test {
      required string label = 1;
      optional int32 type = 2 [default=77];
      repeated int64 reps = 3;
    }
  5. 使用protoc生成go代码,生成的文件名为*.pb.go。

    protoc --proto_path=IMPORT_PATH --go_out=DST_DIR *.proto
    • --proto_path:同-I,指定proto文件的目录,缺省则为当前进程目录。
    • --go_out:指定go文件生成目录。
  6. 调用(示例中假设生成的go代码位于path/to/example)。

    package main
    
    import (
        "log"
    
        "github.com/golang/protobuf/proto"
    
        "path/to/example"
    )
    
    func main() {
        test := &example.Test{
            Label: proto.String("hello"),
            Type:  proto.Int32(17),
            Reps:  []int64{1, 2, 3},
        }
        data, err := proto.Marshal(test)
        if err != nil {
            log.Fatal("marshaling error: ", err)
        }
        newTest := &example.Test{}
        err = proto.Unmarshal(data, newTest)
        if err != nil {
            log.Fatal("unmarshaling error: ", err)
        }
        // Now test and newTest contain the same data.
        if test.GetLabel() != newTest.GetLabel() {
            log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
        }
        // etc.
    }

Go使用protobuf

原文:https://www.cnblogs.com/garvenc/p/use_protobuf_in_go.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!