-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
83 lines (70 loc) · 2.17 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
package main
import (
"net/http"
"strings"
"time"
"github.com/inconshreveable/log15"
"github.com/prosavage/github-contributions-chart-data/contributions"
)
type CacheEntry struct {
data []byte
timestamp time.Time
}
func main() {
rootLogger := log15.New("caller", "api")
mux := http.NewServeMux()
cache := make(map[string]CacheEntry)
mux.HandleFunc("/contributions/", func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
if strings.HasPrefix(path, "/contributions/") {
username := strings.TrimPrefix(path, "/contributions/")
reqLogger := rootLogger.New("username", username)
cp := contributions.NewContributionsParser(reqLogger, username)
if entry, ok := cache[username]; ok {
if time.Since(entry.timestamp) < time.Hour {
reqLogger.Info("Using cached data", "age", time.Since(entry.timestamp))
_, err := w.Write(entry.data)
if err != nil {
reqLogger.Error("Failed to write response", "error", err)
http.Error(w, "Failed to write response", http.StatusInternalServerError)
return
}
return
} else {
reqLogger.Info("Cached data expired", "age", time.Since(entry.timestamp))
delete(cache, username)
}
}
startTime := time.Now()
data, err := cp.ScrapeContributions()
if err != nil {
reqLogger.Error("Failed to scrape contributions", "error", err)
http.Error(w, "Failed to scrape contributions", http.StatusInternalServerError)
return
}
if len(cache) > 250 {
reqLogger.Info("Cache size exceeded, clearing expired cache entries")
for key, entry := range cache {
if time.Since(entry.timestamp) > time.Hour {
delete(cache, key)
}
}
reqLogger.Info("Cache size after cleanup", "size", len(cache))
}
cache[username] = CacheEntry{
data: data,
timestamp: time.Now(),
}
reqLogger.Info("Contributions scraped", "duration", time.Since(startTime))
_, err = w.Write(data)
if err != nil {
reqLogger.Error("Failed to write response", "error", err)
http.Error(w, "Failed to write response", http.StatusInternalServerError)
return
}
} else {
http.NotFound(w, r)
}
})
http.ListenAndServe(":8080", mux)
}