golang protobuf
1.安装protoc
- 安装完后把bin下放入环境变量中
- https://github.com/protocolbuffers/protobuf/releases
- protoc —version (查看当前版本)
2.安装protoc-gen-go
- go get -u github.com/golang/protobuf/protoc-gen-go (cmd输入)
- $GOPATH/bin (会自动存入这个目录,把这个目录也加入环境变量)
3.创建proto文件
package goprotobuf;
message HelloWorld
{
required int32 id = 1; // ID
required string str = 2; // str
optional int32 opt = 3; //optional field
}
同级目录下 cmd ,protoc —go_out=. *.proto (或者protoc —go_out=. test.proto)
会生成go文件
4.开始编解码
package main
import (
"fmt"
proto "github.com/golang/protobuf/proto"
goprotobuf "hou/src/study/pb"
)
func main() {
msg := &goprotobuf.HelloWorld{
Id: proto.Int32(996),
Str: proto.String("fuck"),
}
//编码
buffer, err := proto.Marshal(msg)
if err != nil {
return
}
//解码
msgEnd := &goprotobuf.HelloWorld{}
err = proto.Unmarshal(buffer, msgEnd)
if err != nil {
return
}
fmt.Println("解码", msgEnd)
}
还没有评论,来说两句吧...