-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
http.go
105 lines (88 loc) · 2.31 KB
/
http.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
// Gone Time Tracker -or- Where has my time gone?
package main
import (
"embed"
"fmt"
"html/template"
"net/http"
"sort"
"time"
)
type Index struct {
Records Records
Classes Classes
Total Duration
Idle Duration
Zzz bool
Refresh time.Duration
}
type Record struct {
Class string
Name string
Spent Duration
Idle Duration
Seen time.Time
}
type Class struct {
Class string
Spent Duration
Percent float64
}
type Records []Record
type Classes []Class
type Duration time.Duration
//go:embed static
var static embed.FS
func (r Records) Len() int { return len(r) }
func (r Records) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
func (r Records) Less(i, j int) bool { return r[i].Spent < r[j].Spent }
func (c Classes) Len() int { return len(c) }
func (c Classes) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
func (c Classes) Less(i, j int) bool { return c[i].Spent < c[j].Spent }
func (d Duration) String() string {
return fmt.Sprint(time.Duration(d).Truncate(time.Second))
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
var idx Index
idx.Zzz = zzz
idx.Refresh = time.Minute // TODO use flag value
class := r.URL.Path[1:]
classes := make(map[string]time.Duration)
for k, v := range tracks {
classes[k.Class] += v.Spent
idx.Total += Duration(v.Spent)
idx.Idle += Duration(v.Idle)
if class != "" && class != k.Class {
continue
}
idx.Records = append(idx.Records, Record{
Class: k.Class,
Name: k.Name,
Spent: Duration(v.Spent),
Idle: Duration(v.Idle)})
}
for k, v := range classes {
idx.Classes = append(idx.Classes, Class{
Class: k,
Spent: Duration(v),
Percent: 100.0 * float64(v) / float64(idx.Total)})
}
sort.Sort(sort.Reverse(idx.Classes))
sort.Sort(sort.Reverse(idx.Records))
tmpl, err := template.ParseFS(static, "static/gone.tmpl")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
if err := tmpl.ExecuteTemplate(w, "root", idx); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func resetHandler(w http.ResponseWriter, r *http.Request) {
tracks.RemoveSince(0)
http.Redirect(w, r, "/", http.StatusFound)
}
func webReporter(port string) error {
http.HandleFunc("/", indexHandler)
http.HandleFunc("/reset", resetHandler)
return http.ListenAndServe(port, nil)
}