list_people.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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/google/protobuf/examples/tutorial"
  10. )
  11. func listPeople(w io.Writer, book *pb.AddressBook) {
  12. for _, p := range book.People {
  13. fmt.Fprintln(w, "Person ID:", p.Id)
  14. fmt.Fprintln(w, " Name:", p.Name)
  15. if p.Email != "" {
  16. fmt.Fprintln(w, " E-mail address:", p.Email)
  17. }
  18. for _, pn := range p.Phones {
  19. switch pn.Type {
  20. case pb.Person_MOBILE:
  21. fmt.Fprint(w, " Mobile phone #: ")
  22. case pb.Person_HOME:
  23. fmt.Fprint(w, " Home phone #: ")
  24. case pb.Person_WORK:
  25. fmt.Fprint(w, " Work phone #: ")
  26. }
  27. fmt.Fprintln(w, pn.Number)
  28. }
  29. }
  30. }
  31. // Main reads the entire address book from a file and prints all the
  32. // information inside.
  33. func main() {
  34. if len(os.Args) != 2 {
  35. log.Fatalf("Usage: %s ADDRESS_BOOK_FILE\n", os.Args[0])
  36. }
  37. fname := os.Args[1]
  38. // Read the existing address book.
  39. in, err := ioutil.ReadFile(fname)
  40. if err != nil {
  41. if os.IsNotExist(err) {
  42. fmt.Printf("%s: File not found. Creating new file.\n", fname)
  43. } else {
  44. log.Fatalln("Error reading file:", err)
  45. }
  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. listPeople(os.Stdout, book)
  52. }