go 使用protobuf 示例
示例文件main.proto
syntax = "proto3";
package main;
message Test {
string comment = 1;
}
message Example {
string name = 1;
int32 age = 2;
repeated Test t = 3;
message Label {
string source = 1;
}
repeated Label labels = 4;
}
程序代码:
package main
import (
"fmt"
"io/ioutil"
"os"
"github.com/golang/protobuf/proto"
)
func main() {
// Open and read the contents of the file
fp, _ := os.Open("main.txt")
defer fp.Close()
data, _ := ioutil.ReadAll(fp)
// convert the file from type []byte to a string
text := string(data)
// initialize the example struct
ex := Example{}
// Unmarshal the text into the struct
_ = proto.UnmarshalText(text, &ex)
fmt.Println(ex)
// Create an output file
fp2, _ := os.Create("gen_main.txt")
defer fp2.Close()
// Write the same data back to another file
_ = proto.MarshalText(fp2, &ex)
}
运行
go run .
{Larry 99 [comment:”hello” comment:”world” ] [source:”foo” source:”bar” ] {} [] 0}
本文链接地址:https://const.net.cn/366.html