/
server.go
140 lines (124 loc) · 3.46 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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package main
import (
"log"
"math/rand"
"net/http"
"net/url"
"os"
"regexp"
"strconv"
"time"
"code.google.com/p/go.blog/content/context/userip"
)
type EventStruct struct {
Id string
Event string
IP string
URI string
Host string
Path string
Query string
UserAgent string
Timestamp time.Time
Action string
}
var ipStore map[string]time.Time
var findStripper *regexp.Regexp
var mngoConnection MngoConnection
func main() {
mngoConnection = MngoConnection{}
mngoConnection.open()
mngoConnection.Opensession = true
findStripper = regexp.MustCompile("ObjectId|\\W")
ipStore = make(map[string]time.Time)
http.HandleFunc("/getTotal", getTotal)
http.HandleFunc("/getSeries", getSeries)
http.HandleFunc("/", handleEvent)
log.Fatal(http.ListenAndServe(":"+os.Getenv("PORT"), nil))
}
func saveIPToBlockList(ip string, timestamp time.Time) {
// dummy function
time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
log.Printf("saved IP %s to Blocklist, time: %s", ip, time.Since(timestamp))
}
// "intelligenter" IP Blocker
func ipBlocker(ip string) bool {
block := ipStore[ip].After(time.Now().Add(-1 * time.Second * 3))
if block {
go saveIPToBlockList(ip, time.Now())
}
return block
}
// Handle HTTP Request
func handleEvent(w http.ResponseWriter, req *http.Request) {
log.Println("Handle event")
userIP, err := userip.FromRequest(req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// check if IP is requesting too frequently
if ipBlocker(userIP.String()) {
http.Error(w, "too many request from "+userIP.String(), http.StatusBadRequest)
return
} else {
ipStore[userIP.String()] = time.Now()
}
requrl, _ := url.QueryUnescape(req.FormValue("uri"))
parsedURI, _ := url.Parse(requrl)
event := EventStruct{
Id: req.FormValue("id"),
Event: req.FormValue("event"),
IP: userIP.String(),
URI: requrl,
Host: parsedURI.Host,
Path: parsedURI.Path,
Query: parsedURI.RawQuery,
UserAgent: req.UserAgent(),
Timestamp: time.Now(),
Action: req.FormValue("action"),
}
if event.Id == "" || event.Event == "" {
http.Error(w, "no query", http.StatusBadRequest)
return
}
// write back to the user, thus the HTTP(s) request
// doesn't block anything at client-side
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Write(nil)
// save Event to all our cool backends / services
saveEvent(event)
}
func saveEvent(event EventStruct) {
saverChannel := make(chan bool)
go func() { saverChannel <- SaveToMongoDB(mngoConnection, event) }()
go func() { saverChannel <- PrintToStdout(event) }()
var savings []bool
for i := 0; i < 2; i++ {
checkBool := <-saverChannel
if checkBool {
savings = append(savings, checkBool)
}
}
if len(savings) == 2 {
log.Println("EVERYTHING SAVED!")
}
}
func getTotal(w http.ResponseWriter, req *http.Request) {
id := findStripper.ReplaceAllString(req.FormValue("id"), "")
days := findStripper.ReplaceAllString(req.FormValue("days"), "")
daysInt, _ := strconv.Atoi(days)
if daysInt < 1 {
daysInt = 30
}
GetTotalById(mngoConnection, w, id, time.Hour*time.Duration(daysInt*24))
}
func getSeries(w http.ResponseWriter, req *http.Request) {
id := findStripper.ReplaceAllString(req.FormValue("id"), "")
days := findStripper.ReplaceAllString(req.FormValue("days"), "")
daysInt, _ := strconv.Atoi(days)
if daysInt < 1 {
daysInt = 30
}
GetSeriesById(mngoConnection, w, id, time.Hour*time.Duration(daysInt*24))
}