list_people.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "io/ioutil"
  6. "log"
  7. "os"
  8. "github.com/golang/protobuf/proto"
  9. pb "github.com/protocolbuffers/protobuf/examples/tutorial"
  10. )
  11. func writePerson(w io.Writer, p *pb.Person) {
  12. fmt.Fprintln(w, "Person ID:", p.Id)
  13. fmt.Fprintln(w, " Name:", p.Name)
  14. if p.Email != "" {
  15. fmt.Fprintln(w, " E-mail address:", p.Email)
  16. }
  17. for _, pn := range p.Phones {
  18. switch pn.Type {
  19. case pb.Person_MOBILE:
  20. fmt.Fprint(w, " Mobile phone #: ")
  21. case pb.Person_HOME:
  22. fmt.Fprint(w, " Home phone #: ")
  23. case pb.Person_WORK:
  24. fmt.Fprint(w, " Work phone #: ")
  25. }
  26. fmt.Fprintln(w, pn.Number)
  27. }
  28. }
  29. func listPeople(w io.Writer, book *pb.AddressBook) {
  30. for _, p := range book.People {
  31. writePerson(w, p)
  32. }
  33. }
  34. // Main reads the entire address book from a file and prints all the
  35. // information inside.
  36. func main() {
  37. if len(os.Args) != 2 {
  38. log.Fatalf("Usage: %s ADDRESS_BOOK_FILE\n", os.Args[0])
  39. }
  40. fname := os.Args[1]
  41. // [START unmarshal_proto]
  42. // Read the existing address book.
  43. in, err := ioutil.ReadFile(fname)
  44. if err != nil {
  45. log.Fatalln("Error reading file:", err)
  46. }
  47. book := &pb.AddressBook{}
  48. if err := proto.Unmarshal(in, book); err != nil {
  49. log.Fatalln("Failed to parse address book:", err)
  50. }
  51. // [END unmarshal_proto]
  52. listPeople(os.Stdout, book)
  53. }