2020-11-07 11:59:33 +00:00
|
|
|
package timeout
|
|
|
|
|
|
|
|
import (
|
2023-12-25 00:47:12 +00:00
|
|
|
"io"
|
2020-11-07 11:59:33 +00:00
|
|
|
"net/http"
|
|
|
|
"net/http/httptest"
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
"github.com/stretchr/testify/require"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestTimeoutPass(t *testing.T) {
|
|
|
|
timeout := Middleware(
|
|
|
|
SetTimeout(time.Second * 1),
|
|
|
|
)
|
|
|
|
|
|
|
|
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
time.Sleep(time.Millisecond * 100)
|
|
|
|
|
|
|
|
_, err := w.Write([]byte("resp"))
|
|
|
|
require.NoError(t, err)
|
|
|
|
})
|
|
|
|
|
|
|
|
server := httptest.NewServer(timeout(handler))
|
|
|
|
defer server.Close()
|
|
|
|
|
|
|
|
res, err := http.Get(server.URL)
|
|
|
|
assert.NoError(t, err)
|
|
|
|
defer res.Body.Close()
|
|
|
|
assert.Equal(t, http.StatusOK, res.StatusCode)
|
|
|
|
|
2023-12-25 00:47:12 +00:00
|
|
|
b, err := io.ReadAll(res.Body)
|
2020-11-07 11:59:33 +00:00
|
|
|
assert.NoError(t, err)
|
|
|
|
assert.Equal(t, "resp", string(b))
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestTimeoutTimedOut(t *testing.T) {
|
|
|
|
timeout := Middleware(
|
|
|
|
SetTimeout(time.Millisecond * 300),
|
|
|
|
)
|
|
|
|
|
|
|
|
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
select {
|
|
|
|
case <-r.Context().Done():
|
|
|
|
return
|
|
|
|
|
|
|
|
case <-time.After(time.Second * 1):
|
2023-06-25 20:10:30 +00:00
|
|
|
_, err := w.Write([]byte("resp"))
|
|
|
|
require.NoError(t, err)
|
2020-11-07 11:59:33 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
server := httptest.NewServer(timeout(handler))
|
|
|
|
defer server.Close()
|
|
|
|
|
|
|
|
res, err := http.Get(server.URL)
|
|
|
|
assert.NoError(t, err)
|
|
|
|
defer res.Body.Close()
|
|
|
|
assert.Equal(t, http.StatusGatewayTimeout, res.StatusCode)
|
|
|
|
}
|