-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsession.go
109 lines (99 loc) · 1.89 KB
/
session.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
106
107
108
109
package main
import (
"fmt"
"os"
"strings"
"github.com/syndtr/goleveldb/leveldb"
)
// Session ...
type Session struct {
DB *leveldb.DB
}
// NewSession create session
func NewSession(path string) (*Session, error) {
db, err := leveldb.OpenFile(path, nil)
if err != nil {
return nil, err
}
return &Session{db}, nil
}
// Exec cmd
func (s *Session) Exec(cmd string) {
cmds := strings.Split(cmd, " ")
switch cmds[0] {
case "":
case "help":
printHelp()
case "exit":
s.DB.Close()
os.Exit(0)
case "keys":
s.keys()
case "get":
s.get(cmds)
case "put":
s.put(cmds)
case "del":
s.del(cmds)
default:
fmt.Printf("Unknow cmd %s.\n", cmd)
printHelp()
}
}
func (s *Session) keys() {
iter := s.DB.NewIterator(nil, nil)
keys := ""
for iter.Next() {
key := iter.Key()
keys = string(key) + "\n"
}
iter.Release()
err := iter.Error()
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
} else {
fmt.Print(keys)
}
}
func (s *Session) get(cmds []string) {
if len(cmds) != 2 {
fmt.Println("error get cmd")
return
}
v, err := s.DB.Get([]byte(cmds[1]), nil)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
} else {
fmt.Println(string(v))
}
}
func (s *Session) put(cmds []string) {
if len(cmds) != 3 {
fmt.Println("error put cmd")
return
}
err := s.DB.Put([]byte(cmds[1]), []byte(cmds[2]), nil)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
}
}
func (s *Session) del(cmds []string) {
if len(cmds) != 2 {
fmt.Println("error del cmd")
return
}
err := s.DB.Delete([]byte(cmds[1]), nil)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
}
}
func printHelp() {
fmt.Println(`Commands:
keys list the keys in the current range
get get a key from the database <str>
put put a key/value into the database <str>
del delete a key/value from the database <str>
exit quit cli
help print this list of REPL commands
`)
}