• Go 使用 protobuf


    一.环境准备

    安装 protoc ,protoc 是用来执行根据 proto 文件生成 代码的工具。

    访问 https://github.com/protocolbuffers/protobuf/releases 选择对应的系统进行下载。

    image-20220310173032102

    为了方便使用,建议将 protoc 加到 PATH 中,mac 可以放到 /usr/local/bin/ 下。

    安装 proto-gen go , 执行命令

    go install github.com/golang/protobuf/protoc-gen-go@lates
    

    安装完成后检查是否安装成功

    ls $GOPATH/bin|grep protoc-gen-go
    

    二.编写代码

    编写 proto 文件

    syntax = "proto3";
    option go_package = "/pb";
    
    message Person {
        string name = 1;
    }
    

    生成 pb.go

    protoc --go_out=. *.proto
    

    生成 grpc 使用命令:protoc --go_out=plugins=grpc:. *.proto

    安装依赖

    go get github.com/golang/protobuf
    

    序列化和反序列化 main.go

    package main
    
    import (
    	"fmt"
    	"github.com/golang/protobuf/proto"
    	"go-protobuf/pb"
    	"log"
    )
    
    func main() {
    	p := &pb.Person{
    		Name: "lzq",
    	}
    
    	data, err := proto.Marshal(p)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	fmt.Printf("matshal data len: %d\n", len(data))
    
    	np := &pb.Person{}
    	if err = proto.Unmarshal(data, np); err != nil {
    		log.Fatal(err)
    	}
    
    	fmt.Printf("unmatshal person name: %s\n", np.Name)
    
    }
    
    

    输出

    image-20220310175454721

  • 相关阅读:
    Linux命令——find
    Linux命令——locate
    python模块:datetime
    python模块:json
    python模块:shelve
    python模块:shutil
    python模块:sys
    python:OS模块
    str.index()与str.find()比较
    python模块:re
  • 原文地址:https://www.cnblogs.com/stulzq/p/15990647.html
Copyright © 2020-2023  润新知