-
Notifications
You must be signed in to change notification settings - Fork 2
/
reponse_time.go
44 lines (37 loc) · 963 Bytes
/
reponse_time.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
package fox
import (
"fmt"
"time"
"github.com/gin-gonic/gin"
)
const headerXResponseTime = "X-Response-Time"
// XResponseTimer wrap gin reponse writer add start time
type XResponseTimer struct {
gin.ResponseWriter
start time.Time
key string
}
// WriteHeader implement http.ResponseWriter
func (w *XResponseTimer) WriteHeader(statusCode int) {
w.Header().Set(w.key, fmt.Sprintf("%d, %d", w.start.UnixMilli(), time.Since(w.start).Nanoseconds()))
w.ResponseWriter.WriteHeader(statusCode)
}
// Write implement http.ResponseWriter
func (w *XResponseTimer) Write(b []byte) (int, error) {
return w.ResponseWriter.Write(b)
}
// NewXResponseTimer x-response-time middleware
func NewXResponseTimer(key ...string) gin.HandlerFunc {
k := headerXResponseTime
if len(key) > 0 {
k = key[0]
}
return func(c *gin.Context) {
c.Writer = &XResponseTimer{
ResponseWriter: c.Writer,
start: time.Now(),
key: k,
}
c.Next()
}
}