1.安装 protoc-gen-go

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

2.下载protoc

https://github.com/google/protobuf/releases

3.编译proto

protoc --proto_path=./proto --go_out=../go/ *.proto

4.使用方式

package main

import (
    "reflect"
    "yqmiot"

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

func main() {
    // 根据具体类型编码
    loginreq := yqmiot.LoginReq{}
    loginreq.Uid = proto.String("wameidemao")
    loginreq.Password = proto.String("woyouyizhixiaomaolv")
    data, _ := proto.Marshal(&loginreq)

    // 根据具体类型解码
    _ = proto.Unmarshal(data, &loginreq)

    // 根据类型名称解码
    messname := "yqmiot.LoginReq"
    messtype := proto.MessageType(messname).Elem() // 获取注册类型
    mess := reflect.New(messtype).Interface().(proto.Message)
    _ = proto.Unmarshal(data, mess)
}

标签: none

添加新评论