File: timer.go

package info (click to toggle)
golang-github-ant0ine-go-json-rest 3.3.2-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 324 kB
  • sloc: makefile: 2
file content (26 lines) | stat: -rw-r--r-- 679 bytes parent folder | download
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
package rest

import (
	"time"
)

// TimerMiddleware computes the elapsed time spent during the execution of the wrapped handler.
// The result is available to the wrapping handlers as request.Env["ELAPSED_TIME"].(*time.Duration),
// and as request.Env["START_TIME"].(*time.Time)
type TimerMiddleware struct{}

// MiddlewareFunc makes TimerMiddleware implement the Middleware interface.
func (mw *TimerMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc {
	return func(w ResponseWriter, r *Request) {

		start := time.Now()
		r.Env["START_TIME"] = &start

		// call the handler
		h(w, r)

		end := time.Now()
		elapsed := end.Sub(start)
		r.Env["ELAPSED_TIME"] = &elapsed
	}
}