created hws module
This commit is contained in:
33
hws/middleware_timer.go
Normal file
33
hws/middleware_timer.go
Normal file
@@ -0,0 +1,33 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user