2015-11-20 23:32:53 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
"log"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"github.com/golang/protobuf/proto"
|
|
|
|
pb "github.com/google/protobuf/examples/tutorial"
|
|
|
|
)
|
|
|
|
|
2015-12-15 23:56:23 +00:00
|
|
|
func writePerson(w io.Writer, p *pb.Person) {
|
|
|
|
fmt.Fprintln(w, "Person ID:", p.Id)
|
|
|
|
fmt.Fprintln(w, " Name:", p.Name)
|
|
|
|
if p.Email != "" {
|
|
|
|
fmt.Fprintln(w, " E-mail address:", p.Email)
|
|
|
|
}
|
2015-11-20 23:32:53 +00:00
|
|
|
|
2015-12-15 23:56:23 +00:00
|
|
|
for _, pn := range p.Phones {
|
|
|
|
switch pn.Type {
|
|
|
|
case pb.Person_MOBILE:
|
|
|
|
fmt.Fprint(w, " Mobile phone #: ")
|
|
|
|
case pb.Person_HOME:
|
|
|
|
fmt.Fprint(w, " Home phone #: ")
|
|
|
|
case pb.Person_WORK:
|
|
|
|
fmt.Fprint(w, " Work phone #: ")
|
2015-11-20 23:32:53 +00:00
|
|
|
}
|
2015-12-15 23:56:23 +00:00
|
|
|
fmt.Fprintln(w, pn.Number)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func listPeople(w io.Writer, book *pb.AddressBook) {
|
|
|
|
for _, p := range book.People {
|
|
|
|
writePerson(w, p)
|
2015-11-20 23:32:53 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Main reads the entire address book from a file and prints all the
|
|
|
|
// information inside.
|
|
|
|
func main() {
|
|
|
|
if len(os.Args) != 2 {
|
|
|
|
log.Fatalf("Usage: %s ADDRESS_BOOK_FILE\n", os.Args[0])
|
|
|
|
}
|
|
|
|
fname := os.Args[1]
|
|
|
|
|
2015-12-15 23:56:23 +00:00
|
|
|
// [START unmarshal_proto]
|
2015-11-20 23:32:53 +00:00
|
|
|
// Read the existing address book.
|
|
|
|
in, err := ioutil.ReadFile(fname)
|
|
|
|
if err != nil {
|
2015-12-15 23:56:23 +00:00
|
|
|
log.Fatalln("Error reading file:", err)
|
2015-11-20 23:32:53 +00:00
|
|
|
}
|
|
|
|
book := &pb.AddressBook{}
|
|
|
|
if err := proto.Unmarshal(in, book); err != nil {
|
|
|
|
log.Fatalln("Failed to parse address book:", err)
|
|
|
|
}
|
2015-12-15 23:56:23 +00:00
|
|
|
// [END unmarshal_proto]
|
2015-11-20 23:32:53 +00:00
|
|
|
|
|
|
|
listPeople(os.Stdout, book)
|
|
|
|
}
|