-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
129 lines (105 loc) · 2.19 KB
/
main.go
File metadata and controls
129 lines (105 loc) · 2.19 KB
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package main
import (
"bufio"
"fmt"
"net"
"strings"
"sync"
)
type Storage struct {
data map[string]string
mu sync.RWMutex
}
func initStorage() *Storage {
storage := &Storage{data: make(map[string]string)}
return storage
}
func (storage *Storage) Set(key, val string) bool {
storage.mu.Lock()
defer storage.mu.Unlock()
storage.data[key] = val
return true
}
func (storage *Storage) Get(key string) (string, bool) {
storage.mu.RLock()
defer storage.mu.RUnlock()
val, ok := storage.data[key]
if ok {
return val, ok
}
return "", ok
}
func (storage *Storage) Delete(key string) bool {
storage.mu.Lock()
defer storage.mu.Unlock()
_, ok := storage.data[key]
if ok {
delete(storage.data, key)
}
return ok
}
func runServer(storage *Storage) {
listener, err := net.Listen("tcp", ":8080")
if err != nil {
fmt.Println("Error starting server:", err)
return
}
defer listener.Close()
fmt.Println("Server is listening on :8080")
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println("Connection err")
continue
}
handleConn(conn, storage)
}
}
func handleConn(conn net.Conn, storage *Storage) {
defer conn.Close()
scanner := bufio.NewScanner(conn)
for scanner.Scan() {
text := scanner.Text()
commands := strings.Fields(text)
if len(commands) == 0 {
continue
}
command := strings.ToLower(commands[0])
switch command {
case "set":
if len(commands) < 3 {
conn.Write([]byte("Use command: set <key> <value>\n"))
continue
}
if ok := storage.Set(commands[1], commands[2]); ok {
conn.Write([]byte("Ok\n"))
}
case "get":
if len(commands) < 2 {
conn.Write([]byte("Use command: get <key>\n"))
continue
}
if value, ok := storage.Get(commands[1]); ok {
conn.Write([]byte(value + "\n"))
} else {
conn.Write([]byte("Key not found\n"))
}
case "del":
if len(commands) < 2 {
conn.Write([]byte("Use command: del <key>\n"))
continue
}
if ok := storage.Delete(commands[1]); ok {
conn.Write([]byte("Ok\n"))
} else {
conn.Write([]byte("Key not found\n"))
}
default:
conn.Write([]byte("Unknown command\n"))
}
}
}
func main() {
storage := initStorage()
runServer(storage)
}