blob: 70bc589efc5cebd1d5dbc5b53f0e14e551b81725 [file] [log] [blame]
Tim Swast7e31c4d2015-11-20 15:32:53 -08001package main
2
3import (
4 "fmt"
5 "io"
6 "io/ioutil"
7 "log"
8 "os"
9
10 "github.com/golang/protobuf/proto"
11 pb "github.com/google/protobuf/examples/tutorial"
12)
13
Tim Swast1cc541b2015-12-15 15:56:23 -080014func 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
Tim Swast7e31c4d2015-11-20 15:32:53 -080034func listPeople(w io.Writer, book *pb.AddressBook) {
35 for _, p := range book.People {
Tim Swast1cc541b2015-12-15 15:56:23 -080036 writePerson(w, p)
Tim Swast7e31c4d2015-11-20 15:32:53 -080037 }
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
Tim Swast1cc541b2015-12-15 15:56:23 -080048 // [START unmarshal_proto]
Tim Swast7e31c4d2015-11-20 15:32:53 -080049 // Read the existing address book.
50 in, err := ioutil.ReadFile(fname)
51 if err != nil {
Tim Swast1cc541b2015-12-15 15:56:23 -080052 log.Fatalln("Error reading file:", err)
Tim Swast7e31c4d2015-11-20 15:32:53 -080053 }
54 book := &pb.AddressBook{}
55 if err := proto.Unmarshal(in, book); err != nil {
56 log.Fatalln("Failed to parse address book:", err)
57 }
Tim Swast1cc541b2015-12-15 15:56:23 -080058 // [END unmarshal_proto]
Tim Swast7e31c4d2015-11-20 15:32:53 -080059
60 listPeople(os.Stdout, book)
61}