/
runner.go
105 lines (91 loc) · 1.67 KB
/
runner.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package soko
import (
"flag"
"fmt"
"os"
)
type Runner struct {
ServerID string
backend Backend
}
func (r *Runner) Run(subcommand string, args []string) {
switch subcommand {
case "open", "config":
config, err := NewConfig(args[0], args[1:])
if err != nil {
panic(err)
}
backend, err := FindBackend(config)
if err != nil {
panic(err)
}
r.backend = backend
r.Save()
case "get":
r.prepare()
checkArgSizeOf(args, 1)
key := args[0]
r.Get(key)
case "put":
r.prepare()
checkArgSizeOf(args, 2)
key := args[0]
value := args[1]
r.Put(key, value)
case "delete":
r.prepare()
checkArgSizeOf(args, 1)
key := args[0]
r.Delete(key)
case "version":
fmt.Printf("version v%s\n", Version)
default:
flag.Usage()
}
}
func (r *Runner) Get(key string) {
ret, err := r.backend.Get(r.ServerID, key)
if err != nil {
panic(err)
}
fmt.Println(ret)
}
func (r *Runner) Put(key string, value string) {
err := r.backend.Put(r.ServerID, key, value)
if err != nil {
panic(err)
}
fmt.Println("OK")
}
func (r *Runner) Delete(key string) {
err := r.backend.Delete(r.ServerID, key)
if err != nil {
panic(err)
}
fmt.Println("OK")
}
func (r *Runner) Save() {
err := r.backend.Save()
if err != nil {
panic(err)
}
fmt.Printf("OK: Write config to %s\n", defaultConfigPath)
}
func (r *Runner) prepare() {
config, err := DefaultConfig()
if err != nil {
panic(err)
}
backend, err := FindBackend(config)
if err != nil {
panic(err)
}
r.backend = backend
}
func checkArgSizeOf(args []string, size int) {
if len(args) != size {
fmt.Fprintf(os.Stderr, "Argument size is mismatch for subcommand: %v\n", flag.Args())
flag.Usage()
os.Exit(1)
}
}