package test

import (
	"io"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"sync"
	"testing"
	"time"
)

func TestServerKeepAliveReadTimeoutCloseNotify(t *testing.T) {
	var startMu sync.Mutex
	var start time.Time

	testServer := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		cn := w.(http.CloseNotifier)
		select {
		case <-time.After(40 * time.Millisecond):
		case <-cn.CloseNotify():
			startMu.Lock()
			delta := time.Since(start)
			startMu.Unlock()
			t.Errorf("Unexpected CloseNotify received after %s", delta)
		}
	}))
	testServer.Config.ReadTimeout = 100 * time.Millisecond
	testServer.Start()
	defer testServer.Close()

	for i := 0; i < 2; i++ {
		startMu.Lock()
		start = time.Now()
		startMu.Unlock()

		resp, err := http.Get(testServer.URL)
		if err != nil {
			t.Fatal(err)
		}
		_, err = io.Copy(ioutil.Discard, resp.Body)
		if err != nil {
			t.Fatal(err)
		}
		err = resp.Body.Close()
		if err != nil {
			t.Fatal(err)
		}

		time.Sleep(70 * time.Millisecond)
	}
}
