forked from ligato/cn-infra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
view.go
89 lines (74 loc) 路 1.92 KB
/
view.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//go:generate protoc --proto_path=../model/phonebook --gogo_out=../model/phonebook ../model/phonebook/phonebook.proto
// Package view contains an example that shows how to read data from etcd.
package main
import (
"fmt"
"os"
"github.com/ligato/cn-infra/config"
"github.com/ligato/cn-infra/db/keyval/etcd"
"github.com/ligato/cn-infra/db/keyval/kvproto"
"github.com/ligato/cn-infra/examples/etcd-lib/model/phonebook"
"github.com/ligato/cn-infra/logging/logrus"
)
// processArgs processes input arguments.
func processArgs() (*etcd.ClientConfig, error) {
fileConfig := &etcd.Config{}
if len(os.Args) > 2 {
if os.Args[1] == "--cfg" {
err := config.ParseConfigFromYamlFile(os.Args[2], fileConfig)
if err != nil {
return nil, err
}
} else {
return nil, fmt.Errorf("incorrect arguments")
}
}
return etcd.ConfigToClient(fileConfig)
}
func printUsage() {
fmt.Printf("\n\n%s: [--cfg CONFIG_FILE] <delete NAME | put NAME COMPANY PHONE>\n\n", os.Args[0])
}
func main() {
cfg, err := processArgs()
if err != nil {
printUsage()
fmt.Println(err)
os.Exit(1)
}
// Create connection to etcd.
db, err := etcd.NewEtcdConnectionWithBytes(*cfg, logrus.DefaultLogger())
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Initialize proto decorator.
protoDb := kvproto.NewProtoWrapper(db)
// Retrieve all contacts from database.
resp, err := protoDb.ListValues(phonebook.EtcdPath())
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Print out all contacts one-by-one.
var revision int64
fmt.Println("Phonebook:")
for {
c := &phonebook.Contact{}
kv, stop := resp.GetNext()
if stop {
break
}
// Maintain the latest revision.
if kv.GetRevision() > revision {
revision = kv.GetRevision()
}
err = kv.GetValue(c)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("\t%s\n\t\t%s\n\t\t%s\n", c.Name, c.Company, c.Phonenumber)
}
fmt.Println("Revision", revision)
protoDb.Close()
}