forked from SideCar6/aegis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
116 lines (97 loc) · 2.64 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
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
package main
import (
"log"
"net/http"
"strings"
"net/url"
"fmt"
"github.com/SideCar6/aegis/aegis_redis"
"code.google.com/p/go.net/websocket"
)
var chttp = http.NewServeMux()
const api_url string = "/api/v1"
var openSockets []*websocket.Conn
func main() {
http.Handle("/websockets", websocket.Handler(socketServer))
chttp.Handle("/", http.FileServer(http.Dir("./public")))
http.HandleFunc("/", HomeHandler)
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Write([]byte("Hello"))
})
http.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Write([]byte("Test"))
})
http.HandleFunc(api_url + "/keys/", func(w http.ResponseWriter, r *http.Request) {
keys := aegis_redis.GetKeys()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
w.Write(keys.ToJSON())
})
http.HandleFunc(api_url + "/stats", func(w http.ResponseWriter, r *http.Request) {
log.Println(r.Method)
switch r.Method {
case "GET":
getStats(w, r)
case "POST":
postStats(w, r)
}
})
fmt.Println(" ___")
fmt.Println("// \\\\ AEGIS")
fmt.Println("\\\\___// STATS\n")
fmt.Println("[ AEGIS ]\tServer started, listening on port 3000")
log.Fatal(http.ListenAndServe(":3000", nil))
}
func socketServer(ws *websocket.Conn) {
fmt.Println("New connection")
openSockets = append(openSockets, ws)
buf := make([]byte, 100)
for {
mess, err := ws.Read(buf)
if err == nil {
fmt.Println(string(buf[0:mess]))
continue
}
for i, s := range openSockets {
if ws != s {
continue
} else {
openSockets = append(openSockets[:i], openSockets[i + 1:]...)
}
}
fmt.Println("%s", err.Error())
break
}
fmt.Println("Closing connection")
}
func sendMessage(msg string) {
for _, ws := range openSockets {
ws.Write([]byte(msg))
}
}
func getStats(w http.ResponseWriter, r *http.Request) {
qs := r.URL.Query()
key, _ := url.QueryUnescape(qs.Get("key"))
stats := aegis_redis.GetList(key, 0, -1)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
w.Write(stats.ToJSON())
}
func postStats(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
body := r.Form["value"][0]
key := r.Form["key"][0]
fmt.Println(body, key)
aegis_redis.SetKey(key, body)
w.WriteHeader(201)
sendMessage("{\"" + key + "\":" + body + "}")
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, ".") {
chttp.ServeHTTP(w, r)
} else {
http.ServeFile(w, r, "./public/index.html")
}
}