-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
176 lines (147 loc) · 4.28 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
package main
import (
"encoding/json"
"log"
"net"
"net/http"
"net/url"
"os"
"strconv"
"time"
"github.com/jellydator/ttlcache/v3"
)
type NotesCount struct {
Domain string `json:"domain"`
Count int `json:"count"`
}
type NotesRequest struct {
Domain string `json:"domain"`
}
// https://golangcode.com/get-the-request-ip-addr/
// https://stackoverflow.com/a/33301173
func GetIP(r *http.Request) string {
forwarded := r.Header.Get("X-Real-IP")
if forwarded != "" {
return forwarded
}
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
return ip
}
func GetJustDomain(myUrl string) string {
// turns a URL into just the domain
// e.g. https://example.com/notes -> example.com
parsedUrl, err := url.Parse(myUrl)
if err != nil {
return ""
}
return parsedUrl.Hostname()
}
func GetDomain(r *http.Request) string {
forwarded := r.Header.Get("Origin")
if forwarded != "" {
return GetJustDomain(forwarded)
}
referer := r.Header.Get("Referer")
if referer != "" {
return GetJustDomain(referer)
}
return ""
}
func getByesOfFileAtPath(name string) []byte {
file, err := os.Open(name)
if err != nil {
log.Fatal(err)
}
defer file.Close()
stat, err := file.Stat()
if err != nil {
log.Fatal(err)
}
bs := make([]byte, stat.Size())
_, err = file.Read(bs)
if err != nil {
log.Fatal(err)
}
return bs
}
func main() {
log.Println("Welcome to the IPNotes Counter, see the readme for more information")
domainCacheTimeout := 24 * time.Hour
userCacheTimeout := 20 * time.Minute
// userCacheTimeout := 30 * time.Second // debugging
cacheOfCaches := ttlcache.New(
ttlcache.WithTTL[string, *ttlcache.Cache[string, bool]](domainCacheTimeout),
)
// our main endpoint, receive the domain and IP and increment the count
http.HandleFunc("/count", func(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Access-Control-Allow-Origin", "*")
ip := GetIP(req)
domain := GetDomain(req)
if domain == "" {
res.WriteHeader(http.StatusBadRequest)
res.Write([]byte("Please provide a an Origin or Referer header in your request."))
return
}
// get the IP cache of this domain, or create it if it doesn't exist
userResp := cacheOfCaches.Get(domain)
var userCache *ttlcache.Cache[string, bool]
if userResp == nil {
newCache := ttlcache.New(
ttlcache.WithTTL[string, bool](userCacheTimeout),
)
cacheOfCaches.Set(domain, newCache, domainCacheTimeout)
userCache = newCache
go userCache.Start()
} else {
userCache = userResp.Value()
}
// track this IP under this domain
userCache.Set(ip, true, userCacheTimeout)
// return the count
count := NotesCount{Domain: domain, Count: int(userCache.Len())}
output, _ := json.MarshalIndent(count, "", "\t")
res.Write(output)
})
http.HandleFunc("/stats", func(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Access-Control-Allow-Origin", "*")
// respond with the count for this domain, irrespective of IP (for read only)
// get the domain from the request (query param)
domain := req.URL.Query().Get("domain")
if domain == "" {
res.WriteHeader(http.StatusBadRequest)
res.Write([]byte("Please provide a domain, e.g. ?domain=example.com"))
return
}
userResp := cacheOfCaches.Get(domain)
userCount := -1
if userResp != nil {
userCache := userResp.Value()
userCount = int(userCache.Len())
}
// return the count
count := NotesCount{Domain: domain, Count: userCount}
output, _ := json.MarshalIndent(count, "", "\t")
res.Write(output)
})
// serve the static files
// read some static files into memory
indexHtml := getByesOfFileAtPath("./index.html")
taggerJs := getByesOfFileAtPath("./tagger.js")
widgetHtml := getByesOfFileAtPath("./widget.html")
http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Access-Control-Allow-Origin", "*")
res.Write(indexHtml)
})
http.HandleFunc("/tag", func(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Access-Control-Allow-Origin", "*")
res.Write(taggerJs)
})
http.HandleFunc("/view", func(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Access-Control-Allow-Origin", "*")
res.Write(widgetHtml)
})
port := 7711
log.Printf("Listening on localhost:%d\n", port)
go cacheOfCaches.Start()
log.Fatal(http.ListenAndServe(":"+strconv.Itoa(port), nil))
}