I am trying to add a timeout
option to a library in Go and have written the below test to mimic the behavior.
func TestClientTimeout(t *testing.T) {
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
d := map[string]interface{}{
"id": "12",
"scope": "test-scope",
}
time.Sleep(100 * time.Millisecond)
e := json.NewEncoder(w)
err := e.Encode(&d)
if err != nil {
t.Error(err)
}
w.WriteHeader(http.StatusOK)
}))
url := backend.URL
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
req, err := http.NewRequest("GET", url, nil)
if err != nil {
t.Error("Request error", err)
}
resp, err := http.DefaultClient.Do(req.WithContext(ctx))
if err != nil {
t.Error("Response error", err)
}
defer resp.Body.Close()
t.Log(">>>>>>>Response is: ", resp)
}
But I always get below error, instead of http.StatusGatewayTimeout
=== RUN TestClientTimeout
--- FAIL: TestClientTimeout (0.05s)
client_test.go:37: Timestamp before req 2018-07-13 09:10:14.936898 +0200 CEST m=+0.002048937 client_test.go:40: Response error Get http://127.0.0.1:49597: context deadline exceeded
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
panic: runtime error: invalid memory address or nil pointer dereference
How do I fix this test, to return response with http.StatusGatewayTimeout
(504) status code?