-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdetectDupesViaCache.go
77 lines (68 loc) · 1.98 KB
/
detectDupesViaCache.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
package main
import (
"fmt"
"log"
"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"
"net/http"
"time"
"strconv"
)
type cacheAccessLog struct {
User_id int `_id`
Ip_addr []string
}
func main() {
//Connecting to mongoDB
session, err := mgo.Dial("localhost")
if err != nil {
log.Fatal(err)
}
defer session.Close()
c := session.DB("local").C("cacheAccessLogOnFly")
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { //localhost:12345/?a=2&b=4
start := time.Now()
q := r.URL.Query()
idA, errA := strconv.Atoi(q.Get("a"))
idB, errB := strconv.Atoi(q.Get("b"))
if errA != nil || errB != nil {
fmt.Fprint(w, "UserID format is not allowed")
return
}
dataA, dataB := cacheAccessLog{}, cacheAccessLog{}
err = c.Find(bson.M{"_id": idA}).One(&dataA)
if err != nil {
fmt.Fprintf(w, "UserID %v %v", idA, err)
return
}
err = c.Find(bson.M{"_id": idB}).One(&dataB)
if err != nil {
fmt.Fprintf(w, "UserID %v %v", idB, err)
return
}
//Create a map with unique ip-addresses for the first UserId
m := map[string]bool{}
for _, v := range dataA.Ip_addr {
m[v] = true
}
//Count matches
matches := 0
for _, v := range dataB.Ip_addr {
if _, ok := m[v]; ok {
matches++
}
}
w.Header().Set("Content-Type", "application/json")
if matches > 1 {
fmt.Fprint(w, "{\"dupes\":true}")
} else {
fmt.Fprint(w, "{\"dupes\":false}")
}
fmt.Println(time.Now().Sub(start))
})
fmt.Println("Service is running")
err = http.ListenAndServe(":12345", nil)
if err != nil {
log.Fatal(err)
}
}