-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
114 lines (102 loc) · 2.31 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
package main
import (
"io"
"log"
"math"
"net/http"
"os"
"strconv"
)
func main() {
logDir := getEnv("DATABASE_DIR", DEFAULT_DATABASE_DIR)
logStore, err := CreateLogStore(logDir, nil)
if err != nil {
log.Fatalf("couldn't create log store: %s", err)
}
http.HandleFunc("/get", get(logStore))
http.HandleFunc("/set", set(logStore))
http.HandleFunc("/delete", del(logStore))
http.ListenAndServe(":"+getEnv("PORT", "8000"), nil)
}
func get(logStore *LogStore) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
key := req.URL.Query().Get("key")
if key == "" {
w.WriteHeader(400)
w.Write([]byte("missing ?key"))
return
}
found, err := logStore.StreamGet(key, w)
if err != nil {
log.Printf("couldn't get %s: %s", key, err)
w.WriteHeader(500)
return
}
if !found {
w.WriteHeader(404)
return
}
if err != nil {
log.Printf("couldn't get %s: %s", key, err)
w.WriteHeader(500)
return
}
}
}
func set(logStore *LogStore) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
key := req.URL.Query().Get("key")
if key == "" {
w.WriteHeader(400)
w.Write([]byte("missing ?key"))
return
}
var expire int
_expire := req.URL.Query().Get("expire")
if _expire == "" {
expire = math.MaxInt64 // Unix milliseconds
} else {
i, err := strconv.Atoi(_expire)
if err != nil {
w.WriteHeader(400)
w.Write([]byte("?expire must be an integer"))
return
}
expire = i
}
value, err := io.ReadAll(req.Body)
if err != nil {
log.Printf("couldn't set %s: %s", key, err)
w.WriteHeader(500)
return
}
err = logStore.Set(key, expire, value)
if err != nil {
log.Printf("couldn't set %s: %s", key, err)
w.WriteHeader(500)
return
}
}
}
func del(logStore *LogStore) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
key := req.URL.Query().Get("key")
if key == "" {
w.WriteHeader(400)
w.Write([]byte("missing ?key"))
return
}
err := logStore.Set(key, 0, []byte(""))
if err != nil {
log.Printf("couldn't delete %s: %s", key, err)
w.WriteHeader(500)
return
}
}
}
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}