user.proto
syntax = "proto3";
package demo;
option go_package = "./pb"; //指定go_out对应的目录
message UserInfo{
int32 UserType = 1;
string UserName = 2;
string UserInfo = 3;
}
// 执行命令
>>> protoc --go_out=. user.proto
会在当前pb目录下生成user.pb.go文件
如何使用
// main.go
package main
import (
"demo/pb"
"fmt"
"google.golang.org/protobuf/proto"
)
func main() {
// 初始化message UserInfo
usermsg := &pb.UserInfo{
UserType: 1,
UserName: "jim",
UserInfo: "i am a worker!",
}
//序列化
userdata, err := proto.Marshal(usermsg)
if err != nil {
fmt.Println("Marshaling err:", err)
}
//反序列化
encodingmsg := &pb.UserInfo{}
err = proto.Unmarshal(userdata, encodingmsg)
if err != nil {
fmt.Println("Unmarshaling err:", err)
}
// 一些生成的相关方法
fmt.Printf("GetUserType:%d\n", encodingmsg.GetUserType())
fmt.Printf("GetUserInfo:%s\n", encodingmsg.GetUserInfo())
fmt.Printf("GetUserName:%s\n", encodingmsg.GetUserName())
/*
GetUserType:1
GetUserInfo:i am a worker!
GetUserName:jim
*/
}