aboutsummaryrefslogtreecommitdiffhomepage
path: root/examples/list_people.go
diff options
context:
space:
mode:
authorGravatar Tim Swast <swast@google.com>2015-12-15 15:56:23 -0800
committerGravatar Tim Swast <swast@google.com>2015-12-15 15:56:23 -0800
commit1cc541b3be263d92aba435b183aca5ad7151ae8a (patch)
treea6e62dd8b8811529f555c436a206410eb49544ac /examples/list_people.go
parent1a59a715dc5fa584340197aac0811ba3de9850b5 (diff)
Add region tags to the Go protobuf examples.
This will allow us to like to specific snippets of code in the documentation. I plan to create a tutorial similar to the C# tutorial https://developers.google.com/protocol-buffers/docs/csharptutorial Since that tutorial has sections for populating a proto, parsing, and serializing, I made a region for each of these for Go. To make the populating sample more self-contained, I refactor the listing example slightly.
Diffstat (limited to 'examples/list_people.go')
-rw-r--r--examples/list_people.go46
1 files changed, 24 insertions, 22 deletions
diff --git a/examples/list_people.go b/examples/list_people.go
index 48b1fbfa..70bc589e 100644
--- a/examples/list_people.go
+++ b/examples/list_people.go
@@ -11,25 +11,29 @@ import (
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)
- }
+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)
+ }
- 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)
+ 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)
+ }
+}
+
+func listPeople(w io.Writer, book *pb.AddressBook) {
+ for _, p := range book.People {
+ writePerson(w, p)
}
}
@@ -41,19 +45,17 @@ func main() {
}
fname := os.Args[1]
+ // [START unmarshal_proto]
// 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)
- }
+ 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)
}
+ // [END unmarshal_proto]
listPeople(os.Stdout, book)
}