【发布时间】:2018-12-21 12:23:30
【问题描述】:
我正在尝试向 Go 中的库添加 timeout 选项,并编写了以下测试来模拟该行为。
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)
}
但我总是遇到错误,而不是http.StatusGatewayTimeout
=== RUN TestClientTimeout
--- 失败: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恐慌:运行时错误:无效的内存地址或 nil 指针取消引用 [已恢复]
恐慌:运行时错误:无效的内存地址或 nil 指针取消引用
如何修复此测试,以返回带有http.StatusGatewayTimeout(504) 状态码的响应?
【问题讨论】: