Files
golib/hws/middleware_timer.go
2026-01-04 00:59:24 +11:00

34 lines
776 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)
},
)
}
// Set the start time of the request
func setStart(ctx context.Context, time time.Time) context.Context {
return context.WithValue(ctx, "hws context key request-timer", time)
}
// Get the start time of the request
func getStartTime(ctx context.Context) (time.Time, error) {
start, ok := ctx.Value("hws context key request-timer").(time.Time)
if !ok {
return time.Time{}, errors.New("Failed to get start time of request")
}
return start, nil
}