原创

go 安装protobuf

温馨提示:
本文最后更新于 2022年01月17日,已超过 823 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

什么是protobuf?

protocol buffers 是一种语言无关、平台无关、可扩展的序列化结构数据的方法,它可用于(数据)通信协议、数据存储等。

Protocol Buffers 是一种灵活,高效,自动化机制的结构数据序列化方法-可类比 XML,但是比 XML 更小(3 ~ 10倍)、更快(20 ~ 100倍)、更为简单。

你可以定义数据的结构,然后使用特殊生成的源代码轻松的在各种数据流中使用各种语言进行编写和读取结构数据。你甚至可以更新数据结构,而不破坏由旧数据结构编译的已部署程序。

简单来说就是:你可以通过protobuf,将不同语言的数据结构进行直接序列化传输,由其他语言接收

安装protobuf

下载地址:https://github.com/protocolbuffers/protobuf/releases

编译安装时需要c,c++编译器

yum install gcc -y
yum install gcc-c++ -y
yum install make -y
wget 
tar -zvxf protobuf-all-3.19.3.tar.gz
cd protobuf-3.19.3
./configure
make
make install
protoc --version

即可看到安装完成

安装 go-protobuf

安装插件 protoc-gen-go,它是一个go程序,编译它之后将可执行文件执行路径写入环境变量

go get github.com/golang/protobuf/protoc-gen-go

获取go的protobuf包

go get github.com/golang/protobuf/proto

输入命令 protoc-gen-go,如果没报错表示安装成功

使用

编写一个proto文件./test/user.proto:

syntax = "proto3";
package test;
option go_package ="./test";
message User{
   string userName = 1;
   int64  userId = 2 ;
   string address = 3;
   string password = 4;
}

在根目录执行命令:

protoc --go_out=. ./test/*.proto

将生成文件:

仙士可博客

main引用并使用:

package main

import (
   "encoding/json"
   "fmt"
   "google.golang.org/protobuf/proto"
   "log"
   "testProject/test"
)

func main() {
   user := test.User{}
   user.Address = "sadsda"
   user.Password = "123456"
   user.UserName = "仙士可"
   bytes, _ := json.Marshal(user)
   fmt.Println(string(bytes))
   //序列化user结构体数据
   out, err := proto.Marshal(&user)
   if err != nil {
      log.Fatalln("Failed to encode address book:", err)
   }

   //反序列化user结构体
   user2:=test.User{}
   err = proto.Unmarshal(out, &user2)
   if err!=nil {
      log.Fatalln("Failed to parse address User:", err)
   }
   bytes, _ = json.Marshal(user2)
   fmt.Println(string(bytes))
}
正文到此结束
本文目录