去Reader.read(); 如何获得内容而不重复?

I've started studying Go recently as a side project and have been trying to get a better handle around the Reader interface. Specifically, I'm trying to get contents from a website, and then reading it to a bytes slice.

I am aware that the ioutils.ReadAll function is the canonical way to get the data, but I'm curious why the original function I wrote has repeated content at the end of the output.

Code: package main

import(
    "net/http"
    "fmt"
)

func main() {
    // retrieve url from hacker news.
    resp, err := http.Get("http://news.ycombinator.com/")
    if err != nil {
        // handle error
    }
    defer resp.Body.Close()
    text := make([]byte, 500)
    buf := make([]byte, 200)
    i, _ := resp.Body.Read(buf)
    for i != 0 {
        text = append(text,buf...)
        i, _ = resp.Body.Read(buf)
    }
    fmt.Println(resp.ContentLength)
    fmt.Println(resp.Status)
    fmt.Printf("%q
", text)

}

Content:

         (...)Search:
  <input type=\"text\" name=\"q\" value=\"\" size=\"17\" autocorrect=\"off\" spellcheck=\"false\" autocapitalize=\"off\" autocomplete=\"false\"></form>
            </center></td></tr>      
         </table></center></body></html>
put type=\"text\" name=\"q\" value=\"\" "

As you can see, for a reason I don't quite understand, one part of the text is repeated at the end after the closed tags; 'nput type=\"text\" name=\"q\" value=\"\" "'.

Maybe this is something related to the buffer not being cleared maybe? Could anyone offer some insight as to what I am getting wrong?

查看全部
doujuncuo9339
doujuncuo9339
2016/05/27 01:11
  • web
  • html
  • buffer
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复