douchen7555 2014-05-31 07:35
浏览 686

ioutil.ReadAll(response.Body)永远阻止-Golang

tr := &http.Transport{
    TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
response, err := client.Get(link)
if err != nil {
    fmt.Println(err)
}
defer response.Body.Close()

//block forever at the next line
content, _ = ioutil.ReadAll(response.Body)

The above is my code to read content from a webpage which resides in a loop. I found sometimes the line ioutil.ReadAll(response.Body) will block forever. This happens randomly, however, it almost always happens on this webpage: http://xkcd.com/55 . It's very interesting that when I do curl http://xkcd.com/55, it returns nothing, however, wget http://xkcd.com/55 returns the whole webpage.

  • 写回答

4条回答 默认 最新

  • douguxun6866 2014-06-01 11:41
    关注

    Your code should work as expected. I am guessing, its a network issue. Try setting a higher timeout.

    package main
    
    import (
        "crypto/tls"
        "fmt"
        "io/ioutil"
        "net/http"
    )
    
    func main() {
    
        link := "http://xkcd.com/55"
    
        tr := &http.Transport{
            TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
        }
        client := &http.Client{Transport: tr}
        response, err := client.Get(link)
        if err != nil {
            fmt.Println(err)
        }
        defer response.Body.Close()
    
        //block forever at the next line
        content, _ := ioutil.ReadAll(response.Body)
    
        fmt.Println(string(content))
    
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr