2020-07-29 18:00:04 +08:00
|
|
|
package handler
|
2020-07-26 17:09:05 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
2020-08-08 16:40:10 +08:00
|
|
|
"github.com/tal-tech/go-zero/core/stat"
|
|
|
|
"github.com/tal-tech/go-zero/core/timex"
|
2020-07-26 17:09:05 +08:00
|
|
|
)
|
|
|
|
|
2021-03-01 19:15:35 +08:00
|
|
|
// MetricHandler returns a middleware that stat the metrics.
|
2020-07-26 17:09:05 +08:00
|
|
|
func MetricHandler(metrics *stat.Metrics) func(http.Handler) http.Handler {
|
|
|
|
return func(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
startTime := timex.Now()
|
|
|
|
defer func() {
|
|
|
|
metrics.Add(stat.Task{
|
|
|
|
Duration: timex.Since(startTime),
|
|
|
|
})
|
|
|
|
}()
|
|
|
|
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|