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