-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
80 lines (75 loc) · 1.99 KB
/
router.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
package cloudlocker
import (
"encoding/json"
"github.com/gorilla/mux"
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/opt"
"io/ioutil"
"net/http"
)
func NewRouter(server *LockerServer) http.Handler {
router := mux.NewRouter()
router.HandleFunc("/set", HandleSet(server)).Methods("POST")
router.HandleFunc("/get", HandleGet(server)).Methods("POST")
router.HandleFunc("/delete", HandleDelete(server)).Methods("POST")
return router
}
func HandleSet(server *LockerServer) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var e Entry
err = json.Unmarshal(body, &e)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_ = server.db.Put(e.K, e.V, &opt.WriteOptions{Sync: false})
}
}
func HandleGet(server *LockerServer) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
v, err := server.db.Get(body, nil)
if err != nil {
if err != leveldb.ErrNotFound {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
_, _ = w.Write(v)
}
}
func HandleDelete(server *LockerServer) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//log.Println("r.Body", string(body))
_ = server.db.Delete(body, nil)
}
}