通过实现一个简单的K–V存储数据库,学习Go语言(二)
实现本地增删改查功能(使用map)
命令为 SET
DELETE
UPDATE
GET
SHOW
- 添加新元素
- 基于key删除已有的元素
- 修改key对应的value
- 给定key查找对应value
- 查找所有key,value
定义全局map
var DATA = map[string]string{}
实现增删改查
func SET(key string, value string) {
if _, ok := DATA[key]; !ok {
DATA[key] = value
//fmt.Println("set successful!")
} else {
fmt.Println("error: existence of this key!")
}
}
func GET(key string) {
if _, ok := DATA[key]; !ok {
fmt.Println("error: not found this key!")
} else {
fmt.Printf("%s\n", DATA[key])
}
}
func DELETE(key string) {
if _, ok := DATA[key]; !ok {
fmt.Println("error: not found this key!")
} else {
delete(DATA, key)
//fmt.Println("delete successful!")
}
}
func UPDATE(key string, value string) {
if _, ok := DATA[key]; !ok {
fmt.Println("error: not found this key!")
} else {
DATA[key] = value
//fmt.Println("update successful!")
}
}
func SHOW() {
for k, v := range DATA {
fmt.Printf("%s:%s\n", k, v)
}
}
命令行实现
func main() {
cmd := []string{}
s := bufio.NewScanner(os.Stdin)
//不断读入命令
for s.Scan() {
text := s.Text()
//分割命令与参数
cmd = strings.Split(text, " ")
//strings.TrimSpace()
//strings.Fields()
//判断对应命令
switch cmd[0] {
case "SET":
SET(cmd[1], cmd[2])
case "GET":
GET(cmd[1])
case "SHOW":
SHOW()
case "DELETE":
DELETE(cmd[1])
case "UPDATE":
UPDATE(cmd[1], cmd[2])
default:
fmt.Println("Unknown command - please try again!")
}
}
}
实现结果
SET test1 2
GET test1
2
GET test22
error: not found this key!
SHOW
test:1
test1:2
UPDATE test 111
GET test
111
SHOW
test:111
test1:2
下一步将 key-value 进行持久化存储和实现TCP/IP接口访问