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