-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
248 lines (195 loc) · 4.59 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
package main
import (
"fmt"
"github.com/fiorix/go-redis/redis"
cache "github.com/victorspringer/http-cache"
"github.com/victorspringer/http-cache/adapter/memory"
"golang.org/x/time/rate"
"log"
"net"
"net/http"
"os"
"strings"
"sync"
"time"
)
var PORT = os.Getenv("PORT")
var REDIS_IP = os.Getenv("REDIS_IP")
var REDIS_PORT = os.Getenv("REDIS_PORT")
var APIKEY = os.Getenv("APIKEY")
var increment = 1;
func initRedis() {
client := RedisClient()
client.Set("keys", "")
}
func checkEnv() {
if PORT == "" {
PORT = "7137"
}
if REDIS_PORT == "" {
REDIS_PORT = "6379"
}
if REDIS_IP == "" {
REDIS_IP = "localhost"
}
if APIKEY == "" {
APIKEY = "admin:nimda"
}
}
func RedisClient() *redis.Client {
return redis.New(REDIS_IP + ":" + REDIS_PORT)
}
func sendRedis(w http.ResponseWriter, r *http.Request) {
lat := r.Header.Get("lat")
lon := r.Header.Get("lon")
apikey := r.Header.Get("apikey")
if apikey != APIKEY {
return
}
client := RedisClient()
if err := client.Set("key" + string(increment), string(lat) + "#" + string(lon)); err != nil {
panic(err)
}
keys, err := client.Get("keys")
if err != nil {
panic(err)
}
if err := client.Set("keys", keys + "," + "key" + string(increment) ); err != nil {
panic(err)
}
increment++
if _, err := w.Write([]byte("Done")); err != nil {
panic(err)
}
}
func getRedis(w http.ResponseWriter, r *http.Request) {
client := RedisClient()
keys, err := client.Get("keys")
if err != nil {
panic(err)
}
finalString := ""
arr := strings.Split(keys, ",")
for index, element := range arr {
key, err := client.Get(element)
if err != nil {
panic(err)
}
if index != len(arr) {
finalString += key + ","
} else {
finalString += key
}
}
if _, err := w.Write([]byte(finalString)); err != nil {
panic(err)
}
}
func delRedis(w http.ResponseWriter, r *http.Request) {
apikey := r.Header.Get("apikey")
if apikey != APIKEY {
return
}
client := RedisClient()
keys, err := client.Get("keys")
if err != nil {
panic(err)
}
arr := strings.Split(keys, ",")
for _, element := range arr {
_, err := client.Del(element)
if err != nil {
panic(err)
}
}
_, err = client.Del("keys")
if err != nil {
panic(err)
}
if _, err := w.Write([]byte("Done")); err != nil {
panic(err)
}
}
// Create a custom visitor struct which holds the rate limiter for each
// visitor and the last time that the visitor was seen.
type visitor struct {
limiter *rate.Limiter
lastSeen time.Time
}
// Change the the map to hold values of the type visitor.
var visitors = make(map[string]*visitor)
var mu sync.Mutex
// Run a background goroutine to remove old entries from the visitors map.
func init() {
go cleanupVisitors()
}
func getVisitor(ip string) *rate.Limiter {
mu.Lock()
defer mu.Unlock()
v, exists := visitors[ip]
if !exists {
limiter := rate.NewLimiter(1, 3)
// Include the current time when creating a new visitor.
visitors[ip] = &visitor{limiter, time.Now()}
return limiter
}
// Update the last seen time for the visitor.
v.lastSeen = time.Now()
return v.limiter
}
// Every minute check the map for visitors that haven't been seen for
// more than 3 minutes and delete the entries.
func cleanupVisitors() {
for {
time.Sleep(time.Minute)
mu.Lock()
for ip, v := range visitors {
if time.Since(v.lastSeen) > 3*time.Minute {
delete(visitors, ip)
}
}
mu.Unlock()
}
}
func limit(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
log.Println(err.Error())
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
limiter := getVisitor(ip)
if limiter.Allow() == false {
http.Error(w, http.StatusText(429), http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}
func main() {
checkEnv()
initRedis()
memcached, err := memory.NewAdapter(
memory.AdapterWithAlgorithm(memory.LFU),
memory.AdapterWithCapacity(10000000),
)
if err != nil {
fmt.Println(err)
}
cacheClient, err := cache.NewClient(
cache.ClientWithAdapter(memcached),
cache.ClientWithTTL(1 * time.Minute),
cache.ClientWithRefreshKey("opn"),
)
if err != nil {
fmt.Println(err)
}
http.Handle("/outshine/client/send", limit(http.HandlerFunc(sendRedis)))
http.Handle("/outshine/client/get", http.HandlerFunc(getRedis))
http.Handle("/outshine/client/delete", http.HandlerFunc(delRedis))
http.Handle("/outshine/client/cached", cacheClient.Middleware(http.HandlerFunc(getRedis)))
if err := http.ListenAndServe(":" + PORT, nil); err != nil {
panic(err)
}
}