list_people.go 1.27 KB
Newer Older
Tim Swast's avatar
Tim Swast committed
1 2 3 4 5 6 7 8 9 10
package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"

	"github.com/golang/protobuf/proto"
Feng Xiao's avatar
Feng Xiao committed
11
	pb "github.com/protocolbuffers/protobuf/examples/tutorial"
Tim Swast's avatar
Tim Swast committed
12 13
)

14 15 16 17 18 19
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)
	}
Tim Swast's avatar
Tim Swast committed
20

21 22 23 24 25 26 27 28
	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 #: ")
Tim Swast's avatar
Tim Swast committed
29
		}
30 31 32 33 34 35 36
		fmt.Fprintln(w, pn.Number)
	}
}

func listPeople(w io.Writer, book *pb.AddressBook) {
	for _, p := range book.People {
		writePerson(w, p)
Tim Swast's avatar
Tim Swast committed
37 38 39 40 41 42 43 44 45 46 47
	}
}

// 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]

48
	// [START unmarshal_proto]
Tim Swast's avatar
Tim Swast committed
49 50 51
	// Read the existing address book.
	in, err := ioutil.ReadFile(fname)
	if err != nil {
52
		log.Fatalln("Error reading file:", err)
Tim Swast's avatar
Tim Swast committed
53 54 55 56 57
	}
	book := &pb.AddressBook{}
	if err := proto.Unmarshal(in, book); err != nil {
		log.Fatalln("Failed to parse address book:", err)
	}
58
	// [END unmarshal_proto]
Tim Swast's avatar
Tim Swast committed
59 60 61

	listPeople(os.Stdout, book)
}