2 回答

TA貢獻1798條經驗 獲得超7個贊
檢查 的文檔Response.Body
以查看何時從中讀取可能會返回錯誤:
// Body represents the response body.
//
// The response body is streamed on demand as the Body field
// is read. If the network connection fails or the server
// terminates the response, Body.Read calls return an error.
//
// The http Client and Transport guarantee that Body is always
// non-nil, even on responses without a body or responses with
// a zero-length body. It is the caller's responsibility to
// close Body. The default HTTP client's Transport may not
// reuse HTTP/1.x "keep-alive" TCP connections if the Body is
// not read to completion and closed.
//
// The Body is automatically dechunked if the server replied
// with a "chunked" Transfer-Encoding.
Body io.ReadCloser
最簡單的方法是從測試處理程序生成無效的 HTTP 響應。
怎么做?方法有很多種,一個簡單的就是“騙”內容長度:
handler := func(w http.ResponseWriter, r *http.Request) {
? ? w.Header().Set("Content-Length", "1")
}
這個處理程序告訴它有 1 個字節的主體,但實際上它沒有發送任何內容。因此在另一端(客戶端)嘗試從中讀取 1 個字節時,顯然不會成功,并將導致以下錯誤:
Unable to read from body unexpected EOF

TA貢獻1802條經驗 獲得超5個贊
要擴展 icza 的精彩答案,您還可以使用httptest.Server對象執行此操作:
bodyErrorServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Length", "1")
}))
defer bodyErrorServer.Close()
然后你可以bodyErrorServer.URL像往常一樣通過你的測試,你總是會得到一個 EOF 錯誤:
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func getBodyFromURL(service string, clientTimeout int) (string, error) {
var netClient = &http.Client{
Timeout: time.Duration(clientTimeout) * time.Millisecond,
}
rsp, err := netClient.Get(service)
if err != nil {
return "", err
}
defer rsp.Body.Close()
if rsp.StatusCode != 200 {
return "", fmt.Errorf("HTTP request error. Response code: %d", rsp.StatusCode)
}
buf, err := ioutil.ReadAll(rsp.Body)
if err != nil {
return "", err
}
return string(bytes.TrimSpace(buf)), nil
}
func TestBodyError(t *testing.T) {
bodyErrorServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Length", "1")
}))
_, err := getBodyFromURL(bodyErrorServer.URL, 1000)
if err.Error() != "unexpected EOF" {
t.Error("GOT AN ERROR")
} else if err == nil {
t.Error("GOT NO ERROR, THATS WRONG!")
} else {
t.Log("Got an unexpected EOF as expected, horray!")
}
}
此處的游樂場示例:https ://play.golang.org/p/JzPmatibgZn
- 2 回答
- 0 關注
- 146 瀏覽
添加回答
舉報