Files
golib/hws/middleware_timer.go
2026-02-03 18:43:31 +11:00

42 lines
908 B
Go

package hws
import (
"context"
"errors"
"net/http"
"time"
)
func startTimer(next http.Handler) http.Handler {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
ctx := setStart(r.Context(), start)
newReq := r.WithContext(ctx)
next.ServeHTTP(w, newReq)
},
)
}
type contextKey string
func (c contextKey) String() string {
return "hws context key " + string(c)
}
var requestTimerCtxKey = contextKey("request-timer")
// Set the start time of the request
func setStart(ctx context.Context, time time.Time) context.Context {
return context.WithValue(ctx, requestTimerCtxKey, time)
}
// Get the start time of the request
func getStartTime(ctx context.Context) (time.Time, error) {
start, ok := ctx.Value(requestTimerCtxKey).(time.Time)
if !ok {
return time.Time{}, errors.New("failed to get start time of request")
}
return start, nil
}