-
Notifications
You must be signed in to change notification settings - Fork 2
/
stopwatch.go
42 lines (35 loc) · 1.05 KB
/
stopwatch.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
package stopwatch
import (
"net/http"
"time"
)
// Measure latency in nanoseconds
func Measure(f func()) int64 {
start := time.Now().UnixNano()
f()
return time.Now().UnixNano() - start
}
// LatencyHandler is a middleware that measures latency given http.Handler struct.
func LatencyHandler(resultChan chan int64, methods []string, next http.Handler) http.Handler {
middle := func(w http.ResponseWriter, r *http.Request) {
foundMethod := false
for _, method := range methods {
if r.Method == method {
foundMethod = true
break
}
}
if foundMethod && resultChan != nil {
start := time.Now().UnixNano()
defer func() {
resultChan <- (time.Now().UnixNano() - start)
}()
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(middle)
}
// LatencyFuncHandler is a middleware that measures latency given request handler function.
func LatencyFuncHandler(resultChan chan int64, methods []string, nextFunc func(http.ResponseWriter, *http.Request)) http.Handler {
return LatencyHandler(resultChan, methods, http.HandlerFunc(nextFunc))
}