metrichandler.go 537 B

123456789101112131415161718192021222324
  1. package handler
  2. import (
  3. "net/http"
  4. "git.i2edu.net/i2/go-zero/core/stat"
  5. "git.i2edu.net/i2/go-zero/core/timex"
  6. )
  7. // MetricHandler returns a middleware that stat the metrics.
  8. func MetricHandler(metrics *stat.Metrics) func(http.Handler) http.Handler {
  9. return func(next http.Handler) http.Handler {
  10. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  11. startTime := timex.Now()
  12. defer func() {
  13. metrics.Add(stat.Task{
  14. Duration: timex.Since(startTime),
  15. })
  16. }()
  17. next.ServeHTTP(w, r)
  18. })
  19. }
  20. }