关于protocolbuf的使用

--------关于protocol_buffers的使用

1.https://github.com/protocolbuffers/protobuf下载好文件,然后再系统环境里配置环境,在path下配置到 protocolbuffers下的bin目录*

2.本地cmd命令下protoc.exe,如果显示出东西配置完成

3.安装插件go install google.golang.org/protobuf/cmd/protoc-gen-go@latest

4.创建一个protobuf文件

  syntax = "proto3";
    option go_package="./;hello";
    package hello;
    message Person{
     string name = 1;
     int32 age = 2;
     string email = 3;
     }

5.生成go文件protoc --go_out=./go ./proto/*

6.可以为其添加枚举类,但必须从 0开始

7. option allow_alias = true; 通过将相同的值分配给不同的枚举常量来定义别名

8.例子:

syntax = "proto3";
option go_package = "./;user";
package user;
message Article1{
  int32 aid = 1;
  string title = 2;
  int32 views = 3;
};

main方法调用

 atrticles :=&user.Article1{
		Aid: 1,
		Title: "protobuffer for golang",
		Views: 100,
	}
	//序列化成二进制数据
	bytes, _ := proto.Marshal(atrticles)
	fmt.Printf("bytes: %v\n", bytes)
    //反序列化
	otherArticle := &user.Article1{}
	proto.Unmarshal(bytes, otherArticle)
	fmt.Printf("otherArticle.GetAid(): %v\n", otherArticle.GetAid())
 // Message to json  josn转换
	jsonString := protojson.Format(article.ProtoReflect().Interface())
	fmt.Printf("jsonString: %v\n", jsonString)

	// jsong to message
	m := article.ProtoReflect().Interface()
	protojson.Unmarshal([]byte(jsonString), m)

	fmt.Printf("m: %v\n", m)

*/


版权声明:本文为qq_43394544原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。