1. 下载 protobuf 插件:
    https://github.com/protocolbuffers/protobuf/releases

  2. 安装 protoc-gen-go 插件:

    go get github.com/golang/protobuf/protoc-gen-go@v1.1.0
    go install github.com/golang/protobuf/protoc-gen-go@v1.1.0
  3. 目录结构:

    |—— protobuf/           // 根目录
    ****|—— hello/
    ********|—— hello.proto // proto 描述文件
    ********|—— hello.pb.go // proto 编译后文件
    ****|—— go.mod
    ****|—— main.go         // 入口文件
  4. 初始化 go module:

    cd protobuf
    go mod init protobuf
  5. 编写 protobuf/hello/hello.proto 文件:

     syntax = "proto3";
     package hello;
     option go_package = ".;hello";
     message Hello {
         string name = 1;
     }
  6. 编译生成 .pb.go 文件:

    cd protobuf/hello
    protoc -I . --go_out=plugins=grpc:. ./hello.proto
  7. 编写 protobuf/main.go:

     package main
    
     import (
         "fmt"
         "github.com/golang/protobuf/proto"
         "protobuf/hello"
     )
    
     func main() {
         data := &hello.Hello{
             Name: "lee",
         }
         // 序列化
         encoded, _ := proto.Marshal(data)
         fmt.Println("encoded:", encoded)
         // 反序列化
         decoded := &hello.Hello{}
         _ = proto.Unmarshal(encoded, decoded)
         fmt.Println("decoded:", decoded)
     }
文档更新时间: 2024-04-20 10:57   作者:lee