func SetTestHookServerServe(fn func(*Server, net.Listener)) { testHookServerServe = fn }
func NewTestTimeoutHandler(handler Handler, ch <-chan time.Time) Handler {
+ ctx, cancel := context.WithCancel(context.Background())
+ go func() {
+ <-ch
+ cancel()
+ }()
return &timeoutHandler{
handler: handler,
- testTimeout: ch,
+ testContext: ctx,
// (no body)
}
}
body string
dt time.Duration
- // When set, no timer will be created and this channel will
+ // When set, no context will be created and this context will
// be used instead.
- testTimeout <-chan time.Time
+ testContext context.Context
}
func (h *timeoutHandler) errorBody() string {
}
func (h *timeoutHandler) ServeHTTP(w ResponseWriter, r *Request) {
- var t *time.Timer
- timeout := h.testTimeout
- if timeout == nil {
- t = time.NewTimer(h.dt)
- timeout = t.C
+ ctx := h.testContext
+ if ctx == nil {
+ var cancelCtx context.CancelFunc
+ ctx, cancelCtx = context.WithTimeout(r.Context(), h.dt)
+ defer cancelCtx()
}
+ r = r.WithContext(ctx)
done := make(chan struct{})
tw := &timeoutWriter{
w: w,
}
w.WriteHeader(tw.code)
w.Write(tw.wbuf.Bytes())
- if t != nil {
- t.Stop()
- }
- case <-timeout:
+ case <-ctx.Done():
tw.mu.Lock()
defer tw.mu.Unlock()
w.WriteHeader(StatusServiceUnavailable)