doushouxie7064 2017-11-24 20:22
浏览 132

在循环中进入bufio ReadString是无限的

I have the next code:

resp, err := http.Get("https://www.google.com")

if err != nil{
    panic(err)
}

r := bufio.NewReader(resp.Body)

for v, e := r.ReadString('
'); e == nil; {
    fmt.Println(v)
}

So, I want to read responce body in loop but reader r reads first line of Body infinitely.

While in the same time, this code works fine:

v, e := r.ReadString('
')
for e == nil {
    fmt.Println(v)
    v, e = r.ReadString('
')
}

Can someone explain why the first solution has such behaviour?

  • 写回答

2条回答 默认 最新

  • douxiaomang5640 2017-11-24 20:29
    关注

    Structure of the loop is:

    for init; condition; post { }
    

    The init part of the loop is called only once, at the beginning. That means that the...

    v, e := r.ReadString('
    ')
    

    ...part from your loop is called only once, which explains why your loop implementation reads only the first line from r and why e is always nil, resulting in an infinite loop.


    You may want to do something like this instead:

    for v, e := "", (error)(nil); e == nil; {
        v, e = r.ReadString('
    ')
        fmt.Println(v)
    }
    

    Or if that looks weird to you, something like this:

    var v string
    var e error
    for ; e == nil; {
        v, e = r.ReadString('
    ')
        fmt.Println(v)
    }
    

    More info here:

    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大