aboutsummaryrefslogtreecommitdiff
path: root/examples/list_people.go
diff options
context:
space:
mode:
authorFeng Xiao <xiaofeng@google.com>2015-11-30 13:43:56 -0800
committerFeng Xiao <xiaofeng@google.com>2015-11-30 13:43:56 -0800
commit1a59a715dc5fa584340197aac0811ba3de9850b5 (patch)
tree054a47a347534b6bdb31dcf08b24f7cc07f5669e /examples/list_people.go
parentf4e4be638634b74cbc9be10150bd8bf7a6cb4e8d (diff)
parent7e31c4d930efa3f80d0f03c93e788ba73b847fd8 (diff)
downloadprotobuf-1a59a715dc5fa584340197aac0811ba3de9850b5.tar.gz
protobuf-1a59a715dc5fa584340197aac0811ba3de9850b5.tar.bz2
protobuf-1a59a715dc5fa584340197aac0811ba3de9850b5.zip
Merge pull request #998 from tswast/goexample
Add a Go language example.
Diffstat (limited to 'examples/list_people.go')
-rw-r--r--examples/list_people.go59
1 files changed, 59 insertions, 0 deletions
diff --git a/examples/list_people.go b/examples/list_people.go
new file mode 100644
index 00000000..48b1fbfa
--- /dev/null
+++ b/examples/list_people.go
@@ -0,0 +1,59 @@
+package main
+
+import (
+ "fmt"
+ "io"
+ "io/ioutil"
+ "log"
+ "os"
+
+ "github.com/golang/protobuf/proto"
+ pb "github.com/google/protobuf/examples/tutorial"
+)
+
+func listPeople(w io.Writer, book *pb.AddressBook) {
+ for _, p := range book.People {
+ fmt.Fprintln(w, "Person ID:", p.Id)
+ fmt.Fprintln(w, " Name:", p.Name)
+ if p.Email != "" {
+ fmt.Fprintln(w, " E-mail address:", p.Email)
+ }
+
+ 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 #: ")
+ }
+ fmt.Fprintln(w, pn.Number)
+ }
+ }
+}
+
+// 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]
+
+ // Read the existing address book.
+ in, err := ioutil.ReadFile(fname)
+ if err != nil {
+ if os.IsNotExist(err) {
+ fmt.Printf("%s: File not found. Creating new file.\n", fname)
+ } else {
+ log.Fatalln("Error reading file:", err)
+ }
+ }
+ book := &pb.AddressBook{}
+ if err := proto.Unmarshal(in, book); err != nil {
+ log.Fatalln("Failed to parse address book:", err)
+ }
+
+ listPeople(os.Stdout, book)
+}