-
Notifications
You must be signed in to change notification settings - Fork 31
/
main.go
101 lines (79 loc) · 1.74 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
package main
import (
"embed"
"flag"
"io/fs"
"log"
"net/http"
"strings"
"github.com/asim/kayvee/server"
)
//go:embed client/*
var html embed.FS
var (
nodes = flag.String("nodes", "", "comma seperated list of nodes")
address = flag.String("address", ":4001", "http host:port")
// global server
srv *server.Server
)
func init() {
flag.Parse()
}
func delHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
key := r.Form.Get("key")
if err := srv.Delete(key); err != nil {
http.Error(w, err.Error(), 500)
return
}
}
func getHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
key := r.Form.Get("key")
val, err := srv.Get(key)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
w.Write([]byte(val.(string)))
}
func setHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
key := r.Form.Get("key")
val := r.Form.Get("val")
if err := srv.Set(key, val); err != nil {
http.Error(w, err.Error(), 500)
return
}
}
func main() {
var members []string
if len(*nodes) > 0 {
members = strings.Split(*nodes, ",")
}
// create new server
s, err := server.New(&server.Options{
Members: members,
})
if err != nil {
log.Fatal(err)
}
// set global server
srv = s
log.Printf("Local node %s\n", srv.Address())
// set http handlers
http.HandleFunc("/get", getHandler)
http.HandleFunc("/set", setHandler)
http.HandleFunc("/del", delHandler)
// extract the embedded html directory
htmlContent, err := fs.Sub(html, "client")
if err != nil {
log.Fatal(err)
}
// serve the html directory by default
http.Handle("/", http.FileServer(http.FS(htmlContent)))
log.Printf("Listening on %s\n", *address)
if err := http.ListenAndServe(*address, nil); err != nil {
log.Fatal(err)
}
}