Golang http请求连续发出多个请求时导致EOF错误

标签 go

我正在尝试调试我收到的一个非常不寻常的错误,因为我编写了一个简单的 REST 库。

我使用标准的 net/http 包来发出 Get、Post、Put、Delete 请求,但是当我连续发出多个请求时,我的测试偶尔会失败。我的测试如下所示:

func TestGetObject(t *testing.T) {
    firebaseRoot := New(firebase_url)
    body, err := firebaseRoot.Get("1")
    if err != nil {
        t.Errorf("Error: %s", err)
    }
    t.Logf("%q", body)
}  

func TestPushObject(t *testing.T) {
    firebaseRoot := New(firebase_url)
    msg := Message{"testing", "1..2..3"}
    body, err := firebaseRoot.Push("/", msg)
    if err != nil {
        t.Errorf("Error: %s", err)
    }
    t.Logf("%q", body)
}

我提出这样的要求:

// Send HTTP Request, return data
func (f *firebaseRoot) SendRequest(method string, path string, body io.Reader) ([]byte, error) {
url := f.BuildURL(path)

// create a request
req, err := http.NewRequest(method, url, body)
if err != nil {
    return nil, err
}

// send JSON to firebase
resp, err := http.DefaultClient.Do(req)
if err != nil {
    return nil, err
}

if resp.StatusCode != http.StatusOK {
    return nil, fmt.Errorf("Bad HTTP Response: %v", resp.Status)
}

defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
    return nil, err
}

return b, nil
} 

有时它会起作用,但大多数时候我会遇到 1 或 2 次失败:

--- FAIL: TestGetObject (0.00 seconds)
firebase_test.go:53: Error: Get https://go-firebase-test.firebaseio.com/1.json: EOF
firebase_test.go:55: ""

--- FAIL: TestPushObject (0.00 seconds)
firebase_test.go:63: Error: Post https://go-firebase-test.firebaseio.com/.json: EOF
firebase_test.go:65: ""
FAIL
exit status 1
FAIL    github.com/chourobin/go.firebase    3.422s

当我提出超过 1 个请求时会发生故障。如果我注释掉除 PUT 请求之外的所有内容,则测试始终通过。一旦我包含第二个测试,例如 GET,其中一个或另一个失败(有时都通过)。

最佳答案

我可靠地经历了这一点。您需要将 Req.Close 设置为 true (示例中使用的延迟 resp.Body.Close() 语法是不够的)。像这样:

client := &http.Client{}
req, err := http.NewRequest(method, url, httpBody)

// NOTE this !!
req.Close = true

req.Header.Set("Content-Type", "application/json")
req.SetBasicAuth("user", "pass")
resp, err := client.Do(req)
if err != nil {
    // whatever
}
defer resp.Body.Close()

response, err = ioutil.ReadAll(resp.Body)
if err != nil {
    // Whatever
}

关于Golang http请求连续发出多个请求时导致EOF错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17714494/

相关文章:

go - 作证模拟函数在函数内部返回

go - 如何使用其中一种方法返回同一接口(interface)的对象的接口(interface)?

go - 尝试从JSON响应中获取 “Total”的值

go - 为什么 map[]interface{} 不采用 map[]SpecificInterface

go - 收到 EOF panic 错误

postgresql - 解码从 postgresql 获得的对象的 Json 数组

loops - 如何在范围循环中添加到 map 中

templates - 如何在模板中添加条件句

go - 将 []fmt.Stringer 参数传递给函数

google-app-engine -/_ah/start 在 AppEngine 上的 Go 中从未被调用