witProtobuf/example-cmd/main.go

90 lines
1.7 KiB
Go

package main
import (
"bytes"
"os"
"bufio"
"io/ioutil"
"go.wit.com/log"
"github.com/golang/protobuf/proto"
pb "go.wit.com/lib/protobuf/witProtobuf"
)
//
// writes out several files in /tmp/
//
func main() {
TestWriteEvent()
in, err := ioutil.ReadFile("/tmp/testing4.protobuf")
if err != nil {
log.Fatalln("Error reading file:", err)
}
allEvents := &pb.Event{}
if err := proto.Unmarshal(in, allEvents); err != nil {
log.Error(err, "Failed to parse events:")
}
log.SetAll(true)
log.Spew("Spew:", allEvents)
log.Spew("Spew:", allEvents.Type)
/*
for i, e := range allEvents {
log.Warn(i, e)
}
*/
// listPeople(os.Stdout, allEvents)
// got := in.String()
log.Println(in)
}
func marshalWriteToFile(myWriter *bufio.Writer, e *pb.Event) {
buf, err := proto.Marshal(e)
if err != nil {
log.Fatal("marshaling error: ", err)
}
tmp, err := myWriter.Write(buf)
myWriter.Flush()
log.Println("bufio.Write() tmp, err = ", tmp, err)
buf, err = proto.Marshal(e)
tmp2, err := myWriter.Write(buf)
myWriter.Flush()
log.Println("bufio.Write() tmp2, err = ", tmp2, err)
}
func TestWriteEvent() {
buf := new(bytes.Buffer)
e := pb.CreateSampleEvent()
got := buf.String()
log.Println(got)
newfile, _ := os.Create("/tmp/testing4.protobuf")
myWriter := bufio.NewWriter(newfile)
marshalWriteToFile(myWriter, e)
marshalUnmarshal()
}
func marshalUnmarshal() {
test := pb.CreateSampleEvent()
data, err := proto.Marshal(test)
if err != nil {
log.Fatal("marshaling error: ", err)
}
newTest := &pb.Event{}
err = proto.Unmarshal(data, newTest)
if err != nil {
log.Fatal("unmarshaling error: ", err)
} else {
log.Println("proto.Marshal() and proto.Unmarshal() worked")
}
}