testproto.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package protocol
  2. import (
  3. "fmt"
  4. "mtp2_if/protocol/student"
  5. "mtp2_if/protocol/testmsg"
  6. "github.com/golang/protobuf/proto"
  7. )
  8. // protobuf测试接口
  9. func TestProto() {
  10. s1 := &student.Student{} //第一个学生信息
  11. s1.Name = "jz01"
  12. s1.Age = 23
  13. s1.Address = "cq"
  14. s1.Cn = student.ClassName_class2 //枚举类型赋值
  15. ss := &student.Students{}
  16. ss.Person = append(ss.Person, s1) //将第一个学生信息添加到Students对应的切片中
  17. s2 := &student.Student{} //第二个学生信息
  18. s2.Name = "jz02"
  19. s2.Age = 25
  20. s2.Address = "cd"
  21. s2.Cn = student.ClassName_class3
  22. ss.Person = append(ss.Person, s2) //将第二个学生信息添加到Students对应的切片中
  23. ss.School = "cqu"
  24. fmt.Println("Students信息为:", ss)
  25. // Marshal takes a protocol buffer message
  26. // and encodes it into the wire format, returning the data.
  27. buffer, _ := proto.Marshal(ss)
  28. fmt.Println("序列化之后的信息为:", buffer)
  29. // Use UnmarshalMerge to preserve and append to existing data.
  30. data := &student.Students{}
  31. proto.Unmarshal(buffer, data)
  32. fmt.Println("反序列化之后的信息为:", data)
  33. msg := &testmsg.TestMessage{}
  34. msg.Name = "HU.XINYU"
  35. msg.Age = 40
  36. msg.Address = "123456"
  37. fmt.Println("信息为:", msg)
  38. buffer, _ = proto.Marshal(msg)
  39. fmt.Println("序列化之后的信息为:", buffer)
  40. msg1 := &testmsg.TestMessage{}
  41. proto.Unmarshal(buffer, msg1)
  42. fmt.Println("反序列化之后的信息为:", msg1)
  43. }