-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
90 lines (70 loc) · 1.79 KB
/
server.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
package main
import (
"encoding/json"
"github.com/go-zoo/bone"
"log"
"net/http"
)
const username = ""
const database = ""
const hostname = ""
const port = 5432
const password = ""
func main() {
mux := bone.New()
mux.Get("/v1/cache/:key", http.HandlerFunc(getCache))
mux.Post("/v1/cache", http.HandlerFunc(setCache))
mux.Get("/v1/clear-cache/:key", http.HandlerFunc(clearCache))
http.ListenAndServe(":8000", mux)
}
var dbh = DBConnect{Username: username, Database: database, Hostname: hostname, Port: port, Password: password}
var db = connectDB(dbh)
func getCache(rw http.ResponseWriter, req *http.Request) {
key := bone.GetValue(req, "key")
rw.Header().Set("Content-Type", "application/json")
result, err := GetCache(db, key)
if err != nil {
log.Print(err)
}
r, err := json.Marshal(result)
if err != nil {
log.Print(err)
rw.WriteHeader(http.StatusInternalServerError)
rw.Write([]byte("fail"))
} else {
rw.WriteHeader(http.StatusOK)
rw.Write([]byte(r))
}
}
func setCache(rw http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
var record Record
var err error
err = decoder.Decode(&record)
rw.Header().Set("Content-Type", "application/json")
if err != nil {
log.Print(err)
}
_, err = SetCache(db, record)
if err != nil {
log.Print(err)
rw.WriteHeader(http.StatusInternalServerError)
rw.Write([]byte("fail"))
} else {
rw.WriteHeader(http.StatusOK)
rw.Write([]byte("ok"))
}
}
func clearCache(rw http.ResponseWriter, req *http.Request) {
key := bone.GetValue(req, "key")
_, err := ClearCache(db, key)
rw.Header().Set("Content-Type", "application/json")
if err != nil {
log.Print(err)
rw.WriteHeader(http.StatusInternalServerError)
rw.Write([]byte("fail"))
} else {
rw.WriteHeader(http.StatusOK)
rw.Write([]byte("ok"))
}
}