這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
先上代碼
package mainimport ( "fmt" "net/http")func main() { resp, err := http.Get("http://mirrors.ustc.edu.cn/opensuse/distribution/12.3/iso/openSUSE-12.3-GNOME-Live-i686.iso") if err != nil { panic(err) } fmt.Println("Resp code", resp.StatusCode) resp.Body.Close() // 注意,這裡並不讀取resp.Body, 而resp.Body有大概700mb未讀取}
你猜會怎樣呢? 卡住了?!
如果你的網速夠快,你會發現, 幾十秒之後, 程式自動結束了,但如果你很不幸是小水管,你會發現一直卡住…
原因是啥呢?
http包預設會重用串連,重用串連就需要先把前一個串連的資料讀完
程式碼片段(net/http/transfer.go)
func (b *body) Close() error { if b.closed { return nil } defer func() { b.closed = true }() if b.hdr == nil && b.closing { return nil } if b.res != nil && b.res.requestBodyLimitHit { return nil } // 操,問題就在這了,讀完整個body!! if _, err := io.Copy(ioutil.Discard, b); err != nil { return err } return nil}
怎麼解決呢?
按上面程式碼片段的邏輯, 需要提前返回nil,從而避免被讀取
// b.hdr 總是為nil,因為從不設定 // 那b.closing什麼時候為true呢? if b.hdr == nil && b.closing { return nil }
讀源碼可知, b.closing依賴於transferReader的Close值
而transferReader的Close值, 是根據shouldClose方法判斷的
// 這裡的header是resp的func shouldClose(major, minor int, header Header) bool { if major < 1 { return true } else if major == 1 && minor == 0 { if !strings.Contains(strings.ToLower(header.Get("Connection")), "keep-alive") { return true } return false } else { // TODO: Should split on commas, toss surrounding white space, // and check each field. if strings.ToLower(header.Get("Connection")) == "close" { header.Del("Connection") return true } } return false}
由於沒法在這些代碼之前修改resp的header,所以修改req的header,使伺服器總是返回Connection: close
最終代碼
package mainimport ( "fmt" "net/http")func main() { req, _ := http.NewRequest("GET", "http://mirrors.ustc.edu.cn/opensuse/distribution/12.3/iso/openSUSE-12.3-GNOME-Live-i686.iso", nil) req.Header.Set("Connection", "close") resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } fmt.Println("Resp code", resp.StatusCode) resp.Body.Close()}
一個月沒寫blog了, 心情欠佳+身體抱恙 ~_~ 哎,多事的3月
2013年4月5號更新
coocood提醒到, go1.1有個新的API來完成這個蛋碎的東西
http.DefaultTransport.(*http.Transport).CancelRequest(req)
如果不是預設的DefaultTransport,就找你自己set的Transport吧