简单例子跑通

https://github.com/google/protobuf/blob/master/src/README.md
https://studygolang.com/articles/7394

$ git clone https://github.com/google/protobuf.git
$ cd protobuf
$ git submodule update --init --recursive
$ ./autogen.sh

$ ./configure
$ make
$ make check
$ sudo make install
$ sudo ldconfig # refresh shared library cache.
go get github.com/golang/protobuf
go get github.com/golang/protobuf/protoc-gen-go
cat test.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;
optional group OptionalGroup = 4 {
required string RequiredField = 5;
}
}
protoc --go_out=. test.proto
#产生的文件放到$GOPATH中便于引用,这里扔到my.protobuf.test/example
cat test.go
package main

import (
    "fmt"
    "log"
    // 辅助库
    "github.com/golang/protobuf/proto"

    // test.pb.go 的路径
    "my.protobuf.test/example"
)

func main() {
    // 创建一个消息 Test
    test := &example.Test{
        // 使用辅助函数设置域的值
        Label: proto.String("hello"),
        Type:  proto.Int32(17),
        Optionalgroup: &example.Test_OptionalGroup{
            RequiredField: proto.String("good bye"),
        },
    }

    fmt.Printf("Label:%s Type:%d\n", test.GetLabel(), test.GetType())

    *(test.Label) = "hello go"
    *(test.Type) = 18

    // 进行编码
    data, err := proto.Marshal(test)
    if err != nil {
        log.Fatal("marshaling error: ", err)
    }

    fmt.Printf("Binary Len:%d\n", len(data))

    // 进行解码
    newTest := &example.Test{}
    err = proto.Unmarshal(data, newTest)
    if err != nil {
        log.Fatal("unmarshaling error: ", err)
    }

    fmt.Printf("Label:%s Type:%d\n", test.GetLabel(), test.GetType())

    // 测试结果
    if test.GetLabel() != newTest.GetLabel() {
        log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
    }
}

你可能感兴趣的:(简单例子跑通)