package main
import (
"fmt"
"github.com/gogo/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
"io/ioutil"
"log"
"test/src/first"
)
func main() {
person := newPersonMessage()
//fmt.Println(person.GetUsername())
//_ = writeToFile("person.bin", person)
//pm := first.PersonMessage{}
//
//_ = readFromFile("person.bin",&pm)
fmt.Println(&person)
jsonstr := toJson(person)
fmt.Println(jsonstr)
pm3 := first.PersonMessage{}
_ = fromJson(jsonstr,&pm3)
fmt.Println(&pm3)
}
func toJson(pm proto.Message) string {
marshaler := jsonpb.Marshaler{Indent: " "}
str,err := marshaler.MarshalToString(pm)
if err != nil{
log.Fatalln("转换失败")
}
return str
}
func fromJson(in string,pb proto.Message) error {
err := jsonpb.UnmarshalString(in,pb); if err!=nil{
log.Fatalln("失败")
}
return nil
}
func readFromFile(filename string,pb proto.Message) error {
dateBytes,err := ioutil.ReadFile("./person.bin"); if err!=nil{
log.Fatalln("读取失败")
}
err =proto.Unmarshal(dateBytes,pb)
if err!=nil{
log.Fatalln("序列化失败")
}
return nil
}
func writeToFile(filename string,pb proto.Message) error {
data,error := proto.Marshal(pb)
if error !=nil{
log.Fatalln("无法序列化到bytes")
}
if err := ioutil.WriteFile(filename,data,0644); err !=nil{
log.Fatalln("无法写入到文件")
}
log.Println("写入成功")
return nil
}
func newPersonMessage() * first.PersonMessage {
p := first.PersonMessage{
Id: 1,
Username: "hello",
}
return &p
}