-
-
Notifications
You must be signed in to change notification settings - Fork 253
/
high_scores.go
78 lines (64 loc) · 1.65 KB
/
high_scores.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
package handlers
import (
"container/heap"
"encoding/json"
"log"
"net/http"
"github.com/dgraph-io/badger/v2"
"github.com/dustin/go-humanize"
)
// HighScoresHandler handles the stats page
func (gh *GRCHandler) HighScoresHandler(w http.ResponseWriter, r *http.Request, db *badger.DB) {
count, scores := 0, &ScoreHeap{}
err := db.View(func(txn *badger.Txn) error {
var scoreBytes = []byte("[]")
item, err := txn.Get([]byte("scores"))
if err != nil {
log.Println("ERROR:", err)
}
if item != nil {
err = item.Value(func(val []byte) error {
scoreBytes = val
return nil
})
if err != nil {
log.Println("ERROR:", err)
}
}
json.Unmarshal(scoreBytes, scores)
heap.Init(scores)
item, err = txn.Get([]byte("total_repos"))
if item == nil {
count = 0
return nil
}
if item != nil {
err = item.Value(func(val []byte) error {
return json.Unmarshal(val, &count)
})
}
return err
})
if err != nil {
log.Println("ERROR: Failed to load high scores from bolt database: ", err)
http.Error(w, err.Error(), 500)
return
}
t, err := gh.loadTemplate("/templates/high_scores.html")
if err != nil {
log.Println("ERROR: could not get high scores template: ", err)
http.Error(w, err.Error(), 500)
return
}
sortedScores := make([]scoreItem, len(*scores))
for i := range sortedScores {
sortedScores[len(sortedScores)-i-1] = heap.Pop(scores).(scoreItem)
}
if err := t.ExecuteTemplate(w, "base", map[string]interface{}{
"HighScores": sortedScores,
"Count": humanize.Comma(int64(count)),
"google_analytics_key": googleAnalyticsKey,
}); err != nil {
log.Println("ERROR:", err)
}
}