/
profiler.go
90 lines (67 loc) · 1.18 KB
/
profiler.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
package profiler
import (
"net/http"
"sync"
"time"
h "github.com/cortezaproject/corteza/server/pkg/http"
)
type (
Profiler struct {
mux sync.RWMutex
l Hits
}
)
func New() *Profiler {
return &Profiler{l: make(Hits)}
}
func (p *Profiler) Hit(r *h.Request) (h *Hit) {
var (
n = time.Now()
)
h = &Hit{"", http.StatusOK, 0, r, &n, nil, nil}
h.generateID()
return
}
func (p *Profiler) Push(h *Hit) (id string) {
p.mux.Lock()
defer p.mux.Unlock()
if h.Tf == nil {
n := time.Now()
d := n.Sub(*h.Ts)
h.Tf = &n
h.D = &d
}
h.generateID()
id = p.id(h.R)
p.l[id] = append(p.l[id], h)
return
}
func (p *Profiler) Hits(s Sort) Hits {
p.mux.RLock()
defer p.mux.RUnlock()
ll := p.l.Filter(func(k string, v *Hit) bool {
var b bool = true
if s.Path != "" && v.R.URL.Path != s.Path {
b = false
}
if s.Hit != "" && v.ID != s.Hit {
b = false
}
return b
})
return ll
}
func (p *Profiler) Purge(f *PurgeFilter) {
p.mux.Lock()
defer p.mux.Unlock()
if f.RouteID == 0 {
p.l = make(Hits, 0)
return
}
p.l = p.l.Filter(func(k string, v *Hit) bool {
return v.Route != f.RouteID
})
}
func (p *Profiler) id(r *h.Request) string {
return r.URL.Path
}