-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
123 lines (99 loc) · 2.01 KB
/
main.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"testt/memory"
"testt/presist"
"github.com/go-chi/chi/v5"
)
type Store interface {
Set(string, any)
Get(string) (any, error)
Delete(string)
}
type KeyValPair struct {
Key string `json:"key"`
Value any `json:"value"`
}
func getValue(w http.ResponseWriter, r *http.Request) {
val, err := myStore.Get(chi.URLParam(r, "key"))
if err != nil {
resBody := formatResponseBody(nil)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(404)
w.Write(resBody)
return
}
resBody := formatResponseBody(val)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
w.Write(resBody)
}
func setValue(w http.ResponseWriter, r *http.Request) {
var data KeyValPair
err := json.NewDecoder(r.Body).Decode(&data)
if err != nil {
fmt.Println(err)
return
}
myStore.Set(data.Key, data.Value)
w.WriteHeader(201)
}
func deleteValue(w http.ResponseWriter, r *http.Request) {
// _, err := inMemoryStore.get(chi.URLParam(r, "key"))
// if err != nil {
// w.WriteHeader(404)
// return
// }
myStore.Delete(chi.URLParam(r, "key"))
w.WriteHeader(200)
}
func formatResponseBody(data any) []byte {
responseBody, err := json.Marshal(struct {
Value any `json:"value"`
}{Value: data})
if err != nil {
log.Fatal(err)
}
return responseBody
}
var myStore Store
func main() {
if len(os.Args) > 1 {
flag := os.Args[1]
switch flag {
case "-p":
myStore = presist.Connect()
case "-m":
myStore = memory.InMemoryStore
case "-h":
fmt.Println("use -p to presist in database or -m to presist in memory")
return
default:
log.Fatal("Invalid input for help -h")
}
} else {
log.Fatal("Invalid input for help -h")
}
r := chi.NewRouter()
r.Get("/{key}", getValue)
r.Post("/", setValue)
r.Delete("/{key}", deleteValue)
err := http.ListenAndServe(":5000", r)
if err != nil {
log.Fatal(err)
}
}
/*
in-memory
- rest http (done)
- socket tcp
- grpc
presist
- rest http (done)
- socket tcp
- grpc
*/