天天看點

Protobuf(二)[環境搭建-Golang]1.Ubuntu1804LTS2.CentOS-73.測試

Protobuf-環境搭建-Golang

  • 1.Ubuntu1804LTS
    • 1.Golang環境搭建
      • 1.安裝工具
      • 2.下載下傳golang包
      • 3.解壓到/usr/local/
      • 4.建立工作目錄
      • 5.設定環境變量
      • 6.測試
    • 2.golang-protobuf
      • 1.下載下傳
      • 2.查找protoc-gen-go
      • 3.操作生效
        • 1.拷貝到/bin/目錄
        • 2.添加環境變量
      • 4.測試
  • 2.CentOS-7
      • 1.安裝工具
      • 2.下載下傳golang包
      • 3.解壓到/usr/local/
      • 4.建立工作目錄
      • 5.設定環境變量
      • 6.測試
    • 2.golang-protobuf
      • 1.下載下傳
      • 2.查找protoc-gen-go
      • 3.操作生效
        • 1.拷貝到/bin/目錄
        • 2.添加環境變量
      • 4.測試
  • 3.測試
    • 1.建立工程
    • 2.go mod 初始化
    • 3.建立protobuf檔案目錄
    • 4.建立.proto檔案
    • 5.編譯成go檔案
    • 6.使用protobuf協定程式設計
    • 7.測試

1.Ubuntu1804LTS

1.Golang環境搭建

1.安裝工具

sudo apt install -y wget curl tar unzip tree
           

2.下載下傳golang包

wget https://dl.google.com/go/go1.14.2.linux-amd64.tar.gz && ls | grep go
           
Protobuf(二)[環境搭建-Golang]1.Ubuntu1804LTS2.CentOS-73.測試

3.解壓到/usr/local/

sudo tar -zxvf go1.14.2.linux-amd64.tar.gz -C /usr/local
ls /usr/local/ | grep go
           
Protobuf(二)[環境搭建-Golang]1.Ubuntu1804LTS2.CentOS-73.測試

4.建立工作目錄

mkdir -p ~/workspace/go/bin ~/workspace/go/src ~/workspace/go/pkg ~/workspace/go/src && tree ~/workspace/go/
           
Protobuf(二)[環境搭建-Golang]1.Ubuntu1804LTS2.CentOS-73.測試

5.設定環境變量

tee -a 是追加
sudo tee -a /etc/profile <<-'EOF'
export GOROOT=/usr/local/go
export GOPATH=~/workspace/go
export GOBIN=~/workspace/go/bin
export GO111MODULE="on"
export GOPROXY=https://goproxy.io
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin:$GOBIN:$GOPROXY
EOF
source /etc/profile

           
Protobuf(二)[環境搭建-Golang]1.Ubuntu1804LTS2.CentOS-73.測試

6.測試

go version
go env
           
Protobuf(二)[環境搭建-Golang]1.Ubuntu1804LTS2.CentOS-73.測試

2.golang-protobuf

1.下載下傳

go get -u -v github.com/golang/protobuf/...
           
Protobuf(二)[環境搭建-Golang]1.Ubuntu1804LTS2.CentOS-73.測試

2.查找protoc-gen-go

cd $GOPATH/bin && ls -la | grep protoc-gen-go
           
Protobuf(二)[環境搭建-Golang]1.Ubuntu1804LTS2.CentOS-73.測試

3.操作生效

拷貝protoc-gen-go到/bin/目錄下,或者添加$GOPATH/bin到環境變量

1.拷貝到/bin/目錄

cp $GOPATH/bin/protoc-gen-go /bin/
           

2.添加環境變量

sudo tee -a /etc/protofile <<-'EOF'
export PATH=$PATH:$GOPATH/bin
EOF
source /etc/profile
           

4.測試

終端輸入protoc-,然後按下Tab鍵檢視是否補全,補全即OK!

protoc-
           
Protobuf(二)[環境搭建-Golang]1.Ubuntu1804LTS2.CentOS-73.測試

2.CentOS-7

1.安裝工具

sudo yum install -y wget curl tar unzip tree
           

2.下載下傳golang包

wget https://dl.google.com/go/go1.14.2.linux-amd64.tar.gz && ls | grep go
           
Protobuf(二)[環境搭建-Golang]1.Ubuntu1804LTS2.CentOS-73.測試

3.解壓到/usr/local/

sudo tar -zxvf go1.14.2.linux-amd64.tar.gz -C /usr/local
ls /usr/local/ | grep go
           
Protobuf(二)[環境搭建-Golang]1.Ubuntu1804LTS2.CentOS-73.測試

4.建立工作目錄

mkdir -p ~/workspace/go/bin ~/workspace/go/src ~/workspace/go/pkg ~/workspace/go/src && tree ~/workspace/go/
           
Protobuf(二)[環境搭建-Golang]1.Ubuntu1804LTS2.CentOS-73.測試

5.設定環境變量

tee -a 是追加
sudo tee -a /etc/profile <<-'EOF'
export GOROOT=/usr/local/go
export GOPATH=~/workspace/go
export GOBIN=~/workspace/go/bin
export GO111MODULE="on"
export GOPROXY=https://goproxy.io
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin:$GOBIN:$GOPROXY
EOF
source /etc/profile

           
Protobuf(二)[環境搭建-Golang]1.Ubuntu1804LTS2.CentOS-73.測試

6.測試

go version
go env
           
Protobuf(二)[環境搭建-Golang]1.Ubuntu1804LTS2.CentOS-73.測試

2.golang-protobuf

1.下載下傳

go get -u -v github.com/golang/protobuf/...
           
Protobuf(二)[環境搭建-Golang]1.Ubuntu1804LTS2.CentOS-73.測試

下載下傳的時候後一定要跟【…】,否則下載下傳後無法在$GOPATH/bin/目錄下找到protoc-gen-go

2.查找protoc-gen-go

cd $GOPATH/bin && ls -la | grep protoc-gen-go
           
Protobuf(二)[環境搭建-Golang]1.Ubuntu1804LTS2.CentOS-73.測試

3.操作生效

拷貝protoc-gen-go到/bin/目錄下,或者添加$GOPATH/bin到環境變量

1.拷貝到/bin/目錄

cp $GOPATH/bin/protoc-gen-go /bin/
           

2.添加環境變量

sudo tee -a /etc/protofile <<-'EOF'
export PATH=$PATH:$GOPATH/bin
EOF
source /etc/profile
           

4.測試

終端輸入protoc-,然後按下Tab鍵檢視是否補全,補全即OK!

protoc-
           
Protobuf(二)[環境搭建-Golang]1.Ubuntu1804LTS2.CentOS-73.測試

3.測試

1.建立工程

Protobuf(二)[環境搭建-Golang]1.Ubuntu1804LTS2.CentOS-73.測試

2.go mod 初始化

go mod init goprotobuf
           
Protobuf(二)[環境搭建-Golang]1.Ubuntu1804LTS2.CentOS-73.測試

3.建立protobuf檔案目錄

Protobuf(二)[環境搭建-Golang]1.Ubuntu1804LTS2.CentOS-73.測試

4.建立.proto檔案

vim Student.proto
           

内容如下:

syntax = "proto3"; //指定版本資訊,不指定會報錯

package pb;

// message為關鍵字,作用為定義一種消息類型
message Student{
    string name = 1;// 序号1
    int32 age = 2; // 序号2
}
           
Protobuf(二)[環境搭建-Golang]1.Ubuntu1804LTS2.CentOS-73.測試

5.編譯成go檔案

1.标準格式

protoc --proto_path=IMPORT_PATH --go_out=DST_DIR path/to/file.proto
           

2.通用格式

cd $GOPATH/src/goprotobuf/pb/
           

将目前目錄下【$GOPATH/src/goprotobuf/pb/】的所有的.proto檔案編譯成go檔案,放在目前目錄下【$GOPATH/src/goprotobuf/pb/】

protoc --go_out=./ *.proto
           

編譯完成後目錄:

Protobuf(二)[環境搭建-Golang]1.Ubuntu1804LTS2.CentOS-73.測試

編譯完成後的Student.pb.go檔案

// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// 	protoc-gen-go v1.21.0
// 	protoc        v3.11.4
// source: Student.proto

package pb

import (
	proto "github.com/golang/protobuf/proto"
	protoreflect "google.golang.org/protobuf/reflect/protoreflect"
	protoimpl "google.golang.org/protobuf/runtime/protoimpl"
	reflect "reflect"
	sync "sync"
)

const (
	// Verify that this generated code is sufficiently up-to-date.
	_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
	// Verify that runtime/protoimpl is sufficiently up-to-date.
	_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)

// This is a compile-time assertion that a sufficiently up-to-date version
// of the legacy proto package is being used.
const _ = proto.ProtoPackageIsVersion4

// message為關鍵字,作用為定義一種消息類型
type Student struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

	Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // 序号1
	Age  int32  `protobuf:"varint,2,opt,name=age,proto3" json:"age,omitempty"`  // 序号2
}

func (x *Student) Reset() {
	*x = Student{}
	if protoimpl.UnsafeEnabled {
		mi := &file_Student_proto_msgTypes[0]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}

func (x *Student) String() string {
	return protoimpl.X.MessageStringOf(x)
}

func (*Student) ProtoMessage() {}

func (x *Student) ProtoReflect() protoreflect.Message {
	mi := &file_Student_proto_msgTypes[0]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}

// Deprecated: Use Student.ProtoReflect.Descriptor instead.
func (*Student) Descriptor() ([]byte, []int) {
	return file_Student_proto_rawDescGZIP(), []int{0}
}

func (x *Student) GetName() string {
	if x != nil {
		return x.Name
	}
	return ""
}

func (x *Student) GetAge() int32 {
	if x != nil {
		return x.Age
	}
	return 0
}

var File_Student_proto protoreflect.FileDescriptor

var file_Student_proto_rawDesc = []byte{
	0x0a, 0x0d, 0x53, 0x74, 0x75, 0x64, 0x65, 0x6e, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12,
	0x02, 0x70, 0x62, 0x22, 0x2f, 0x0a, 0x07, 0x53, 0x74, 0x75, 0x64, 0x65, 0x6e, 0x74, 0x12, 0x12,
	0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61,
	0x6d, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52,
	0x03, 0x61, 0x67, 0x65, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}

var (
	file_Student_proto_rawDescOnce sync.Once
	file_Student_proto_rawDescData = file_Student_proto_rawDesc
)

func file_Student_proto_rawDescGZIP() []byte {
	file_Student_proto_rawDescOnce.Do(func() {
		file_Student_proto_rawDescData = protoimpl.X.CompressGZIP(file_Student_proto_rawDescData)
	})
	return file_Student_proto_rawDescData
}

var file_Student_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_Student_proto_goTypes = []interface{}{
	(*Student)(nil), // 0: pb.Student
}
var file_Student_proto_depIdxs = []int32{
	0, // [0:0] is the sub-list for method output_type
	0, // [0:0] is the sub-list for method input_type
	0, // [0:0] is the sub-list for extension type_name
	0, // [0:0] is the sub-list for extension extendee
	0, // [0:0] is the sub-list for field type_name
}

func init() { file_Student_proto_init() }
func file_Student_proto_init() {
	if File_Student_proto != nil {
		return
	}
	if !protoimpl.UnsafeEnabled {
		file_Student_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
			switch v := v.(*Student); i {
			case 0:
				return &v.state
			case 1:
				return &v.sizeCache
			case 2:
				return &v.unknownFields
			default:
				return nil
			}
		}
	}
	type x struct{}
	out := protoimpl.TypeBuilder{
		File: protoimpl.DescBuilder{
			GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
			RawDescriptor: file_Student_proto_rawDesc,
			NumEnums:      0,
			NumMessages:   1,
			NumExtensions: 0,
			NumServices:   0,
		},
		GoTypes:           file_Student_proto_goTypes,
		DependencyIndexes: file_Student_proto_depIdxs,
		MessageInfos:      file_Student_proto_msgTypes,
	}.Build()
	File_Student_proto = out.File
	file_Student_proto_rawDesc = nil
	file_Student_proto_goTypes = nil
	file_Student_proto_depIdxs = nil
}
           

生成的【.pb.go】檔案不允許編輯,如需要修改某些字段或者資訊,則需要修改【.proto】檔案然後重新編譯生成即可。

6.使用protobuf協定程式設計

1.在工程項目目錄下建立main.go檔案

cd $GOPATH/src/ && touch main.go
           

2.編輯main.go

vim main.go
           

内容如下

package main

import (
	"fmt"
	"goprotobuf/pb"
	"log"

	"github.com/golang/protobuf/proto"
)

func main() {
	// 1.定義一個go的protobuf結構體
	student := &pb.Student{
		Name: "Lisa",
		Age:  18,
	}

	// 2.編碼的序列化--生成二進制
	data, err := proto.Marshal(student)
	if err != nil {
		log.Fatal(err)
	}
	// 3.二進制傳輸

	// 4.對端進行解碼
	stu := &pb.Student{}
	err = proto.Unmarshal(data, stu)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(stu)
}
           

7.測試

cd $GOPATH/src/goprotobuf/
           
Protobuf(二)[環境搭建-Golang]1.Ubuntu1804LTS2.CentOS-73.測試