-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathtiming.go
More file actions
97 lines (80 loc) · 2 KB
/
timing.go
File metadata and controls
97 lines (80 loc) · 2 KB
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
package diecast
import (
"fmt"
"net/http"
"strings"
"sync"
"time"
"github.com/ghetzel/go-stockutil/stringutil"
"github.com/ghetzel/go-stockutil/typeutil"
)
var reqTimes sync.Map
var timerDescriptions sync.Map
type requestTimer struct {
ID string
Request *http.Request
StartedAt time.Time
Times map[string]time.Duration
}
func startRequestTimer(req *http.Request) {
if id := reqid(req); id != `` {
reqTimes.Store(id, &requestTimer{
ID: id,
Request: req,
StartedAt: time.Now(),
Times: make(map[string]time.Duration),
})
}
}
func describeTimer(key string, desc string) {
timerDescriptions.Store(key, desc)
}
func reqtime(req *http.Request, key string, took time.Duration) {
if id := reqid(req); id != `` {
if v, ok := reqTimes.Load(id); ok {
if timer, ok := v.(*requestTimer); ok {
// log.Debugf("[%v] %v=%v", id, key, took)
timer.Times[key] = took
}
}
}
}
func getRequestTimer(req *http.Request) *requestTimer {
if id := reqid(req); id != `` {
if v, ok := reqTimes.Load(id); ok {
if timer, ok := v.(*requestTimer); ok {
return timer
}
}
}
return nil
}
func writeRequestTimerHeaders(server *Server, w http.ResponseWriter, req *http.Request) {
if server.DisableTimings {
return
}
var timings = make([]string, 0)
if id := reqid(req); id != `` {
if v, ok := reqTimes.Load(id); ok {
if timer, ok := v.(*requestTimer); ok {
for tk, dur := range timer.Times {
var timing string
var outkey = stringutil.Hyphenate(tk)
var outdur = float64(dur/time.Microsecond) / 1000.0
if desc, ok := timerDescriptions.Load(tk); ok {
timing = fmt.Sprintf("%s;desc=%q;dur=%.2f", outkey, typeutil.String(desc), outdur)
} else {
timing = fmt.Sprintf("%s;dur=%.2f", outkey, outdur)
}
timings = append(timings, timing)
}
}
}
if len(timings) > 0 {
w.Header().Set(`Server-Timing`, strings.Join(timings, `, `))
}
}
}
func removeRequestTimer(req *http.Request) {
reqTimes.Delete(reqid(req))
}